cmDependsC.cxx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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 "cmDependsC.h"
  4. #include <utility>
  5. #include "cmsys/FStream.hxx"
  6. #include "cmFileTime.h"
  7. #include "cmGlobalUnixMakefileGenerator3.h"
  8. #include "cmList.h"
  9. #include "cmLocalUnixMakefileGenerator3.h"
  10. #include "cmMakefile.h"
  11. #include "cmStringAlgorithms.h"
  12. #include "cmSystemTools.h"
  13. #include "cmValue.h"
  14. #define INCLUDE_REGEX_LINE \
  15. "^[ \t]*[#%][ \t]*(include|import)[ \t]*[<\"]([^\">]+)([\">])"
  16. #define INCLUDE_REGEX_LINE_MARKER "#IncludeRegexLine: "
  17. #define INCLUDE_REGEX_SCAN_MARKER "#IncludeRegexScan: "
  18. #define INCLUDE_REGEX_COMPLAIN_MARKER "#IncludeRegexComplain: "
  19. #define INCLUDE_REGEX_TRANSFORM_MARKER "#IncludeRegexTransform: "
  20. cmDependsC::cmDependsC() = default;
  21. cmDependsC::cmDependsC(cmLocalUnixMakefileGenerator3* lg,
  22. const std::string& targetDir, const std::string& lang,
  23. const DependencyMap* validDeps)
  24. : cmDepends(lg, targetDir)
  25. , ValidDeps(validDeps)
  26. {
  27. cmMakefile* mf = lg->GetMakefile();
  28. // Configure the include file search path.
  29. this->SetIncludePathFromLanguage(lang);
  30. // Configure regular expressions.
  31. std::string scanRegex = "^.*$";
  32. std::string complainRegex = "^$";
  33. {
  34. std::string scanRegexVar = cmStrCat("CMAKE_", lang, "_INCLUDE_REGEX_SCAN");
  35. if (cmValue sr = mf->GetDefinition(scanRegexVar)) {
  36. scanRegex = *sr;
  37. }
  38. std::string complainRegexVar =
  39. cmStrCat("CMAKE_", lang, "_INCLUDE_REGEX_COMPLAIN");
  40. if (cmValue cr = mf->GetDefinition(complainRegexVar)) {
  41. complainRegex = *cr;
  42. }
  43. }
  44. this->IncludeRegexLine.compile(INCLUDE_REGEX_LINE);
  45. this->IncludeRegexScan.compile(scanRegex);
  46. this->IncludeRegexComplain.compile(complainRegex);
  47. this->IncludeRegexLineString = INCLUDE_REGEX_LINE_MARKER INCLUDE_REGEX_LINE;
  48. this->IncludeRegexScanString =
  49. cmStrCat(INCLUDE_REGEX_SCAN_MARKER, scanRegex);
  50. this->IncludeRegexComplainString =
  51. cmStrCat(INCLUDE_REGEX_COMPLAIN_MARKER, complainRegex);
  52. this->SetupTransforms();
  53. this->CacheFileName =
  54. cmStrCat(this->TargetDirectory, '/', lang, ".includecache");
  55. this->ReadCacheFile();
  56. }
  57. cmDependsC::~cmDependsC()
  58. {
  59. this->WriteCacheFile();
  60. }
  61. bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
  62. const std::string& obj,
  63. std::ostream& makeDepends,
  64. std::ostream& internalDepends)
  65. {
  66. // Make sure this is a scanning instance.
  67. if (sources.empty() || sources.begin()->empty()) {
  68. cmSystemTools::Error("Cannot scan dependencies without a source file.");
  69. return false;
  70. }
  71. if (obj.empty()) {
  72. cmSystemTools::Error("Cannot scan dependencies without an object file.");
  73. return false;
  74. }
  75. std::set<std::string> dependencies;
  76. bool haveDeps = false;
  77. // Compute a path to the object file to write to the internal depend file.
  78. // Any existing content of the internal depend file has already been
  79. // loaded in ValidDeps with this path as a key.
  80. std::string obj_i = this->LocalGenerator->MaybeRelativeToTopBinDir(obj);
  81. if (this->ValidDeps != nullptr) {
  82. auto const tmpIt = this->ValidDeps->find(obj_i);
  83. if (tmpIt != this->ValidDeps->end()) {
  84. dependencies.insert(tmpIt->second.begin(), tmpIt->second.end());
  85. haveDeps = true;
  86. }
  87. }
  88. if (!haveDeps) {
  89. // Walk the dependency graph starting with the source file.
  90. int srcFiles = static_cast<int>(sources.size());
  91. this->Encountered.clear();
  92. for (std::string const& src : sources) {
  93. UnscannedEntry root;
  94. root.FileName = src;
  95. this->Unscanned.push(root);
  96. this->Encountered.insert(src);
  97. }
  98. std::set<std::string> scanned;
  99. while (!this->Unscanned.empty()) {
  100. // Get the next file to scan.
  101. UnscannedEntry current = this->Unscanned.front();
  102. this->Unscanned.pop();
  103. // If not a full path, find the file in the include path.
  104. std::string fullName;
  105. if ((srcFiles > 0) || cmSystemTools::FileIsFullPath(current.FileName)) {
  106. if (cmSystemTools::FileExists(current.FileName, true)) {
  107. fullName = current.FileName;
  108. }
  109. } else if (!current.QuotedLocation.empty() &&
  110. cmSystemTools::FileExists(current.QuotedLocation, true)) {
  111. // The include statement producing this entry was a double-quote
  112. // include and the included file is present in the directory of
  113. // the source containing the include statement.
  114. fullName = current.QuotedLocation;
  115. } else {
  116. auto headerLocationIt =
  117. this->HeaderLocationCache.find(current.FileName);
  118. if (headerLocationIt != this->HeaderLocationCache.end()) {
  119. fullName = headerLocationIt->second;
  120. } else {
  121. for (std::string const& iPath : this->IncludePath) {
  122. // Construct the name of the file as if it were in the current
  123. // include directory. Avoid using a leading "./".
  124. std::string tmpPath =
  125. cmSystemTools::CollapseFullPath(current.FileName, iPath);
  126. // Look for the file in this location.
  127. if (cmSystemTools::FileExists(tmpPath, true)) {
  128. fullName = tmpPath;
  129. this->HeaderLocationCache[current.FileName] = std::move(tmpPath);
  130. break;
  131. }
  132. }
  133. }
  134. }
  135. // Complain if the file cannot be found and matches the complain
  136. // regex.
  137. if (fullName.empty() &&
  138. this->IncludeRegexComplain.find(current.FileName)) {
  139. cmSystemTools::Error("Cannot find file \"" + current.FileName + "\".");
  140. return false;
  141. }
  142. // Scan the file if it was found and has not been scanned already.
  143. if (!fullName.empty() && (scanned.find(fullName) == scanned.end())) {
  144. // Record scanned files.
  145. scanned.insert(fullName);
  146. // Check whether this file is already in the cache
  147. auto fileIt = this->FileCache.find(fullName);
  148. if (fileIt != this->FileCache.end()) {
  149. fileIt->second.Used = true;
  150. dependencies.insert(fullName);
  151. for (UnscannedEntry const& inc : fileIt->second.UnscannedEntries) {
  152. if (this->Encountered.find(inc.FileName) ==
  153. this->Encountered.end()) {
  154. this->Encountered.insert(inc.FileName);
  155. this->Unscanned.push(inc);
  156. }
  157. }
  158. } else {
  159. // Try to scan the file. Just leave it out if we cannot find
  160. // it.
  161. cmsys::ifstream fin(fullName.c_str());
  162. if (fin) {
  163. cmsys::FStream::BOM bom = cmsys::FStream::ReadBOM(fin);
  164. if (bom == cmsys::FStream::BOM_None ||
  165. bom == cmsys::FStream::BOM_UTF8) {
  166. // Add this file as a dependency.
  167. dependencies.insert(fullName);
  168. // Scan this file for new dependencies. Pass the directory
  169. // containing the file to handle double-quote includes.
  170. std::string dir = cmSystemTools::GetFilenamePath(fullName);
  171. this->Scan(fin, dir, fullName);
  172. } else {
  173. // Skip file with encoding we do not implement.
  174. }
  175. }
  176. }
  177. }
  178. srcFiles--;
  179. }
  180. }
  181. // Write the dependencies to the output stream. Makefile rules
  182. // written by the original local generator for this directory
  183. // convert the dependencies to paths relative to the home output
  184. // directory. We must do the same here.
  185. std::string obj_m = this->LocalGenerator->ConvertToMakefilePath(obj_i);
  186. internalDepends << obj_i << '\n';
  187. if (!dependencies.empty()) {
  188. const auto& lineContinue = static_cast<cmGlobalUnixMakefileGenerator3*>(
  189. this->LocalGenerator->GetGlobalGenerator())
  190. ->LineContinueDirective;
  191. bool supportLongLineDepend = static_cast<cmGlobalUnixMakefileGenerator3*>(
  192. this->LocalGenerator->GetGlobalGenerator())
  193. ->SupportsLongLineDependencies();
  194. if (supportLongLineDepend) {
  195. makeDepends << obj_m << ':';
  196. }
  197. for (std::string const& dep : dependencies) {
  198. std::string dependee = this->LocalGenerator->ConvertToMakefilePath(
  199. this->LocalGenerator->MaybeRelativeToTopBinDir(dep));
  200. if (supportLongLineDepend) {
  201. makeDepends << ' ' << lineContinue << ' ' << dependee;
  202. } else {
  203. makeDepends << obj_m << ": " << dependee << '\n';
  204. }
  205. internalDepends << ' ' << dep << '\n';
  206. }
  207. makeDepends << '\n';
  208. }
  209. return true;
  210. }
  211. void cmDependsC::ReadCacheFile()
  212. {
  213. if (this->CacheFileName.empty()) {
  214. return;
  215. }
  216. cmsys::ifstream fin(this->CacheFileName.c_str());
  217. if (!fin) {
  218. return;
  219. }
  220. std::string line;
  221. cmIncludeLines* cacheEntry = nullptr;
  222. bool haveFileName = false;
  223. cmFileTime cacheFileTime;
  224. bool const cacheFileTimeGood = cacheFileTime.Load(this->CacheFileName);
  225. while (cmSystemTools::GetLineFromStream(fin, line)) {
  226. if (line.empty()) {
  227. cacheEntry = nullptr;
  228. haveFileName = false;
  229. continue;
  230. }
  231. // the first line after an empty line is the name of the parsed file
  232. if (!haveFileName) {
  233. haveFileName = true;
  234. cmFileTime fileTime;
  235. bool const res = cacheFileTimeGood && fileTime.Load(line);
  236. bool const newer = res && cacheFileTime.Newer(fileTime);
  237. if (res && newer) // cache is newer than the parsed file
  238. {
  239. cacheEntry = &this->FileCache[line];
  240. }
  241. // file doesn't exist, check that the regular expressions
  242. // haven't changed
  243. else if (!res) {
  244. if (cmHasLiteralPrefix(line, INCLUDE_REGEX_LINE_MARKER)) {
  245. if (line != this->IncludeRegexLineString) {
  246. return;
  247. }
  248. } else if (cmHasLiteralPrefix(line, INCLUDE_REGEX_SCAN_MARKER)) {
  249. if (line != this->IncludeRegexScanString) {
  250. return;
  251. }
  252. } else if (cmHasLiteralPrefix(line, INCLUDE_REGEX_COMPLAIN_MARKER)) {
  253. if (line != this->IncludeRegexComplainString) {
  254. return;
  255. }
  256. } else if (cmHasLiteralPrefix(line, INCLUDE_REGEX_TRANSFORM_MARKER)) {
  257. if (line != this->IncludeRegexTransformString) {
  258. return;
  259. }
  260. }
  261. }
  262. } else if (cacheEntry != nullptr) {
  263. UnscannedEntry entry;
  264. entry.FileName = line;
  265. if (cmSystemTools::GetLineFromStream(fin, line)) {
  266. if (line != "-") {
  267. entry.QuotedLocation = line;
  268. }
  269. cacheEntry->UnscannedEntries.push_back(std::move(entry));
  270. }
  271. }
  272. }
  273. }
  274. void cmDependsC::WriteCacheFile() const
  275. {
  276. if (this->CacheFileName.empty()) {
  277. return;
  278. }
  279. cmsys::ofstream cacheOut(this->CacheFileName.c_str());
  280. if (!cacheOut) {
  281. return;
  282. }
  283. cacheOut << this->IncludeRegexLineString << "\n\n";
  284. cacheOut << this->IncludeRegexScanString << "\n\n";
  285. cacheOut << this->IncludeRegexComplainString << "\n\n";
  286. cacheOut << this->IncludeRegexTransformString << "\n\n";
  287. for (auto const& fileIt : this->FileCache) {
  288. if (fileIt.second.Used) {
  289. cacheOut << fileIt.first << '\n';
  290. for (UnscannedEntry const& inc : fileIt.second.UnscannedEntries) {
  291. cacheOut << inc.FileName << '\n';
  292. if (inc.QuotedLocation.empty()) {
  293. cacheOut << '-' << '\n';
  294. } else {
  295. cacheOut << inc.QuotedLocation << '\n';
  296. }
  297. }
  298. cacheOut << '\n';
  299. }
  300. }
  301. }
  302. void cmDependsC::Scan(std::istream& is, const std::string& directory,
  303. const std::string& fullName)
  304. {
  305. cmIncludeLines& newCacheEntry = this->FileCache[fullName];
  306. newCacheEntry.Used = true;
  307. // Read one line at a time.
  308. std::string line;
  309. while (cmSystemTools::GetLineFromStream(is, line)) {
  310. // Transform the line content first.
  311. if (!this->TransformRules.empty()) {
  312. this->TransformLine(line);
  313. }
  314. // Match include directives.
  315. if (this->IncludeRegexLine.find(line)) {
  316. // Get the file being included.
  317. UnscannedEntry entry;
  318. entry.FileName = this->IncludeRegexLine.match(2);
  319. cmSystemTools::ConvertToUnixSlashes(entry.FileName);
  320. if (this->IncludeRegexLine.match(3) == "\"" &&
  321. !cmSystemTools::FileIsFullPath(entry.FileName)) {
  322. // This was a double-quoted include with a relative path. We
  323. // must check for the file in the directory containing the
  324. // file we are scanning.
  325. entry.QuotedLocation =
  326. cmSystemTools::CollapseFullPath(entry.FileName, directory);
  327. }
  328. // Queue the file if it has not yet been encountered and it
  329. // matches the regular expression for recursive scanning. Note
  330. // that this check does not account for the possibility of two
  331. // headers with the same name in different directories when one
  332. // is included by double-quotes and the other by angle brackets.
  333. // It also does not work properly if two header files with the same
  334. // name exist in different directories, and both are included from a
  335. // file their own directory by simply using "filename.h" (#12619)
  336. // This kind of problem will be fixed when a more
  337. // preprocessor-like implementation of this scanner is created.
  338. if (this->IncludeRegexScan.find(entry.FileName)) {
  339. newCacheEntry.UnscannedEntries.push_back(entry);
  340. if (this->Encountered.find(entry.FileName) ==
  341. this->Encountered.end()) {
  342. this->Encountered.insert(entry.FileName);
  343. this->Unscanned.push(entry);
  344. }
  345. }
  346. }
  347. }
  348. }
  349. void cmDependsC::SetupTransforms()
  350. {
  351. // Get the transformation rules.
  352. cmMakefile* mf = this->LocalGenerator->GetMakefile();
  353. cmList transformRules{ mf->GetDefinition("CMAKE_INCLUDE_TRANSFORMS"),
  354. cmList::EmptyElements::Yes };
  355. for (auto const& tr : transformRules) {
  356. this->ParseTransform(tr);
  357. }
  358. this->IncludeRegexTransformString = INCLUDE_REGEX_TRANSFORM_MARKER;
  359. if (!this->TransformRules.empty()) {
  360. // Construct the regular expression to match lines to be
  361. // transformed.
  362. std::string xform = "^([ \t]*[#%][ \t]*(include|import)[ \t]*)(";
  363. const char* sep = "";
  364. for (auto const& tr : this->TransformRules) {
  365. xform += sep;
  366. xform += tr.first;
  367. sep = "|";
  368. }
  369. xform += ")[ \t]*\\(([^),]*)\\)";
  370. this->IncludeRegexTransform.compile(xform);
  371. // Build a string that encodes all transformation rules and will
  372. // change when rules are changed.
  373. this->IncludeRegexTransformString += xform;
  374. for (auto const& tr : this->TransformRules) {
  375. this->IncludeRegexTransformString += " ";
  376. this->IncludeRegexTransformString += tr.first;
  377. this->IncludeRegexTransformString += "(%)=";
  378. this->IncludeRegexTransformString += tr.second;
  379. }
  380. }
  381. }
  382. void cmDependsC::ParseTransform(std::string const& xform)
  383. {
  384. // A transform rule is of the form SOME_MACRO(%)=value-with-%
  385. // We can simply separate with "(%)=".
  386. std::string::size_type pos = xform.find("(%)=");
  387. if (pos == std::string::npos || pos == 0) {
  388. return;
  389. }
  390. std::string name = xform.substr(0, pos);
  391. std::string value = xform.substr(pos + 4);
  392. this->TransformRules[name] = value;
  393. }
  394. void cmDependsC::TransformLine(std::string& line)
  395. {
  396. // Check for a transform rule match. Return if none.
  397. if (!this->IncludeRegexTransform.find(line)) {
  398. return;
  399. }
  400. auto tri = this->TransformRules.find(this->IncludeRegexTransform.match(3));
  401. if (tri == this->TransformRules.end()) {
  402. return;
  403. }
  404. // Construct the transformed line.
  405. std::string newline = this->IncludeRegexTransform.match(1);
  406. std::string arg = this->IncludeRegexTransform.match(4);
  407. for (char c : tri->second) {
  408. if (c == '%') {
  409. newline += arg;
  410. } else {
  411. newline += c;
  412. }
  413. }
  414. // Return the transformed line.
  415. line = newline;
  416. }