cmDependsC.cxx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 "cmLocalUnixMakefileGenerator3.h"
  8. #include "cmMakefile.h"
  9. #include "cmProperty.h"
  10. #include "cmStringAlgorithms.h"
  11. #include "cmSystemTools.h"
  12. #define INCLUDE_REGEX_LINE \
  13. "^[ \t]*[#%][ \t]*(include|import)[ \t]*[<\"]([^\">]+)([\">])"
  14. #define INCLUDE_REGEX_LINE_MARKER "#IncludeRegexLine: "
  15. #define INCLUDE_REGEX_SCAN_MARKER "#IncludeRegexScan: "
  16. #define INCLUDE_REGEX_COMPLAIN_MARKER "#IncludeRegexComplain: "
  17. #define INCLUDE_REGEX_TRANSFORM_MARKER "#IncludeRegexTransform: "
  18. cmDependsC::cmDependsC() = default;
  19. cmDependsC::cmDependsC(cmLocalUnixMakefileGenerator3* lg,
  20. const std::string& targetDir, const std::string& lang,
  21. const DependencyMap* validDeps)
  22. : cmDepends(lg, targetDir)
  23. , ValidDeps(validDeps)
  24. {
  25. cmMakefile* mf = lg->GetMakefile();
  26. // Configure the include file search path.
  27. this->SetIncludePathFromLanguage(lang);
  28. // Configure regular expressions.
  29. std::string scanRegex = "^.*$";
  30. std::string complainRegex = "^$";
  31. {
  32. std::string scanRegexVar = cmStrCat("CMAKE_", lang, "_INCLUDE_REGEX_SCAN");
  33. if (cmProp sr = mf->GetDefinition(scanRegexVar)) {
  34. scanRegex = *sr;
  35. }
  36. std::string complainRegexVar =
  37. cmStrCat("CMAKE_", lang, "_INCLUDE_REGEX_COMPLAIN");
  38. if (cmProp cr = mf->GetDefinition(complainRegexVar)) {
  39. complainRegex = *cr;
  40. }
  41. }
  42. this->IncludeRegexLine.compile(INCLUDE_REGEX_LINE);
  43. this->IncludeRegexScan.compile(scanRegex);
  44. this->IncludeRegexComplain.compile(complainRegex);
  45. this->IncludeRegexLineString = INCLUDE_REGEX_LINE_MARKER INCLUDE_REGEX_LINE;
  46. this->IncludeRegexScanString =
  47. cmStrCat(INCLUDE_REGEX_SCAN_MARKER, scanRegex);
  48. this->IncludeRegexComplainString =
  49. cmStrCat(INCLUDE_REGEX_COMPLAIN_MARKER, complainRegex);
  50. this->SetupTransforms();
  51. this->CacheFileName =
  52. cmStrCat(this->TargetDirectory, '/', lang, ".includecache");
  53. this->ReadCacheFile();
  54. }
  55. cmDependsC::~cmDependsC()
  56. {
  57. this->WriteCacheFile();
  58. }
  59. bool cmDependsC::WriteDependencies(const std::set<std::string>& sources,
  60. const std::string& obj,
  61. std::ostream& makeDepends,
  62. std::ostream& internalDepends)
  63. {
  64. // Make sure this is a scanning instance.
  65. if (sources.empty() || sources.begin()->empty()) {
  66. cmSystemTools::Error("Cannot scan dependencies without a source file.");
  67. return false;
  68. }
  69. if (obj.empty()) {
  70. cmSystemTools::Error("Cannot scan dependencies without an object file.");
  71. return false;
  72. }
  73. std::set<std::string> dependencies;
  74. bool haveDeps = false;
  75. std::string binDir = this->LocalGenerator->GetBinaryDirectory();
  76. // Compute a path to the object file to write to the internal depend file.
  77. // Any existing content of the internal depend file has already been
  78. // loaded in ValidDeps with this path as a key.
  79. std::string obj_i =
  80. this->LocalGenerator->MaybeConvertToRelativePath(binDir, 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. for (std::string const& dep : dependencies) {
  188. makeDepends << obj_m << ": "
  189. << this->LocalGenerator->ConvertToMakefilePath(
  190. this->LocalGenerator->MaybeConvertToRelativePath(binDir,
  191. dep))
  192. << '\n';
  193. internalDepends << ' ' << dep << '\n';
  194. }
  195. makeDepends << '\n';
  196. return true;
  197. }
  198. void cmDependsC::ReadCacheFile()
  199. {
  200. if (this->CacheFileName.empty()) {
  201. return;
  202. }
  203. cmsys::ifstream fin(this->CacheFileName.c_str());
  204. if (!fin) {
  205. return;
  206. }
  207. std::string line;
  208. cmIncludeLines* cacheEntry = nullptr;
  209. bool haveFileName = false;
  210. cmFileTime cacheFileTime;
  211. bool const cacheFileTimeGood = cacheFileTime.Load(this->CacheFileName);
  212. while (cmSystemTools::GetLineFromStream(fin, line)) {
  213. if (line.empty()) {
  214. cacheEntry = nullptr;
  215. haveFileName = false;
  216. continue;
  217. }
  218. // the first line after an empty line is the name of the parsed file
  219. if (!haveFileName) {
  220. haveFileName = true;
  221. cmFileTime fileTime;
  222. bool const res = cacheFileTimeGood && fileTime.Load(line);
  223. bool const newer = res && cacheFileTime.Newer(fileTime);
  224. if (res && newer) // cache is newer than the parsed file
  225. {
  226. cacheEntry = &this->FileCache[line];
  227. }
  228. // file doesn't exist, check that the regular expressions
  229. // haven't changed
  230. else if (!res) {
  231. if (cmHasLiteralPrefix(line, INCLUDE_REGEX_LINE_MARKER)) {
  232. if (line != this->IncludeRegexLineString) {
  233. return;
  234. }
  235. } else if (cmHasLiteralPrefix(line, INCLUDE_REGEX_SCAN_MARKER)) {
  236. if (line != this->IncludeRegexScanString) {
  237. return;
  238. }
  239. } else if (cmHasLiteralPrefix(line, INCLUDE_REGEX_COMPLAIN_MARKER)) {
  240. if (line != this->IncludeRegexComplainString) {
  241. return;
  242. }
  243. } else if (cmHasLiteralPrefix(line, INCLUDE_REGEX_TRANSFORM_MARKER)) {
  244. if (line != this->IncludeRegexTransformString) {
  245. return;
  246. }
  247. }
  248. }
  249. } else if (cacheEntry != nullptr) {
  250. UnscannedEntry entry;
  251. entry.FileName = line;
  252. if (cmSystemTools::GetLineFromStream(fin, line)) {
  253. if (line != "-") {
  254. entry.QuotedLocation = line;
  255. }
  256. cacheEntry->UnscannedEntries.push_back(std::move(entry));
  257. }
  258. }
  259. }
  260. }
  261. void cmDependsC::WriteCacheFile() const
  262. {
  263. if (this->CacheFileName.empty()) {
  264. return;
  265. }
  266. cmsys::ofstream cacheOut(this->CacheFileName.c_str());
  267. if (!cacheOut) {
  268. return;
  269. }
  270. cacheOut << this->IncludeRegexLineString << "\n\n";
  271. cacheOut << this->IncludeRegexScanString << "\n\n";
  272. cacheOut << this->IncludeRegexComplainString << "\n\n";
  273. cacheOut << this->IncludeRegexTransformString << "\n\n";
  274. for (auto const& fileIt : this->FileCache) {
  275. if (fileIt.second.Used) {
  276. cacheOut << fileIt.first << '\n';
  277. for (UnscannedEntry const& inc : fileIt.second.UnscannedEntries) {
  278. cacheOut << inc.FileName << '\n';
  279. if (inc.QuotedLocation.empty()) {
  280. cacheOut << '-' << '\n';
  281. } else {
  282. cacheOut << inc.QuotedLocation << '\n';
  283. }
  284. }
  285. cacheOut << '\n';
  286. }
  287. }
  288. }
  289. void cmDependsC::Scan(std::istream& is, const std::string& directory,
  290. const std::string& fullName)
  291. {
  292. cmIncludeLines& newCacheEntry = this->FileCache[fullName];
  293. newCacheEntry.Used = true;
  294. // Read one line at a time.
  295. std::string line;
  296. while (cmSystemTools::GetLineFromStream(is, line)) {
  297. // Transform the line content first.
  298. if (!this->TransformRules.empty()) {
  299. this->TransformLine(line);
  300. }
  301. // Match include directives.
  302. if (this->IncludeRegexLine.find(line)) {
  303. // Get the file being included.
  304. UnscannedEntry entry;
  305. entry.FileName = this->IncludeRegexLine.match(2);
  306. cmSystemTools::ConvertToUnixSlashes(entry.FileName);
  307. if (this->IncludeRegexLine.match(3) == "\"" &&
  308. !cmSystemTools::FileIsFullPath(entry.FileName)) {
  309. // This was a double-quoted include with a relative path. We
  310. // must check for the file in the directory containing the
  311. // file we are scanning.
  312. entry.QuotedLocation =
  313. cmSystemTools::CollapseFullPath(entry.FileName, directory);
  314. }
  315. // Queue the file if it has not yet been encountered and it
  316. // matches the regular expression for recursive scanning. Note
  317. // that this check does not account for the possibility of two
  318. // headers with the same name in different directories when one
  319. // is included by double-quotes and the other by angle brackets.
  320. // It also does not work properly if two header files with the same
  321. // name exist in different directories, and both are included from a
  322. // file their own directory by simply using "filename.h" (#12619)
  323. // This kind of problem will be fixed when a more
  324. // preprocessor-like implementation of this scanner is created.
  325. if (this->IncludeRegexScan.find(entry.FileName)) {
  326. newCacheEntry.UnscannedEntries.push_back(entry);
  327. if (this->Encountered.find(entry.FileName) ==
  328. this->Encountered.end()) {
  329. this->Encountered.insert(entry.FileName);
  330. this->Unscanned.push(entry);
  331. }
  332. }
  333. }
  334. }
  335. }
  336. void cmDependsC::SetupTransforms()
  337. {
  338. // Get the transformation rules.
  339. std::vector<std::string> transformRules;
  340. cmMakefile* mf = this->LocalGenerator->GetMakefile();
  341. mf->GetDefExpandList("CMAKE_INCLUDE_TRANSFORMS", transformRules, true);
  342. for (std::string const& tr : transformRules) {
  343. this->ParseTransform(tr);
  344. }
  345. this->IncludeRegexTransformString = INCLUDE_REGEX_TRANSFORM_MARKER;
  346. if (!this->TransformRules.empty()) {
  347. // Construct the regular expression to match lines to be
  348. // transformed.
  349. std::string xform = "^([ \t]*[#%][ \t]*(include|import)[ \t]*)(";
  350. const char* sep = "";
  351. for (auto const& tr : this->TransformRules) {
  352. xform += sep;
  353. xform += tr.first;
  354. sep = "|";
  355. }
  356. xform += ")[ \t]*\\(([^),]*)\\)";
  357. this->IncludeRegexTransform.compile(xform);
  358. // Build a string that encodes all transformation rules and will
  359. // change when rules are changed.
  360. this->IncludeRegexTransformString += xform;
  361. for (auto const& tr : this->TransformRules) {
  362. this->IncludeRegexTransformString += " ";
  363. this->IncludeRegexTransformString += tr.first;
  364. this->IncludeRegexTransformString += "(%)=";
  365. this->IncludeRegexTransformString += tr.second;
  366. }
  367. }
  368. }
  369. void cmDependsC::ParseTransform(std::string const& xform)
  370. {
  371. // A transform rule is of the form SOME_MACRO(%)=value-with-%
  372. // We can simply separate with "(%)=".
  373. std::string::size_type pos = xform.find("(%)=");
  374. if (pos == std::string::npos || pos == 0) {
  375. return;
  376. }
  377. std::string name = xform.substr(0, pos);
  378. std::string value = xform.substr(pos + 4);
  379. this->TransformRules[name] = value;
  380. }
  381. void cmDependsC::TransformLine(std::string& line)
  382. {
  383. // Check for a transform rule match. Return if none.
  384. if (!this->IncludeRegexTransform.find(line)) {
  385. return;
  386. }
  387. auto tri = this->TransformRules.find(this->IncludeRegexTransform.match(3));
  388. if (tri == this->TransformRules.end()) {
  389. return;
  390. }
  391. // Construct the transformed line.
  392. std::string newline = this->IncludeRegexTransform.match(1);
  393. std::string arg = this->IncludeRegexTransform.match(4);
  394. for (char c : tri->second) {
  395. if (c == '%') {
  396. newline += arg;
  397. } else {
  398. newline += c;
  399. }
  400. }
  401. // Return the transformed line.
  402. line = newline;
  403. }