cmOutputRequiredFilesCommand.cxx 15 KB

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