cmOutputRequiredFilesCommand.cxx 15 KB

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