cmOutputRequiredFilesCommand.cxx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. cmTargets& targets = this->Makefile->GetTargets();
  98. for (auto const& target : targets) {
  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;
  107. cmSystemTools::ExpandListArgument(incDirs, includes);
  108. for (std::string& path : includes) {
  109. this->Makefile->ExpandVariablesInString(path);
  110. if (uniqueIncludes.insert(path).second) {
  111. orderedAndUniqueIncludes.push_back(path);
  112. }
  113. }
  114. }
  115. for (std::string const& inc : orderedAndUniqueIncludes) {
  116. this->AddSearchPath(inc);
  117. }
  118. }
  119. /**
  120. * Add a directory to the search path for include files.
  121. */
  122. void AddSearchPath(const std::string& path)
  123. {
  124. this->IncludeDirectories.push_back(path);
  125. }
  126. /**
  127. * Generate dependencies for the file given. Returns a pointer to
  128. * the cmDependInformation object for the file.
  129. */
  130. const cmDependInformation* FindDependencies(const char* file)
  131. {
  132. cmDependInformation* info = this->GetDependInformation(file, nullptr);
  133. this->GenerateDependInformation(info);
  134. return info;
  135. }
  136. protected:
  137. /**
  138. * Compute the depend information for this class.
  139. */
  140. void DependWalk(cmDependInformation* info)
  141. {
  142. cmsys::ifstream fin(info->FullPath.c_str());
  143. if (!fin) {
  144. cmSystemTools::Error("error can not open ", info->FullPath.c_str());
  145. return;
  146. }
  147. std::string line;
  148. while (cmSystemTools::GetLineFromStream(fin, line)) {
  149. if (cmHasLiteralPrefix(line, "#include")) {
  150. // if it is an include line then create a string class
  151. size_t qstart = line.find('\"', 8);
  152. size_t qend;
  153. // if a quote is not found look for a <
  154. if (qstart == std::string::npos) {
  155. qstart = line.find('<', 8);
  156. // if a < is not found then move on
  157. if (qstart == std::string::npos) {
  158. cmSystemTools::Error("unknown include directive ", line.c_str());
  159. continue;
  160. }
  161. qend = line.find('>', qstart + 1);
  162. } else {
  163. qend = line.find('\"', qstart + 1);
  164. }
  165. // extract the file being included
  166. std::string includeFile = line.substr(qstart + 1, qend - qstart - 1);
  167. // see if the include matches the regular expression
  168. if (!this->IncludeFileRegularExpression.find(includeFile)) {
  169. if (this->Verbose) {
  170. std::string message = "Skipping ";
  171. message += includeFile;
  172. message += " for file ";
  173. message += info->FullPath;
  174. cmSystemTools::Error(message);
  175. }
  176. continue;
  177. }
  178. // Add this file and all its dependencies.
  179. this->AddDependency(info, includeFile.c_str());
  180. /// add the cxx file if it exists
  181. std::string cxxFile = includeFile;
  182. std::string::size_type pos = cxxFile.rfind('.');
  183. if (pos != std::string::npos) {
  184. std::string root = cxxFile.substr(0, pos);
  185. cxxFile = root + ".cxx";
  186. bool found = false;
  187. // try jumping to .cxx .cpp and .c in order
  188. if (cmSystemTools::FileExists(cxxFile)) {
  189. found = true;
  190. }
  191. for (std::string path : this->IncludeDirectories) {
  192. path = path + "/";
  193. path = path + cxxFile;
  194. if (cmSystemTools::FileExists(path)) {
  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 path : this->IncludeDirectories) {
  204. path = path + "/";
  205. path = path + cxxFile;
  206. if (cmSystemTools::FileExists(path)) {
  207. found = true;
  208. }
  209. }
  210. }
  211. if (!found) {
  212. cxxFile = root + ".c";
  213. if (cmSystemTools::FileExists(cxxFile)) {
  214. found = true;
  215. }
  216. for (std::string path : this->IncludeDirectories) {
  217. path = path + "/";
  218. path = path + cxxFile;
  219. if (cmSystemTools::FileExists(path)) {
  220. found = true;
  221. }
  222. }
  223. }
  224. if (!found) {
  225. cxxFile = root + ".txx";
  226. if (cmSystemTools::FileExists(cxxFile)) {
  227. found = true;
  228. }
  229. for (std::string path : this->IncludeDirectories) {
  230. path = path + "/";
  231. path = path + cxxFile;
  232. if (cmSystemTools::FileExists(path)) {
  233. found = true;
  234. }
  235. }
  236. }
  237. if (found) {
  238. this->AddDependency(info, cxxFile.c_str());
  239. }
  240. }
  241. }
  242. }
  243. }
  244. /**
  245. * Add a dependency. Possibly walk it for more dependencies.
  246. */
  247. void AddDependency(cmDependInformation* info, const char* file)
  248. {
  249. cmDependInformation* dependInfo =
  250. this->GetDependInformation(file, info->PathOnly.c_str());
  251. this->GenerateDependInformation(dependInfo);
  252. info->AddDependencies(dependInfo);
  253. }
  254. /**
  255. * Fill in the given object with dependency information. If the
  256. * information is already complete, nothing is done.
  257. */
  258. void GenerateDependInformation(cmDependInformation* info)
  259. {
  260. // If dependencies are already done, stop now.
  261. if (info->DependDone) {
  262. return;
  263. }
  264. // Make sure we don't visit the same file more than once.
  265. info->DependDone = true;
  266. const char* path = info->FullPath.c_str();
  267. if (!path) {
  268. cmSystemTools::Error(
  269. "Attempt to find dependencies for file without path!");
  270. return;
  271. }
  272. bool found = false;
  273. // If the file exists, use it to find dependency information.
  274. if (cmSystemTools::FileExists(path, true)) {
  275. // Use the real file to find its dependencies.
  276. this->DependWalk(info);
  277. found = true;
  278. }
  279. // See if the cmSourceFile for it has any files specified as
  280. // dependency hints.
  281. if (info->SourceFile != nullptr) {
  282. // Get the cmSourceFile corresponding to this.
  283. const cmSourceFile& cFile = *(info->SourceFile);
  284. // See if there are any hints for finding dependencies for the missing
  285. // file.
  286. if (!cFile.GetDepends().empty()) {
  287. // Dependency hints have been given. Use them to begin the
  288. // recursion.
  289. for (std::string const& file : cFile.GetDepends()) {
  290. this->AddDependency(info, file.c_str());
  291. }
  292. // Found dependency information. We are done.
  293. found = true;
  294. }
  295. }
  296. if (!found) {
  297. // Try to find the file amongst the sources
  298. cmSourceFile* srcFile = this->Makefile->GetSource(
  299. cmSystemTools::GetFilenameWithoutExtension(path));
  300. if (srcFile) {
  301. if (srcFile->GetFullPath() == path) {
  302. found = true;
  303. } else {
  304. // try to guess which include path to use
  305. for (std::string incpath : this->IncludeDirectories) {
  306. if (!incpath.empty() && incpath.back() != '/') {
  307. incpath = incpath + "/";
  308. }
  309. incpath = incpath + path;
  310. if (srcFile->GetFullPath() == incpath) {
  311. // set the path to the guessed path
  312. info->FullPath = incpath;
  313. found = true;
  314. }
  315. }
  316. }
  317. }
  318. }
  319. if (!found) {
  320. // Couldn't find any dependency information.
  321. if (this->ComplainFileRegularExpression.find(info->IncludeName)) {
  322. cmSystemTools::Error("error cannot find dependencies for ", path);
  323. } else {
  324. // Destroy the name of the file so that it won't be output as a
  325. // dependency.
  326. info->FullPath.clear();
  327. }
  328. }
  329. }
  330. /**
  331. * Get an instance of cmDependInformation corresponding to the given file
  332. * name.
  333. */
  334. cmDependInformation* GetDependInformation(const char* file,
  335. const char* extraPath)
  336. {
  337. // Get the full path for the file so that lookup is unambiguous.
  338. std::string fullPath = this->FullPath(file, extraPath);
  339. // Try to find the file's instance of cmDependInformation.
  340. DependInformationMapType::const_iterator result =
  341. this->DependInformationMap.find(fullPath);
  342. if (result != this->DependInformationMap.end()) {
  343. // Found an instance, return it.
  344. return result->second;
  345. }
  346. // Didn't find an instance. Create a new one and save it.
  347. cmDependInformation* info = new cmDependInformation;
  348. info->FullPath = fullPath;
  349. info->PathOnly = cmSystemTools::GetFilenamePath(fullPath);
  350. info->IncludeName = file;
  351. this->DependInformationMap[fullPath] = info;
  352. return info;
  353. }
  354. /**
  355. * Find the full path name for the given file name.
  356. * This uses the include directories.
  357. * TODO: Cache path conversions to reduce FileExists calls.
  358. */
  359. std::string FullPath(const char* fname, const char* extraPath)
  360. {
  361. DirectoryToFileToPathMapType::iterator m;
  362. if (extraPath) {
  363. m = this->DirectoryToFileToPathMap.find(extraPath);
  364. } else {
  365. m = this->DirectoryToFileToPathMap.find("");
  366. }
  367. if (m != this->DirectoryToFileToPathMap.end()) {
  368. FileToPathMapType& map = m->second;
  369. FileToPathMapType::iterator p = map.find(fname);
  370. if (p != map.end()) {
  371. return p->second;
  372. }
  373. }
  374. if (cmSystemTools::FileExists(fname, true)) {
  375. std::string fp = cmSystemTools::CollapseFullPath(fname);
  376. this->DirectoryToFileToPathMap[extraPath ? extraPath : ""][fname] = fp;
  377. return fp;
  378. }
  379. for (std::string path : this->IncludeDirectories) {
  380. if (!path.empty() && path.back() != '/') {
  381. path = path + "/";
  382. }
  383. path = path + fname;
  384. if (cmSystemTools::FileExists(path, true) &&
  385. !cmSystemTools::FileIsDirectory(path)) {
  386. std::string fp = cmSystemTools::CollapseFullPath(path);
  387. this->DirectoryToFileToPathMap[extraPath ? extraPath : ""][fname] = fp;
  388. return fp;
  389. }
  390. }
  391. if (extraPath) {
  392. std::string path = extraPath;
  393. if (!path.empty() && path.back() != '/') {
  394. path = path + "/";
  395. }
  396. path = path + fname;
  397. if (cmSystemTools::FileExists(path, true) &&
  398. !cmSystemTools::FileIsDirectory(path)) {
  399. std::string fp = cmSystemTools::CollapseFullPath(path);
  400. this->DirectoryToFileToPathMap[extraPath][fname] = fp;
  401. return fp;
  402. }
  403. }
  404. // Couldn't find the file.
  405. return std::string(fname);
  406. }
  407. cmMakefile* Makefile;
  408. bool Verbose;
  409. cmsys::RegularExpression IncludeFileRegularExpression;
  410. cmsys::RegularExpression ComplainFileRegularExpression;
  411. std::vector<std::string> IncludeDirectories;
  412. typedef std::map<std::string, std::string> FileToPathMapType;
  413. typedef std::map<std::string, FileToPathMapType>
  414. DirectoryToFileToPathMapType;
  415. typedef std::map<std::string, cmDependInformation*> DependInformationMapType;
  416. DependInformationMapType DependInformationMap;
  417. DirectoryToFileToPathMapType DirectoryToFileToPathMap;
  418. };
  419. // cmOutputRequiredFilesCommand
  420. bool cmOutputRequiredFilesCommand::InitialPass(
  421. std::vector<std::string> const& args, cmExecutionStatus&)
  422. {
  423. if (args.size() != 2) {
  424. this->SetError("called with incorrect number of arguments");
  425. return false;
  426. }
  427. // store the arg for final pass
  428. this->File = args[0];
  429. this->OutputFile = args[1];
  430. // compute the list of files
  431. cmLBDepend md;
  432. md.SetMakefile(this->Makefile);
  433. md.AddSearchPath(this->Makefile->GetCurrentSourceDirectory());
  434. // find the depends for a file
  435. const cmDependInformation* info = md.FindDependencies(this->File.c_str());
  436. if (info) {
  437. // write them out
  438. FILE* fout = cmsys::SystemTools::Fopen(this->OutputFile, "w");
  439. if (!fout) {
  440. std::string err = "Can not open output file: ";
  441. err += this->OutputFile;
  442. this->SetError(err);
  443. return false;
  444. }
  445. std::set<cmDependInformation const*> visited;
  446. this->ListDependencies(info, fout, &visited);
  447. fclose(fout);
  448. }
  449. return true;
  450. }
  451. void cmOutputRequiredFilesCommand::ListDependencies(
  452. cmDependInformation const* info, FILE* fout,
  453. std::set<cmDependInformation const*>* visited)
  454. {
  455. // add info to the visited set
  456. visited->insert(info);
  457. // now recurse with info's dependencies
  458. for (cmDependInformation* d : info->DependencySet) {
  459. if (visited->find(d) == visited->end()) {
  460. if (!info->FullPath.empty()) {
  461. std::string tmp = d->FullPath;
  462. std::string::size_type pos = tmp.rfind('.');
  463. if (pos != std::string::npos && (tmp.substr(pos) != ".h")) {
  464. tmp = tmp.substr(0, pos);
  465. fprintf(fout, "%s\n", d->FullPath.c_str());
  466. }
  467. }
  468. this->ListDependencies(d, fout, visited);
  469. }
  470. }
  471. }