1 //===--- HeaderIncludes.cpp - Generate Header Includes --------------------===//
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 #include "clang/Frontend/Utils.h"
11 #include "clang/Basic/SourceManager.h"
12 #include "clang/Frontend/FrontendDiagnostic.h"
13 #include "clang/Lex/Preprocessor.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/Support/raw_ostream.h"
16 using namespace clang;
17 
18 namespace {
19 class HeaderIncludesCallback : public PPCallbacks {
20   SourceManager &SM;
21   raw_ostream *OutputFile;
22   unsigned CurrentIncludeDepth;
23   bool HasProcessedPredefines;
24   bool OwnsOutputFile;
25   bool ShowAllHeaders;
26   bool ShowDepth;
27   bool MSStyle;
28 
29 public:
30   HeaderIncludesCallback(const Preprocessor *PP, bool ShowAllHeaders_,
31                          raw_ostream *OutputFile_, bool OwnsOutputFile_,
32                          bool ShowDepth_, bool MSStyle_)
33     : SM(PP->getSourceManager()), OutputFile(OutputFile_),
34       CurrentIncludeDepth(0), HasProcessedPredefines(false),
35       OwnsOutputFile(OwnsOutputFile_), ShowAllHeaders(ShowAllHeaders_),
36       ShowDepth(ShowDepth_), MSStyle(MSStyle_) {}
37 
38   ~HeaderIncludesCallback() override {
39     if (OwnsOutputFile)
40       delete OutputFile;
41   }
42 
43   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
44                    SrcMgr::CharacteristicKind FileType,
45                    FileID PrevFID) override;
46 };
47 }
48 
49 static void PrintHeaderInfo(raw_ostream *OutputFile, const char* Filename,
50                             bool ShowDepth, unsigned CurrentIncludeDepth,
51                             bool MSStyle) {
52     // Write to a temporary string to avoid unnecessary flushing on errs().
53     SmallString<512> Pathname(Filename);
54     if (!MSStyle)
55       Lexer::Stringify(Pathname);
56 
57     SmallString<256> Msg;
58     if (MSStyle)
59       Msg += "Note: including file:";
60 
61     if (ShowDepth) {
62       // The main source file is at depth 1, so skip one dot.
63       for (unsigned i = 1; i != CurrentIncludeDepth; ++i)
64         Msg += MSStyle ? ' ' : '.';
65 
66       if (!MSStyle)
67         Msg += ' ';
68     }
69     Msg += Pathname;
70     Msg += '\n';
71 
72     OutputFile->write(Msg.data(), Msg.size());
73     OutputFile->flush();
74 }
75 
76 void clang::AttachHeaderIncludeGen(Preprocessor &PP,
77                                    const std::vector<std::string> &ExtraHeaders,
78                                    bool ShowAllHeaders,
79                                    StringRef OutputPath, bool ShowDepth,
80                                    bool MSStyle) {
81   raw_ostream *OutputFile = MSStyle ? &llvm::outs() : &llvm::errs();
82   bool OwnsOutputFile = false;
83 
84   // Open the output file, if used.
85   if (!OutputPath.empty()) {
86     std::error_code EC;
87     llvm::raw_fd_ostream *OS = new llvm::raw_fd_ostream(
88         OutputPath.str(), EC, llvm::sys::fs::F_Append | llvm::sys::fs::F_Text);
89     if (EC) {
90       PP.getDiagnostics().Report(clang::diag::warn_fe_cc_print_header_failure)
91           << EC.message();
92       delete OS;
93     } else {
94       OS->SetUnbuffered();
95       OS->SetUseAtomicWrites(true);
96       OutputFile = OS;
97       OwnsOutputFile = true;
98     }
99   }
100 
101   // Print header info for extra headers, pretending they were discovered
102   // by the regular preprocessor. The primary use case is to support
103   // proper generation of Make / Ninja file dependencies for implicit includes,
104   // such as sanitizer blacklists. It's only important for cl.exe
105   // compatibility, the GNU way to generate rules is -M / -MM / -MD / -MMD.
106   for (auto Header : ExtraHeaders) {
107     PrintHeaderInfo(OutputFile, Header.c_str(), ShowDepth, 2, MSStyle);
108   }
109   PP.addPPCallbacks(llvm::make_unique<HeaderIncludesCallback>(&PP,
110                                                               ShowAllHeaders,
111                                                               OutputFile,
112                                                               OwnsOutputFile,
113                                                               ShowDepth,
114                                                               MSStyle));
115 }
116 
117 void HeaderIncludesCallback::FileChanged(SourceLocation Loc,
118                                          FileChangeReason Reason,
119                                        SrcMgr::CharacteristicKind NewFileType,
120                                        FileID PrevFID) {
121   // Unless we are exiting a #include, make sure to skip ahead to the line the
122   // #include directive was at.
123   PresumedLoc UserLoc = SM.getPresumedLoc(Loc);
124   if (UserLoc.isInvalid())
125     return;
126 
127   // Adjust the current include depth.
128   if (Reason == PPCallbacks::EnterFile) {
129     ++CurrentIncludeDepth;
130   } else if (Reason == PPCallbacks::ExitFile) {
131     if (CurrentIncludeDepth)
132       --CurrentIncludeDepth;
133 
134     // We track when we are done with the predefines by watching for the first
135     // place where we drop back to a nesting depth of 1.
136     if (CurrentIncludeDepth == 1 && !HasProcessedPredefines)
137       HasProcessedPredefines = true;
138 
139     return;
140   } else
141     return;
142 
143   // Show the header if we are (a) past the predefines, or (b) showing all
144   // headers and in the predefines at a depth past the initial file and command
145   // line buffers.
146   bool ShowHeader = (HasProcessedPredefines ||
147                      (ShowAllHeaders && CurrentIncludeDepth > 2));
148 
149   // Dump the header include information we are past the predefines buffer or
150   // are showing all headers.
151   if (ShowHeader && Reason == PPCallbacks::EnterFile) {
152     PrintHeaderInfo(OutputFile, UserLoc.getFilename(),
153                     ShowDepth, CurrentIncludeDepth, MSStyle);
154   }
155 }
156