cmDependsC.cxx 17 KB

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