DependencyFile.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. //===--- DependencyFile.cpp - Generate dependency file --------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This code generates dependency files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Frontend/Utils.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/SourceManager.h"
  16. #include "clang/Frontend/DependencyOutputOptions.h"
  17. #include "clang/Frontend/FrontendDiagnostic.h"
  18. #include "clang/Lex/DirectoryLookup.h"
  19. #include "clang/Lex/LexDiagnostic.h"
  20. #include "clang/Lex/ModuleMap.h"
  21. #include "clang/Lex/PPCallbacks.h"
  22. #include "clang/Lex/Preprocessor.h"
  23. #include "clang/Serialization/ASTReader.h"
  24. #include "llvm/ADT/StringSet.h"
  25. #include "llvm/ADT/StringSwitch.h"
  26. #include "llvm/Support/FileSystem.h"
  27. #include "llvm/Support/Path.h"
  28. #include "llvm/Support/raw_ostream.h"
  29. using namespace clang;
  30. namespace {
  31. struct DepCollectorPPCallbacks : public PPCallbacks {
  32. DependencyCollector &DepCollector;
  33. SourceManager &SM;
  34. DepCollectorPPCallbacks(DependencyCollector &L, SourceManager &SM)
  35. : DepCollector(L), SM(SM) { }
  36. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  37. SrcMgr::CharacteristicKind FileType,
  38. FileID PrevFID) override {
  39. if (Reason != PPCallbacks::EnterFile)
  40. return;
  41. // Dependency generation really does want to go all the way to the
  42. // file entry for a source location to find out what is depended on.
  43. // We do not want #line markers to affect dependency generation!
  44. const FileEntry *FE =
  45. SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
  46. if (!FE)
  47. return;
  48. StringRef Filename = FE->getName();
  49. // Remove leading "./" (or ".//" or "././" etc.)
  50. while (Filename.size() > 2 && Filename[0] == '.' &&
  51. llvm::sys::path::is_separator(Filename[1])) {
  52. Filename = Filename.substr(1);
  53. while (llvm::sys::path::is_separator(Filename[0]))
  54. Filename = Filename.substr(1);
  55. }
  56. DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
  57. FileType != SrcMgr::C_User,
  58. /*IsModuleFile*/false, /*IsMissing*/false);
  59. }
  60. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  61. StringRef FileName, bool IsAngled,
  62. CharSourceRange FilenameRange, const FileEntry *File,
  63. StringRef SearchPath, StringRef RelativePath,
  64. const Module *Imported) override {
  65. if (!File)
  66. DepCollector.maybeAddDependency(FileName, /*FromModule*/false,
  67. /*IsSystem*/false, /*IsModuleFile*/false,
  68. /*IsMissing*/true);
  69. // Files that actually exist are handled by FileChanged.
  70. }
  71. void EndOfMainFile() override {
  72. DepCollector.finishedMainFile();
  73. }
  74. };
  75. struct DepCollectorMMCallbacks : public ModuleMapCallbacks {
  76. DependencyCollector &DepCollector;
  77. DepCollectorMMCallbacks(DependencyCollector &DC) : DepCollector(DC) {}
  78. void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
  79. bool IsSystem) override {
  80. StringRef Filename = Entry.getName();
  81. DepCollector.maybeAddDependency(Filename, /*FromModule*/false,
  82. /*IsSystem*/IsSystem,
  83. /*IsModuleFile*/false,
  84. /*IsMissing*/false);
  85. }
  86. };
  87. struct DepCollectorASTListener : public ASTReaderListener {
  88. DependencyCollector &DepCollector;
  89. DepCollectorASTListener(DependencyCollector &L) : DepCollector(L) { }
  90. bool needsInputFileVisitation() override { return true; }
  91. bool needsSystemInputFileVisitation() override {
  92. return DepCollector.needSystemDependencies();
  93. }
  94. void visitModuleFile(StringRef Filename) override {
  95. DepCollector.maybeAddDependency(Filename, /*FromModule*/true,
  96. /*IsSystem*/false, /*IsModuleFile*/true,
  97. /*IsMissing*/false);
  98. }
  99. bool visitInputFile(StringRef Filename, bool IsSystem,
  100. bool IsOverridden) override {
  101. if (IsOverridden)
  102. return true;
  103. DepCollector.maybeAddDependency(Filename, /*FromModule*/true, IsSystem,
  104. /*IsModuleFile*/false, /*IsMissing*/false);
  105. return true;
  106. }
  107. };
  108. } // end anonymous namespace
  109. void DependencyCollector::maybeAddDependency(StringRef Filename, bool FromModule,
  110. bool IsSystem, bool IsModuleFile,
  111. bool IsMissing) {
  112. if (Seen.insert(Filename).second &&
  113. sawDependency(Filename, FromModule, IsSystem, IsModuleFile, IsMissing))
  114. Dependencies.push_back(Filename);
  115. }
  116. static bool isSpecialFilename(StringRef Filename) {
  117. return llvm::StringSwitch<bool>(Filename)
  118. .Case("<built-in>", true)
  119. .Case("<stdin>", true)
  120. .Default(false);
  121. }
  122. bool DependencyCollector::sawDependency(StringRef Filename, bool FromModule,
  123. bool IsSystem, bool IsModuleFile,
  124. bool IsMissing) {
  125. return !isSpecialFilename(Filename) &&
  126. (needSystemDependencies() || !IsSystem);
  127. }
  128. DependencyCollector::~DependencyCollector() { }
  129. void DependencyCollector::attachToPreprocessor(Preprocessor &PP) {
  130. PP.addPPCallbacks(
  131. llvm::make_unique<DepCollectorPPCallbacks>(*this, PP.getSourceManager()));
  132. PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
  133. llvm::make_unique<DepCollectorMMCallbacks>(*this));
  134. }
  135. void DependencyCollector::attachToASTReader(ASTReader &R) {
  136. R.addListener(llvm::make_unique<DepCollectorASTListener>(*this));
  137. }
  138. namespace {
  139. /// Private implementation for DependencyFileGenerator
  140. class DFGImpl : public PPCallbacks {
  141. std::vector<std::string> Files;
  142. llvm::StringSet<> FilesSet;
  143. const Preprocessor *PP;
  144. std::string OutputFile;
  145. std::vector<std::string> Targets;
  146. bool IncludeSystemHeaders;
  147. bool PhonyTarget;
  148. bool AddMissingHeaderDeps;
  149. bool SeenMissingHeader;
  150. bool IncludeModuleFiles;
  151. DependencyOutputFormat OutputFormat;
  152. private:
  153. bool FileMatchesDepCriteria(const char *Filename,
  154. SrcMgr::CharacteristicKind FileType);
  155. void OutputDependencyFile();
  156. public:
  157. DFGImpl(const Preprocessor *_PP, const DependencyOutputOptions &Opts)
  158. : PP(_PP), OutputFile(Opts.OutputFile), Targets(Opts.Targets),
  159. IncludeSystemHeaders(Opts.IncludeSystemHeaders),
  160. PhonyTarget(Opts.UsePhonyTargets),
  161. AddMissingHeaderDeps(Opts.AddMissingHeaderDeps),
  162. SeenMissingHeader(false),
  163. IncludeModuleFiles(Opts.IncludeModuleFiles),
  164. OutputFormat(Opts.OutputFormat) {
  165. for (auto ExtraDep : Opts.ExtraDeps) {
  166. AddFilename(ExtraDep);
  167. }
  168. }
  169. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  170. SrcMgr::CharacteristicKind FileType,
  171. FileID PrevFID) override;
  172. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  173. StringRef FileName, bool IsAngled,
  174. CharSourceRange FilenameRange, const FileEntry *File,
  175. StringRef SearchPath, StringRef RelativePath,
  176. const Module *Imported) override;
  177. void EndOfMainFile() override {
  178. OutputDependencyFile();
  179. }
  180. void AddFilename(StringRef Filename);
  181. bool includeSystemHeaders() const { return IncludeSystemHeaders; }
  182. bool includeModuleFiles() const { return IncludeModuleFiles; }
  183. };
  184. class DFGMMCallback : public ModuleMapCallbacks {
  185. DFGImpl &Parent;
  186. public:
  187. DFGMMCallback(DFGImpl &Parent) : Parent(Parent) {}
  188. void moduleMapFileRead(SourceLocation Loc, const FileEntry &Entry,
  189. bool IsSystem) override {
  190. if (!IsSystem || Parent.includeSystemHeaders())
  191. Parent.AddFilename(Entry.getName());
  192. }
  193. };
  194. class DFGASTReaderListener : public ASTReaderListener {
  195. DFGImpl &Parent;
  196. public:
  197. DFGASTReaderListener(DFGImpl &Parent)
  198. : Parent(Parent) { }
  199. bool needsInputFileVisitation() override { return true; }
  200. bool needsSystemInputFileVisitation() override {
  201. return Parent.includeSystemHeaders();
  202. }
  203. void visitModuleFile(StringRef Filename) override;
  204. bool visitInputFile(StringRef Filename, bool isSystem,
  205. bool isOverridden) override;
  206. };
  207. }
  208. DependencyFileGenerator::DependencyFileGenerator(void *Impl)
  209. : Impl(Impl) { }
  210. DependencyFileGenerator *DependencyFileGenerator::CreateAndAttachToPreprocessor(
  211. clang::Preprocessor &PP, const clang::DependencyOutputOptions &Opts) {
  212. if (Opts.Targets.empty()) {
  213. PP.getDiagnostics().Report(diag::err_fe_dependency_file_requires_MT);
  214. return nullptr;
  215. }
  216. // Disable the "file not found" diagnostic if the -MG option was given.
  217. if (Opts.AddMissingHeaderDeps)
  218. PP.SetSuppressIncludeNotFoundError(true);
  219. DFGImpl *Callback = new DFGImpl(&PP, Opts);
  220. PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(Callback));
  221. PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
  222. llvm::make_unique<DFGMMCallback>(*Callback));
  223. return new DependencyFileGenerator(Callback);
  224. }
  225. void DependencyFileGenerator::AttachToASTReader(ASTReader &R) {
  226. DFGImpl *I = reinterpret_cast<DFGImpl *>(Impl);
  227. assert(I && "missing implementation");
  228. R.addListener(llvm::make_unique<DFGASTReaderListener>(*I));
  229. }
  230. /// FileMatchesDepCriteria - Determine whether the given Filename should be
  231. /// considered as a dependency.
  232. bool DFGImpl::FileMatchesDepCriteria(const char *Filename,
  233. SrcMgr::CharacteristicKind FileType) {
  234. if (isSpecialFilename(Filename))
  235. return false;
  236. if (IncludeSystemHeaders)
  237. return true;
  238. return FileType == SrcMgr::C_User;
  239. }
  240. void DFGImpl::FileChanged(SourceLocation Loc,
  241. FileChangeReason Reason,
  242. SrcMgr::CharacteristicKind FileType,
  243. FileID PrevFID) {
  244. if (Reason != PPCallbacks::EnterFile)
  245. return;
  246. // Dependency generation really does want to go all the way to the
  247. // file entry for a source location to find out what is depended on.
  248. // We do not want #line markers to affect dependency generation!
  249. SourceManager &SM = PP->getSourceManager();
  250. const FileEntry *FE =
  251. SM.getFileEntryForID(SM.getFileID(SM.getExpansionLoc(Loc)));
  252. if (!FE) return;
  253. StringRef Filename = FE->getName();
  254. if (!FileMatchesDepCriteria(Filename.data(), FileType))
  255. return;
  256. // Remove leading "./" (or ".//" or "././" etc.)
  257. while (Filename.size() > 2 && Filename[0] == '.' &&
  258. llvm::sys::path::is_separator(Filename[1])) {
  259. Filename = Filename.substr(1);
  260. while (llvm::sys::path::is_separator(Filename[0]))
  261. Filename = Filename.substr(1);
  262. }
  263. AddFilename(Filename);
  264. }
  265. void DFGImpl::InclusionDirective(SourceLocation HashLoc,
  266. const Token &IncludeTok,
  267. StringRef FileName,
  268. bool IsAngled,
  269. CharSourceRange FilenameRange,
  270. const FileEntry *File,
  271. StringRef SearchPath,
  272. StringRef RelativePath,
  273. const Module *Imported) {
  274. if (!File) {
  275. if (AddMissingHeaderDeps)
  276. AddFilename(FileName);
  277. else
  278. SeenMissingHeader = true;
  279. }
  280. }
  281. void DFGImpl::AddFilename(StringRef Filename) {
  282. if (FilesSet.insert(Filename).second)
  283. Files.push_back(Filename);
  284. }
  285. /// Print the filename, with escaping or quoting that accommodates the three
  286. /// most likely tools that use dependency files: GNU Make, BSD Make, and
  287. /// NMake/Jom.
  288. ///
  289. /// BSD Make is the simplest case: It does no escaping at all. This means
  290. /// characters that are normally delimiters, i.e. space and # (the comment
  291. /// character) simply aren't supported in filenames.
  292. ///
  293. /// GNU Make does allow space and # in filenames, but to avoid being treated
  294. /// as a delimiter or comment, these must be escaped with a backslash. Because
  295. /// backslash is itself the escape character, if a backslash appears in a
  296. /// filename, it should be escaped as well. (As a special case, $ is escaped
  297. /// as $$, which is the normal Make way to handle the $ character.)
  298. /// For compatibility with BSD Make and historical practice, if GNU Make
  299. /// un-escapes characters in a filename but doesn't find a match, it will
  300. /// retry with the unmodified original string.
  301. ///
  302. /// GCC tries to accommodate both Make formats by escaping any space or #
  303. /// characters in the original filename, but not escaping backslashes. The
  304. /// apparent intent is so that filenames with backslashes will be handled
  305. /// correctly by BSD Make, and by GNU Make in its fallback mode of using the
  306. /// unmodified original string; filenames with # or space characters aren't
  307. /// supported by BSD Make at all, but will be handled correctly by GNU Make
  308. /// due to the escaping.
  309. ///
  310. /// A corner case that GCC gets only partly right is when the original filename
  311. /// has a backslash immediately followed by space or #. GNU Make would expect
  312. /// this backslash to be escaped; however GCC escapes the original backslash
  313. /// only when followed by space, not #. It will therefore take a dependency
  314. /// from a directive such as
  315. /// #include "a\ b\#c.h"
  316. /// and emit it as
  317. /// a\\\ b\\#c.h
  318. /// which GNU Make will interpret as
  319. /// a\ b\
  320. /// followed by a comment. Failing to find this file, it will fall back to the
  321. /// original string, which probably doesn't exist either; in any case it won't
  322. /// find
  323. /// a\ b\#c.h
  324. /// which is the actual filename specified by the include directive.
  325. ///
  326. /// Clang does what GCC does, rather than what GNU Make expects.
  327. ///
  328. /// NMake/Jom has a different set of scary characters, but wraps filespecs in
  329. /// double-quotes to avoid misinterpreting them; see
  330. /// https://msdn.microsoft.com/en-us/library/dd9y37ha.aspx for NMake info,
  331. /// https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx
  332. /// for Windows file-naming info.
  333. static void PrintFilename(raw_ostream &OS, StringRef Filename,
  334. DependencyOutputFormat OutputFormat) {
  335. if (OutputFormat == DependencyOutputFormat::NMake) {
  336. // Add quotes if needed. These are the characters listed as "special" to
  337. // NMake, that are legal in a Windows filespec, and that could cause
  338. // misinterpretation of the dependency string.
  339. if (Filename.find_first_of(" #${}^!") != StringRef::npos)
  340. OS << '\"' << Filename << '\"';
  341. else
  342. OS << Filename;
  343. return;
  344. }
  345. assert(OutputFormat == DependencyOutputFormat::Make);
  346. for (unsigned i = 0, e = Filename.size(); i != e; ++i) {
  347. if (Filename[i] == '#') // Handle '#' the broken gcc way.
  348. OS << '\\';
  349. else if (Filename[i] == ' ') { // Handle space correctly.
  350. OS << '\\';
  351. unsigned j = i;
  352. while (j > 0 && Filename[--j] == '\\')
  353. OS << '\\';
  354. } else if (Filename[i] == '$') // $ is escaped by $$.
  355. OS << '$';
  356. OS << Filename[i];
  357. }
  358. }
  359. void DFGImpl::OutputDependencyFile() {
  360. if (SeenMissingHeader) {
  361. llvm::sys::fs::remove(OutputFile);
  362. return;
  363. }
  364. std::error_code EC;
  365. llvm::raw_fd_ostream OS(OutputFile, EC, llvm::sys::fs::F_Text);
  366. if (EC) {
  367. PP->getDiagnostics().Report(diag::err_fe_error_opening) << OutputFile
  368. << EC.message();
  369. return;
  370. }
  371. // Write out the dependency targets, trying to avoid overly long
  372. // lines when possible. We try our best to emit exactly the same
  373. // dependency file as GCC (4.2), assuming the included files are the
  374. // same.
  375. const unsigned MaxColumns = 75;
  376. unsigned Columns = 0;
  377. for (std::vector<std::string>::iterator
  378. I = Targets.begin(), E = Targets.end(); I != E; ++I) {
  379. unsigned N = I->length();
  380. if (Columns == 0) {
  381. Columns += N;
  382. } else if (Columns + N + 2 > MaxColumns) {
  383. Columns = N + 2;
  384. OS << " \\\n ";
  385. } else {
  386. Columns += N + 1;
  387. OS << ' ';
  388. }
  389. // Targets already quoted as needed.
  390. OS << *I;
  391. }
  392. OS << ':';
  393. Columns += 1;
  394. // Now add each dependency in the order it was seen, but avoiding
  395. // duplicates.
  396. for (std::vector<std::string>::iterator I = Files.begin(),
  397. E = Files.end(); I != E; ++I) {
  398. // Start a new line if this would exceed the column limit. Make
  399. // sure to leave space for a trailing " \" in case we need to
  400. // break the line on the next iteration.
  401. unsigned N = I->length();
  402. if (Columns + (N + 1) + 2 > MaxColumns) {
  403. OS << " \\\n ";
  404. Columns = 2;
  405. }
  406. OS << ' ';
  407. PrintFilename(OS, *I, OutputFormat);
  408. Columns += N + 1;
  409. }
  410. OS << '\n';
  411. // Create phony targets if requested.
  412. if (PhonyTarget && !Files.empty()) {
  413. // Skip the first entry, this is always the input file itself.
  414. for (std::vector<std::string>::iterator I = Files.begin() + 1,
  415. E = Files.end(); I != E; ++I) {
  416. OS << '\n';
  417. PrintFilename(OS, *I, OutputFormat);
  418. OS << ":\n";
  419. }
  420. }
  421. }
  422. bool DFGASTReaderListener::visitInputFile(llvm::StringRef Filename,
  423. bool IsSystem, bool IsOverridden) {
  424. assert(!IsSystem || needsSystemInputFileVisitation());
  425. if (IsOverridden)
  426. return true;
  427. Parent.AddFilename(Filename);
  428. return true;
  429. }
  430. void DFGASTReaderListener::visitModuleFile(llvm::StringRef Filename) {
  431. if (Parent.includeModuleFiles())
  432. Parent.AddFilename(Filename);
  433. }