cmOutputRequiredFilesCommand.cxx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmOutputRequiredFilesCommand.h"
  4. #include "cmsys/FStream.hxx"
  5. #include "cmsys/RegularExpression.hxx"
  6. #include <map>
  7. #include <utility>
  8. #include "cmAlgorithms.h"
  9. #include "cmGeneratorExpression.h"
  10. #include "cmMakefile.h"
  11. #include "cmSourceFile.h"
  12. #include "cmSystemTools.h"
  13. #include "cmTarget.h"
  14. class cmExecutionStatus;
  15. /** \class cmDependInformation
  16. * \brief Store dependency information for a single source file.
  17. *
  18. * This structure stores the depend information for a single source file.
  19. */
  20. class cmDependInformation
  21. {
  22. public:
  23. /**
  24. * Construct with dependency generation marked not done; instance
  25. * not placed in cmMakefile's list.
  26. */
  27. cmDependInformation() = default;
  28. /**
  29. * The set of files on which this one depends.
  30. */
  31. typedef std::set<cmDependInformation*> DependencySetType;
  32. DependencySetType DependencySet;
  33. /**
  34. * This flag indicates whether dependency checking has been
  35. * performed for this file.
  36. */
  37. bool DependDone = false;
  38. /**
  39. * If this object corresponds to a cmSourceFile instance, this points
  40. * to it.
  41. */
  42. const cmSourceFile* SourceFile = nullptr;
  43. /**
  44. * Full path to this file.
  45. */
  46. std::string FullPath;
  47. /**
  48. * Full path not including file name.
  49. */
  50. std::string PathOnly;
  51. /**
  52. * Name used to #include this file.
  53. */
  54. std::string IncludeName;
  55. /**
  56. * This method adds the dependencies of another file to this one.
  57. */
  58. void AddDependencies(cmDependInformation* info)
  59. {
  60. if (this != info) {
  61. this->DependencySet.insert(info);
  62. }
  63. }
  64. };
  65. class cmLBDepend
  66. {
  67. public:
  68. /**
  69. * Construct the object with verbose turned off.
  70. */
  71. cmLBDepend()
  72. {
  73. this->Verbose = false;
  74. this->IncludeFileRegularExpression.compile("^.*$");
  75. this->ComplainFileRegularExpression.compile("^$");
  76. }
  77. /**
  78. * Destructor.
  79. */
  80. ~cmLBDepend() { cmDeleteAll(this->DependInformationMap); }
  81. cmLBDepend(const cmLBDepend&) = delete;
  82. cmLBDepend& operator=(const cmLBDepend&) = delete;
  83. /**
  84. * Set the makefile that is used as a source of classes.
  85. */
  86. void SetMakefile(cmMakefile* makefile)
  87. {
  88. this->Makefile = makefile;
  89. // Now extract the include file regular expression from the makefile.
  90. this->IncludeFileRegularExpression.compile(
  91. this->Makefile->GetIncludeRegularExpression());
  92. this->ComplainFileRegularExpression.compile(
  93. this->Makefile->GetComplainRegularExpression());
  94. // Now extract any include paths from the targets
  95. std::set<std::string> uniqueIncludes;
  96. std::vector<std::string> orderedAndUniqueIncludes;
  97. for (auto const& target : this->Makefile->GetTargets()) {
  98. const char* incDirProp =
  99. target.second.GetProperty("INCLUDE_DIRECTORIES");
  100. if (!incDirProp) {
  101. continue;
  102. }
  103. std::string incDirs = cmGeneratorExpression::Preprocess(
  104. incDirProp, cmGeneratorExpression::StripAllGeneratorExpressions);
  105. std::vector<std::string> includes;
  106. cmSystemTools::ExpandListArgument(incDirs, includes);
  107. for (std::string& path : includes) {
  108. this->Makefile->ExpandVariablesInString(path);
  109. if (uniqueIncludes.insert(path).second) {
  110. orderedAndUniqueIncludes.push_back(path);
  111. }
  112. }
  113. }
  114. for (std::string const& inc : orderedAndUniqueIncludes) {
  115. this->AddSearchPath(inc);
  116. }
  117. }
  118. /**
  119. * Add a directory to the search path for include files.
  120. */
  121. void AddSearchPath(const std::string& path)
  122. {
  123. this->IncludeDirectories.push_back(path);
  124. }
  125. /**
  126. * Generate dependencies for the file given. Returns a pointer to
  127. * the cmDependInformation object for the file.
  128. */
  129. const cmDependInformation* FindDependencies(const char* file)
  130. {
  131. cmDependInformation* info = this->GetDependInformation(file, nullptr);
  132. this->GenerateDependInformation(info);
  133. return info;
  134. }
  135. protected:
  136. /**
  137. * Compute the depend information for this class.
  138. */
  139. void DependWalk(cmDependInformation* info)
  140. {
  141. cmsys::ifstream fin(info->FullPath.c_str());
  142. if (!fin) {
  143. cmSystemTools::Error("error can not open " + info->FullPath);
  144. return;
  145. }
  146. std::string line;
  147. while (cmSystemTools::GetLineFromStream(fin, line)) {
  148. if (cmHasLiteralPrefix(line, "#include")) {
  149. // if it is an include line then create a string class
  150. size_t qstart = line.find('\"', 8);
  151. size_t qend;
  152. // if a quote is not found look for a <
  153. if (qstart == std::string::npos) {
  154. qstart = line.find('<', 8);
  155. // if a < is not found then move on
  156. if (qstart == std::string::npos) {
  157. cmSystemTools::Error("unknown include directive " + line);
  158. continue;
  159. }
  160. qend = line.find('>', qstart + 1);
  161. } else {
  162. qend = line.find('\"', qstart + 1);
  163. }
  164. // extract the file being included
  165. std::string includeFile = line.substr(qstart + 1, qend - qstart - 1);
  166. // see if the include matches the regular expression
  167. if (!this->IncludeFileRegularExpression.find(includeFile)) {
  168. if (this->Verbose) {
  169. std::string message = "Skipping ";
  170. message += includeFile;
  171. message += " for file ";
  172. message += info->FullPath;
  173. cmSystemTools::Error(message);
  174. }
  175. continue;
  176. }
  177. // Add this file and all its dependencies.
  178. this->AddDependency(info, includeFile.c_str());
  179. /// add the cxx file if it exists
  180. std::string cxxFile = includeFile;
  181. std::string::size_type pos = cxxFile.rfind('.');
  182. if (pos != std::string::npos) {
  183. std::string root = cxxFile.substr(0, pos);
  184. cxxFile = root + ".cxx";
  185. bool found = false;
  186. // try jumping to .cxx .cpp and .c in order
  187. if (cmSystemTools::FileExists(cxxFile)) {
  188. found = true;
  189. }
  190. for (std::string path : this->IncludeDirectories) {
  191. path = path + "/";
  192. path = path + cxxFile;
  193. if (cmSystemTools::FileExists(path)) {
  194. found = true;
  195. }
  196. }
  197. if (!found) {
  198. cxxFile = root + ".cpp";
  199. if (cmSystemTools::FileExists(cxxFile)) {
  200. found = true;
  201. }
  202. for (std::string path : this->IncludeDirectories) {
  203. path = path + "/";
  204. path = path + cxxFile;
  205. if (cmSystemTools::FileExists(path)) {
  206. found = true;
  207. }
  208. }
  209. }
  210. if (!found) {
  211. cxxFile = root + ".c";
  212. if (cmSystemTools::FileExists(cxxFile)) {
  213. found = true;
  214. }
  215. for (std::string path : this->IncludeDirectories) {
  216. path = path + "/";
  217. path = path + cxxFile;
  218. if (cmSystemTools::FileExists(path)) {
  219. found = true;
  220. }
  221. }
  222. }
  223. if (!found) {
  224. cxxFile = root + ".txx";
  225. if (cmSystemTools::FileExists(cxxFile)) {
  226. found = true;
  227. }
  228. for (std::string path : this->IncludeDirectories) {
  229. path = path + "/";
  230. path = path + cxxFile;
  231. if (cmSystemTools::FileExists(path)) {
  232. found = true;
  233. }
  234. }
  235. }
  236. if (found) {
  237. this->AddDependency(info, cxxFile.c_str());
  238. }
  239. }
  240. }
  241. }
  242. }
  243. /**
  244. * Add a dependency. Possibly walk it for more dependencies.
  245. */
  246. void AddDependency(cmDependInformation* info, const char* file)
  247. {
  248. cmDependInformation* dependInfo =
  249. this->GetDependInformation(file, info->PathOnly.c_str());
  250. this->GenerateDependInformation(dependInfo);
  251. info->AddDependencies(dependInfo);
  252. }
  253. /**
  254. * Fill in the given object with dependency information. If the
  255. * information is already complete, nothing is done.
  256. */
  257. void GenerateDependInformation(cmDependInformation* info)
  258. {
  259. // If dependencies are already done, stop now.
  260. if (info->DependDone) {
  261. return;
  262. }
  263. // Make sure we don't visit the same file more than once.
  264. info->DependDone = true;
  265. const std::string& path = info->FullPath;
  266. if (path.empty()) {
  267. cmSystemTools::Error(
  268. "Attempt to find dependencies for file without path!");
  269. return;
  270. }
  271. bool found = false;
  272. // If the file exists, use it to find dependency information.
  273. if (cmSystemTools::FileExists(path, true)) {
  274. // Use the real file to find its dependencies.
  275. this->DependWalk(info);
  276. found = true;
  277. }
  278. // See if the cmSourceFile for it has any files specified as
  279. // dependency hints.
  280. if (info->SourceFile != nullptr) {
  281. // Get the cmSourceFile corresponding to this.
  282. const cmSourceFile& cFile = *(info->SourceFile);
  283. // See if there are any hints for finding dependencies for the missing
  284. // file.
  285. if (!cFile.GetDepends().empty()) {
  286. // Dependency hints have been given. Use them to begin the
  287. // recursion.
  288. for (std::string const& file : cFile.GetDepends()) {
  289. this->AddDependency(info, file.c_str());
  290. }
  291. // Found dependency information. We are done.
  292. found = true;
  293. }
  294. }
  295. if (!found) {
  296. // Try to find the file amongst the sources
  297. cmSourceFile* srcFile = this->Makefile->GetSource(
  298. cmSystemTools::GetFilenameWithoutExtension(path));
  299. if (srcFile) {
  300. if (srcFile->GetFullPath() == path) {
  301. found = true;
  302. } else {
  303. // try to guess which include path to use
  304. for (std::string incpath : this->IncludeDirectories) {
  305. if (!incpath.empty() && incpath.back() != '/') {
  306. incpath = incpath + "/";
  307. }
  308. incpath = incpath + path;
  309. if (srcFile->GetFullPath() == incpath) {
  310. // set the path to the guessed path
  311. info->FullPath = incpath;
  312. found = true;
  313. }
  314. }
  315. }
  316. }
  317. }
  318. if (!found) {
  319. // Couldn't find any dependency information.
  320. if (this->ComplainFileRegularExpression.find(info->IncludeName)) {
  321. cmSystemTools::Error("error cannot find dependencies for " + path);
  322. } else {
  323. // Destroy the name of the file so that it won't be output as a
  324. // dependency.
  325. info->FullPath.clear();
  326. }
  327. }
  328. }
  329. /**
  330. * Get an instance of cmDependInformation corresponding to the given file
  331. * name.
  332. */
  333. cmDependInformation* GetDependInformation(const char* file,
  334. const char* extraPath)
  335. {
  336. // Get the full path for the file so that lookup is unambiguous.
  337. std::string fullPath = this->FullPath(file, extraPath);
  338. // Try to find the file's instance of cmDependInformation.
  339. DependInformationMapType::const_iterator result =
  340. this->DependInformationMap.find(fullPath);
  341. if (result != this->DependInformationMap.end()) {
  342. // Found an instance, return it.
  343. return result->second;
  344. }
  345. // Didn't find an instance. Create a new one and save it.
  346. cmDependInformation* info = new cmDependInformation;
  347. info->FullPath = fullPath;
  348. info->PathOnly = cmSystemTools::GetFilenamePath(fullPath);
  349. info->IncludeName = file;
  350. this->DependInformationMap[fullPath] = info;
  351. return info;
  352. }
  353. /**
  354. * Find the full path name for the given file name.
  355. * This uses the include directories.
  356. * TODO: Cache path conversions to reduce FileExists calls.
  357. */
  358. std::string FullPath(const char* fname, const char* extraPath)
  359. {
  360. DirectoryToFileToPathMapType::iterator m;
  361. if (extraPath) {
  362. m = this->DirectoryToFileToPathMap.find(extraPath);
  363. } else {
  364. m = this->DirectoryToFileToPathMap.find("");
  365. }
  366. if (m != this->DirectoryToFileToPathMap.end()) {
  367. FileToPathMapType& map = m->second;
  368. FileToPathMapType::iterator p = map.find(fname);
  369. if (p != map.end()) {
  370. return p->second;
  371. }
  372. }
  373. if (cmSystemTools::FileExists(fname, true)) {
  374. std::string fp = cmSystemTools::CollapseFullPath(fname);
  375. this->DirectoryToFileToPathMap[extraPath ? extraPath : ""][fname] = fp;
  376. return fp;
  377. }
  378. for (std::string path : this->IncludeDirectories) {
  379. if (!path.empty() && path.back() != '/') {
  380. path = path + "/";
  381. }
  382. path = path + fname;
  383. if (cmSystemTools::FileExists(path, true) &&
  384. !cmSystemTools::FileIsDirectory(path)) {
  385. std::string fp = cmSystemTools::CollapseFullPath(path);
  386. this->DirectoryToFileToPathMap[extraPath ? extraPath : ""][fname] = fp;
  387. return fp;
  388. }
  389. }
  390. if (extraPath) {
  391. std::string path = extraPath;
  392. if (!path.empty() && path.back() != '/') {
  393. path = path + "/";
  394. }
  395. path = path + fname;
  396. if (cmSystemTools::FileExists(path, true) &&
  397. !cmSystemTools::FileIsDirectory(path)) {
  398. std::string fp = cmSystemTools::CollapseFullPath(path);
  399. this->DirectoryToFileToPathMap[extraPath][fname] = fp;
  400. return fp;
  401. }
  402. }
  403. // Couldn't find the file.
  404. return std::string(fname);
  405. }
  406. cmMakefile* Makefile;
  407. bool Verbose;
  408. cmsys::RegularExpression IncludeFileRegularExpression;
  409. cmsys::RegularExpression ComplainFileRegularExpression;
  410. std::vector<std::string> IncludeDirectories;
  411. typedef std::map<std::string, std::string> FileToPathMapType;
  412. typedef std::map<std::string, FileToPathMapType>
  413. DirectoryToFileToPathMapType;
  414. typedef std::map<std::string, cmDependInformation*> DependInformationMapType;
  415. DependInformationMapType DependInformationMap;
  416. DirectoryToFileToPathMapType DirectoryToFileToPathMap;
  417. };
  418. // cmOutputRequiredFilesCommand
  419. bool cmOutputRequiredFilesCommand::InitialPass(
  420. std::vector<std::string> const& args, cmExecutionStatus&)
  421. {
  422. if (args.size() != 2) {
  423. this->SetError("called with incorrect number of arguments");
  424. return false;
  425. }
  426. // store the arg for final pass
  427. this->File = args[0];
  428. this->OutputFile = args[1];
  429. // compute the list of files
  430. cmLBDepend md;
  431. md.SetMakefile(this->Makefile);
  432. md.AddSearchPath(this->Makefile->GetCurrentSourceDirectory());
  433. // find the depends for a file
  434. const cmDependInformation* info = md.FindDependencies(this->File.c_str());
  435. if (info) {
  436. // write them out
  437. FILE* fout = cmsys::SystemTools::Fopen(this->OutputFile, "w");
  438. if (!fout) {
  439. std::string err = "Can not open output file: ";
  440. err += this->OutputFile;
  441. this->SetError(err);
  442. return false;
  443. }
  444. std::set<cmDependInformation const*> visited;
  445. this->ListDependencies(info, fout, &visited);
  446. fclose(fout);
  447. }
  448. return true;
  449. }
  450. void cmOutputRequiredFilesCommand::ListDependencies(
  451. cmDependInformation const* info, FILE* fout,
  452. std::set<cmDependInformation const*>* visited)
  453. {
  454. // add info to the visited set
  455. visited->insert(info);
  456. // now recurse with info's dependencies
  457. for (cmDependInformation* d : info->DependencySet) {
  458. if (visited->find(d) == visited->end()) {
  459. if (!info->FullPath.empty()) {
  460. std::string tmp = d->FullPath;
  461. std::string::size_type pos = tmp.rfind('.');
  462. if (pos != std::string::npos && (tmp.substr(pos) != ".h")) {
  463. tmp = tmp.substr(0, pos);
  464. fprintf(fout, "%s\n", d->FullPath.c_str());
  465. }
  466. }
  467. this->ListDependencies(d, fout, visited);
  468. }
  469. }
  470. }