HeaderIncludeGen.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. //===-- HeaderIncludeGen.cpp - Generate Header Includes -------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Frontend/DependencyOutputOptions.h"
  9. #include "clang/Frontend/Utils.h"
  10. #include "clang/Basic/SourceManager.h"
  11. #include "clang/Frontend/FrontendDiagnostic.h"
  12. #include "clang/Lex/Preprocessor.h"
  13. #include "llvm/ADT/SmallString.h"
  14. #include "llvm/Support/JSON.h"
  15. #include "llvm/Support/raw_ostream.h"
  16. using namespace clang;
  17. namespace {
  18. class HeaderIncludesCallback : public PPCallbacks {
  19. SourceManager &SM;
  20. raw_ostream *OutputFile;
  21. const DependencyOutputOptions &DepOpts;
  22. unsigned CurrentIncludeDepth;
  23. bool HasProcessedPredefines;
  24. bool OwnsOutputFile;
  25. bool ShowAllHeaders;
  26. bool ShowDepth;
  27. bool MSStyle;
  28. public:
  29. HeaderIncludesCallback(const Preprocessor *PP, bool ShowAllHeaders_,
  30. raw_ostream *OutputFile_,
  31. const DependencyOutputOptions &DepOpts,
  32. bool OwnsOutputFile_, bool ShowDepth_, bool MSStyle_)
  33. : SM(PP->getSourceManager()), OutputFile(OutputFile_), DepOpts(DepOpts),
  34. CurrentIncludeDepth(0), HasProcessedPredefines(false),
  35. OwnsOutputFile(OwnsOutputFile_), ShowAllHeaders(ShowAllHeaders_),
  36. ShowDepth(ShowDepth_), MSStyle(MSStyle_) {}
  37. ~HeaderIncludesCallback() override {
  38. if (OwnsOutputFile)
  39. delete OutputFile;
  40. }
  41. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  42. SrcMgr::CharacteristicKind FileType,
  43. FileID PrevFID) override;
  44. void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
  45. SrcMgr::CharacteristicKind FileType) override;
  46. };
  47. /// A callback for emitting header usage information to a file in JSON. Each
  48. /// line in the file is a JSON object that includes the source file name and
  49. /// the list of headers directly or indirectly included from it. For example:
  50. ///
  51. /// {"source":"/tmp/foo.c",
  52. /// "includes":["/usr/include/stdio.h", "/usr/include/stdlib.h"]}
  53. ///
  54. /// To reduce the amount of data written to the file, we only record system
  55. /// headers that are directly included from a file that isn't in the system
  56. /// directory.
  57. class HeaderIncludesJSONCallback : public PPCallbacks {
  58. SourceManager &SM;
  59. raw_ostream *OutputFile;
  60. bool OwnsOutputFile;
  61. SmallVector<std::string, 16> IncludedHeaders;
  62. public:
  63. HeaderIncludesJSONCallback(const Preprocessor *PP, raw_ostream *OutputFile_,
  64. bool OwnsOutputFile_)
  65. : SM(PP->getSourceManager()), OutputFile(OutputFile_),
  66. OwnsOutputFile(OwnsOutputFile_) {}
  67. ~HeaderIncludesJSONCallback() override {
  68. if (OwnsOutputFile)
  69. delete OutputFile;
  70. }
  71. void EndOfMainFile() override;
  72. void FileChanged(SourceLocation Loc, FileChangeReason Reason,
  73. SrcMgr::CharacteristicKind FileType,
  74. FileID PrevFID) override;
  75. void FileSkipped(const FileEntryRef &SkippedFile, const Token &FilenameTok,
  76. SrcMgr::CharacteristicKind FileType) override;
  77. };
  78. }
  79. static void PrintHeaderInfo(raw_ostream *OutputFile, StringRef Filename,
  80. bool ShowDepth, unsigned CurrentIncludeDepth,
  81. bool MSStyle) {
  82. // Write to a temporary string to avoid unnecessary flushing on errs().
  83. SmallString<512> Pathname(Filename);
  84. if (!MSStyle)
  85. Lexer::Stringify(Pathname);
  86. SmallString<256> Msg;
  87. if (MSStyle)
  88. Msg += "Note: including file:";
  89. if (ShowDepth) {
  90. // The main source file is at depth 1, so skip one dot.
  91. for (unsigned i = 1; i != CurrentIncludeDepth; ++i)
  92. Msg += MSStyle ? ' ' : '.';
  93. if (!MSStyle)
  94. Msg += ' ';
  95. }
  96. Msg += Pathname;
  97. Msg += '\n';
  98. *OutputFile << Msg;
  99. OutputFile->flush();
  100. }
  101. void clang::AttachHeaderIncludeGen(Preprocessor &PP,
  102. const DependencyOutputOptions &DepOpts,
  103. bool ShowAllHeaders, StringRef OutputPath,
  104. bool ShowDepth, bool MSStyle) {
  105. raw_ostream *OutputFile = &llvm::errs();
  106. bool OwnsOutputFile = false;
  107. // Choose output stream, when printing in cl.exe /showIncludes style.
  108. if (MSStyle) {
  109. switch (DepOpts.ShowIncludesDest) {
  110. default:
  111. llvm_unreachable("Invalid destination for /showIncludes output!");
  112. case ShowIncludesDestination::Stderr:
  113. OutputFile = &llvm::errs();
  114. break;
  115. case ShowIncludesDestination::Stdout:
  116. OutputFile = &llvm::outs();
  117. break;
  118. }
  119. }
  120. // Open the output file, if used.
  121. if (!OutputPath.empty()) {
  122. std::error_code EC;
  123. llvm::raw_fd_ostream *OS = new llvm::raw_fd_ostream(
  124. OutputPath.str(), EC,
  125. llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
  126. if (EC) {
  127. PP.getDiagnostics().Report(clang::diag::warn_fe_cc_print_header_failure)
  128. << EC.message();
  129. delete OS;
  130. } else {
  131. OS->SetUnbuffered();
  132. OutputFile = OS;
  133. OwnsOutputFile = true;
  134. }
  135. }
  136. switch (DepOpts.HeaderIncludeFormat) {
  137. case HIFMT_None:
  138. llvm_unreachable("unexpected header format kind");
  139. case HIFMT_Textual: {
  140. assert(DepOpts.HeaderIncludeFiltering == HIFIL_None &&
  141. "header filtering is currently always disabled when output format is"
  142. "textual");
  143. // Print header info for extra headers, pretending they were discovered by
  144. // the regular preprocessor. The primary use case is to support proper
  145. // generation of Make / Ninja file dependencies for implicit includes, such
  146. // as sanitizer ignorelists. It's only important for cl.exe compatibility,
  147. // the GNU way to generate rules is -M / -MM / -MD / -MMD.
  148. for (const auto &Header : DepOpts.ExtraDeps)
  149. PrintHeaderInfo(OutputFile, Header.first, ShowDepth, 2, MSStyle);
  150. PP.addPPCallbacks(std::make_unique<HeaderIncludesCallback>(
  151. &PP, ShowAllHeaders, OutputFile, DepOpts, OwnsOutputFile, ShowDepth,
  152. MSStyle));
  153. break;
  154. }
  155. case HIFMT_JSON: {
  156. assert(DepOpts.HeaderIncludeFiltering == HIFIL_Only_Direct_System &&
  157. "only-direct-system is the only option for filtering");
  158. PP.addPPCallbacks(std::make_unique<HeaderIncludesJSONCallback>(
  159. &PP, OutputFile, OwnsOutputFile));
  160. break;
  161. }
  162. }
  163. }
  164. void HeaderIncludesCallback::FileChanged(SourceLocation Loc,
  165. FileChangeReason Reason,
  166. SrcMgr::CharacteristicKind NewFileType,
  167. FileID PrevFID) {
  168. // Unless we are exiting a #include, make sure to skip ahead to the line the
  169. // #include directive was at.
  170. PresumedLoc UserLoc = SM.getPresumedLoc(Loc);
  171. if (UserLoc.isInvalid())
  172. return;
  173. // Adjust the current include depth.
  174. if (Reason == PPCallbacks::EnterFile) {
  175. ++CurrentIncludeDepth;
  176. } else if (Reason == PPCallbacks::ExitFile) {
  177. if (CurrentIncludeDepth)
  178. --CurrentIncludeDepth;
  179. // We track when we are done with the predefines by watching for the first
  180. // place where we drop back to a nesting depth of 1.
  181. if (CurrentIncludeDepth == 1 && !HasProcessedPredefines) {
  182. if (!DepOpts.ShowIncludesPretendHeader.empty()) {
  183. PrintHeaderInfo(OutputFile, DepOpts.ShowIncludesPretendHeader,
  184. ShowDepth, 2, MSStyle);
  185. }
  186. HasProcessedPredefines = true;
  187. }
  188. return;
  189. } else
  190. return;
  191. // Show the header if we are (a) past the predefines, or (b) showing all
  192. // headers and in the predefines at a depth past the initial file and command
  193. // line buffers.
  194. bool ShowHeader = (HasProcessedPredefines ||
  195. (ShowAllHeaders && CurrentIncludeDepth > 2));
  196. unsigned IncludeDepth = CurrentIncludeDepth;
  197. if (!HasProcessedPredefines)
  198. --IncludeDepth; // Ignore indent from <built-in>.
  199. else if (!DepOpts.ShowIncludesPretendHeader.empty())
  200. ++IncludeDepth; // Pretend inclusion by ShowIncludesPretendHeader.
  201. if (!DepOpts.IncludeSystemHeaders && isSystem(NewFileType))
  202. ShowHeader = false;
  203. // Dump the header include information we are past the predefines buffer or
  204. // are showing all headers and this isn't the magic implicit <command line>
  205. // header.
  206. // FIXME: Identify headers in a more robust way than comparing their name to
  207. // "<command line>" and "<built-in>" in a bunch of places.
  208. if (ShowHeader && Reason == PPCallbacks::EnterFile &&
  209. UserLoc.getFilename() != StringRef("<command line>")) {
  210. PrintHeaderInfo(OutputFile, UserLoc.getFilename(), ShowDepth, IncludeDepth,
  211. MSStyle);
  212. }
  213. }
  214. void HeaderIncludesCallback::FileSkipped(const FileEntryRef &SkippedFile, const
  215. Token &FilenameTok,
  216. SrcMgr::CharacteristicKind FileType) {
  217. if (!DepOpts.ShowSkippedHeaderIncludes)
  218. return;
  219. if (!DepOpts.IncludeSystemHeaders && isSystem(FileType))
  220. return;
  221. PrintHeaderInfo(OutputFile, SkippedFile.getName(), ShowDepth,
  222. CurrentIncludeDepth + 1, MSStyle);
  223. }
  224. void HeaderIncludesJSONCallback::EndOfMainFile() {
  225. const FileEntry *FE = SM.getFileEntryForID(SM.getMainFileID());
  226. SmallString<256> MainFile(FE->getName());
  227. SM.getFileManager().makeAbsolutePath(MainFile);
  228. std::string Str;
  229. llvm::raw_string_ostream OS(Str);
  230. llvm::json::OStream JOS(OS);
  231. JOS.object([&] {
  232. JOS.attribute("source", MainFile.c_str());
  233. JOS.attributeArray("includes", [&] {
  234. llvm::StringSet<> SeenHeaders;
  235. for (const std::string &H : IncludedHeaders)
  236. if (SeenHeaders.insert(H).second)
  237. JOS.value(H);
  238. });
  239. });
  240. OS << "\n";
  241. if (OutputFile->get_kind() == raw_ostream::OStreamKind::OK_FDStream) {
  242. llvm::raw_fd_ostream *FDS = static_cast<llvm::raw_fd_ostream *>(OutputFile);
  243. if (auto L = FDS->lock())
  244. *OutputFile << Str;
  245. } else
  246. *OutputFile << Str;
  247. }
  248. /// Determine whether the header file should be recorded. The header file should
  249. /// be recorded only if the header file is a system header and the current file
  250. /// isn't a system header.
  251. static bool shouldRecordNewFile(SrcMgr::CharacteristicKind NewFileType,
  252. SourceLocation PrevLoc, SourceManager &SM) {
  253. return SrcMgr::isSystem(NewFileType) && !SM.isInSystemHeader(PrevLoc);
  254. }
  255. void HeaderIncludesJSONCallback::FileChanged(
  256. SourceLocation Loc, FileChangeReason Reason,
  257. SrcMgr::CharacteristicKind NewFileType, FileID PrevFID) {
  258. if (PrevFID.isInvalid() ||
  259. !shouldRecordNewFile(NewFileType, SM.getLocForStartOfFile(PrevFID), SM))
  260. return;
  261. // Unless we are exiting a #include, make sure to skip ahead to the line the
  262. // #include directive was at.
  263. PresumedLoc UserLoc = SM.getPresumedLoc(Loc);
  264. if (UserLoc.isInvalid())
  265. return;
  266. if (Reason == PPCallbacks::EnterFile &&
  267. UserLoc.getFilename() != StringRef("<command line>"))
  268. IncludedHeaders.push_back(UserLoc.getFilename());
  269. }
  270. void HeaderIncludesJSONCallback::FileSkipped(
  271. const FileEntryRef &SkippedFile, const Token &FilenameTok,
  272. SrcMgr::CharacteristicKind FileType) {
  273. if (!shouldRecordNewFile(FileType, FilenameTok.getLocation(), SM))
  274. return;
  275. IncludedHeaders.push_back(SkippedFile.getName().str());
  276. }