cmOutputRequiredFilesCommand.cxx 15 KB

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