cmDependsC.cxx 15 KB

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