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