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