cmOutputRequiredFilesCommand.cxx 15 KB

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