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