cmDependsC.cxx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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 "cmsys/FStream.hxx"
  5. #include <utility>
  6. #include "cmAlgorithms.h"
  7. #include "cmFileTime.h"
  8. #include "cmLocalGenerator.h"
  9. #include "cmMakefile.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(cmLocalGenerator* lg, const std::string& targetDir,
  20. const std::string& lang, 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. cmDeleteAll(this->FileCache);
  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 = cmSystemTools::ConvertToOutputPath(obj_i);
  186. internalDepends << obj_i << std::endl;
  187. for (std::string const& dep : dependencies) {
  188. makeDepends << obj_m << ": "
  189. << cmSystemTools::ConvertToOutputPath(
  190. this->LocalGenerator->MaybeConvertToRelativePath(binDir,
  191. dep))
  192. << std::endl;
  193. internalDepends << " " << dep << std::endl;
  194. }
  195. makeDepends << std::endl;
  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 = new cmIncludeLines;
  227. this->FileCache[line] = cacheEntry;
  228. }
  229. // file doesn't exist, check that the regular expressions
  230. // haven't changed
  231. else if (!res) {
  232. if (line.find(INCLUDE_REGEX_LINE_MARKER) == 0) {
  233. if (line != this->IncludeRegexLineString) {
  234. return;
  235. }
  236. } else if (line.find(INCLUDE_REGEX_SCAN_MARKER) == 0) {
  237. if (line != this->IncludeRegexScanString) {
  238. return;
  239. }
  240. } else if (line.find(INCLUDE_REGEX_COMPLAIN_MARKER) == 0) {
  241. if (line != this->IncludeRegexComplainString) {
  242. return;
  243. }
  244. } else if (line.find(INCLUDE_REGEX_TRANSFORM_MARKER) == 0) {
  245. if (line != this->IncludeRegexTransformString) {
  246. return;
  247. }
  248. }
  249. }
  250. } else if (cacheEntry != nullptr) {
  251. UnscannedEntry entry;
  252. entry.FileName = line;
  253. if (cmSystemTools::GetLineFromStream(fin, line)) {
  254. if (line != "-") {
  255. entry.QuotedLocation = line;
  256. }
  257. cacheEntry->UnscannedEntries.push_back(std::move(entry));
  258. }
  259. }
  260. }
  261. }
  262. void cmDependsC::WriteCacheFile() const
  263. {
  264. if (this->CacheFileName.empty()) {
  265. return;
  266. }
  267. cmsys::ofstream cacheOut(this->CacheFileName.c_str());
  268. if (!cacheOut) {
  269. return;
  270. }
  271. cacheOut << this->IncludeRegexLineString << "\n\n";
  272. cacheOut << this->IncludeRegexScanString << "\n\n";
  273. cacheOut << this->IncludeRegexComplainString << "\n\n";
  274. cacheOut << this->IncludeRegexTransformString << "\n\n";
  275. for (auto const& fileIt : this->FileCache) {
  276. if (fileIt.second->Used) {
  277. cacheOut << fileIt.first << std::endl;
  278. for (UnscannedEntry const& inc : fileIt.second->UnscannedEntries) {
  279. cacheOut << inc.FileName << std::endl;
  280. if (inc.QuotedLocation.empty()) {
  281. cacheOut << "-" << std::endl;
  282. } else {
  283. cacheOut << inc.QuotedLocation << std::endl;
  284. }
  285. }
  286. cacheOut << std::endl;
  287. }
  288. }
  289. }
  290. void cmDependsC::Scan(std::istream& is, const std::string& directory,
  291. const std::string& fullName)
  292. {
  293. cmIncludeLines* newCacheEntry = new cmIncludeLines;
  294. newCacheEntry->Used = true;
  295. this->FileCache[fullName] = newCacheEntry;
  296. // Read one line at a time.
  297. std::string line;
  298. while (cmSystemTools::GetLineFromStream(is, line)) {
  299. // Transform the line content first.
  300. if (!this->TransformRules.empty()) {
  301. this->TransformLine(line);
  302. }
  303. // Match include directives.
  304. if (this->IncludeRegexLine.find(line)) {
  305. // Get the file being included.
  306. UnscannedEntry entry;
  307. entry.FileName = this->IncludeRegexLine.match(2);
  308. cmSystemTools::ConvertToUnixSlashes(entry.FileName);
  309. if (this->IncludeRegexLine.match(3) == "\"" &&
  310. !cmSystemTools::FileIsFullPath(entry.FileName)) {
  311. // This was a double-quoted include with a relative path. We
  312. // must check for the file in the directory containing the
  313. // file we are scanning.
  314. entry.QuotedLocation =
  315. cmSystemTools::CollapseFullPath(entry.FileName, directory);
  316. }
  317. // Queue the file if it has not yet been encountered and it
  318. // matches the regular expression for recursive scanning. Note
  319. // that this check does not account for the possibility of two
  320. // headers with the same name in different directories when one
  321. // is included by double-quotes and the other by angle brackets.
  322. // It also does not work properly if two header files with the same
  323. // name exist in different directories, and both are included from a
  324. // file their own directory by simply using "filename.h" (#12619)
  325. // This kind of problem will be fixed when a more
  326. // preprocessor-like implementation of this scanner is created.
  327. if (this->IncludeRegexScan.find(entry.FileName)) {
  328. newCacheEntry->UnscannedEntries.push_back(entry);
  329. if (this->Encountered.find(entry.FileName) ==
  330. this->Encountered.end()) {
  331. this->Encountered.insert(entry.FileName);
  332. this->Unscanned.push(entry);
  333. }
  334. }
  335. }
  336. }
  337. }
  338. void cmDependsC::SetupTransforms()
  339. {
  340. // Get the transformation rules.
  341. std::vector<std::string> transformRules;
  342. cmMakefile* mf = this->LocalGenerator->GetMakefile();
  343. if (const char* xform = mf->GetDefinition("CMAKE_INCLUDE_TRANSFORMS")) {
  344. cmExpandList(xform, transformRules, true);
  345. }
  346. for (std::string const& tr : transformRules) {
  347. this->ParseTransform(tr);
  348. }
  349. this->IncludeRegexTransformString = INCLUDE_REGEX_TRANSFORM_MARKER;
  350. if (!this->TransformRules.empty()) {
  351. // Construct the regular expression to match lines to be
  352. // transformed.
  353. std::string xform = "^([ \t]*[#%][ \t]*(include|import)[ \t]*)(";
  354. const char* sep = "";
  355. for (auto const& tr : this->TransformRules) {
  356. xform += sep;
  357. xform += tr.first;
  358. sep = "|";
  359. }
  360. xform += ")[ \t]*\\(([^),]*)\\)";
  361. this->IncludeRegexTransform.compile(xform);
  362. // Build a string that encodes all transformation rules and will
  363. // change when rules are changed.
  364. this->IncludeRegexTransformString += xform;
  365. for (auto const& tr : this->TransformRules) {
  366. this->IncludeRegexTransformString += " ";
  367. this->IncludeRegexTransformString += tr.first;
  368. this->IncludeRegexTransformString += "(%)=";
  369. this->IncludeRegexTransformString += tr.second;
  370. }
  371. }
  372. }
  373. void cmDependsC::ParseTransform(std::string const& xform)
  374. {
  375. // A transform rule is of the form SOME_MACRO(%)=value-with-%
  376. // We can simply separate with "(%)=".
  377. std::string::size_type pos = xform.find("(%)=");
  378. if (pos == std::string::npos || pos == 0) {
  379. return;
  380. }
  381. std::string name = xform.substr(0, pos);
  382. std::string value = xform.substr(pos + 4);
  383. this->TransformRules[name] = value;
  384. }
  385. void cmDependsC::TransformLine(std::string& line)
  386. {
  387. // Check for a transform rule match. Return if none.
  388. if (!this->IncludeRegexTransform.find(line)) {
  389. return;
  390. }
  391. TransformRulesType::const_iterator tri =
  392. this->TransformRules.find(this->IncludeRegexTransform.match(3));
  393. if (tri == this->TransformRules.end()) {
  394. return;
  395. }
  396. // Construct the transformed line.
  397. std::string newline = this->IncludeRegexTransform.match(1);
  398. std::string arg = this->IncludeRegexTransform.match(4);
  399. for (char c : tri->second) {
  400. if (c == '%') {
  401. newline += arg;
  402. } else {
  403. newline += c;
  404. }
  405. }
  406. // Return the transformed line.
  407. line = newline;
  408. }