cmDependsC.cxx 16 KB

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