ModuleDependencyCollector.cpp 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. //===--- ModuleDependencyCollector.cpp - Collect module dependencies ------===//
  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. //
  9. // Collect the dependencies of a set of modules.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Basic/CharInfo.h"
  13. #include "clang/Frontend/Utils.h"
  14. #include "clang/Lex/Preprocessor.h"
  15. #include "clang/Serialization/ASTReader.h"
  16. #include "llvm/ADT/iterator_range.h"
  17. #include "llvm/Config/llvm-config.h"
  18. #include "llvm/Support/FileSystem.h"
  19. #include "llvm/Support/Path.h"
  20. #include "llvm/Support/raw_ostream.h"
  21. using namespace clang;
  22. namespace {
  23. /// Private implementations for ModuleDependencyCollector
  24. class ModuleDependencyListener : public ASTReaderListener {
  25. ModuleDependencyCollector &Collector;
  26. FileManager &FileMgr;
  27. public:
  28. ModuleDependencyListener(ModuleDependencyCollector &Collector,
  29. FileManager &FileMgr)
  30. : Collector(Collector), FileMgr(FileMgr) {}
  31. bool needsInputFileVisitation() override { return true; }
  32. bool needsSystemInputFileVisitation() override { return true; }
  33. bool visitInputFile(StringRef Filename, bool IsSystem, bool IsOverridden,
  34. bool IsExplicitModule) override {
  35. // Run this through the FileManager in order to respect 'use-external-name'
  36. // in case we have a VFS overlay.
  37. if (auto FE = FileMgr.getOptionalFileRef(Filename))
  38. Filename = FE->getName();
  39. Collector.addFile(Filename);
  40. return true;
  41. }
  42. };
  43. struct ModuleDependencyPPCallbacks : public PPCallbacks {
  44. ModuleDependencyCollector &Collector;
  45. SourceManager &SM;
  46. ModuleDependencyPPCallbacks(ModuleDependencyCollector &Collector,
  47. SourceManager &SM)
  48. : Collector(Collector), SM(SM) {}
  49. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  50. StringRef FileName, bool IsAngled,
  51. CharSourceRange FilenameRange,
  52. OptionalFileEntryRef File, StringRef SearchPath,
  53. StringRef RelativePath, const Module *Imported,
  54. SrcMgr::CharacteristicKind FileType) override {
  55. if (!File)
  56. return;
  57. Collector.addFile(File->getName());
  58. }
  59. };
  60. struct ModuleDependencyMMCallbacks : public ModuleMapCallbacks {
  61. ModuleDependencyCollector &Collector;
  62. ModuleDependencyMMCallbacks(ModuleDependencyCollector &Collector)
  63. : Collector(Collector) {}
  64. void moduleMapAddHeader(StringRef HeaderPath) override {
  65. if (llvm::sys::path::is_absolute(HeaderPath))
  66. Collector.addFile(HeaderPath);
  67. }
  68. void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
  69. const FileEntry *Header) override {
  70. StringRef HeaderFilename = Header->getName();
  71. moduleMapAddHeader(HeaderFilename);
  72. // The FileManager can find and cache the symbolic link for a framework
  73. // header before its real path, this means a module can have some of its
  74. // headers to use other paths. Although this is usually not a problem, it's
  75. // inconsistent, and not collecting the original path header leads to
  76. // umbrella clashes while rebuilding modules in the crash reproducer. For
  77. // example:
  78. // ApplicationServices.framework/Frameworks/ImageIO.framework/ImageIO.h
  79. // instead of:
  80. // ImageIO.framework/ImageIO.h
  81. //
  82. // FIXME: this shouldn't be necessary once we have FileName instances
  83. // around instead of FileEntry ones. For now, make sure we collect all
  84. // that we need for the reproducer to work correctly.
  85. StringRef UmbreallDirFromHeader =
  86. llvm::sys::path::parent_path(HeaderFilename);
  87. StringRef UmbrellaDir = Header->getDir()->getName();
  88. if (!UmbrellaDir.equals(UmbreallDirFromHeader)) {
  89. SmallString<128> AltHeaderFilename;
  90. llvm::sys::path::append(AltHeaderFilename, UmbrellaDir,
  91. llvm::sys::path::filename(HeaderFilename));
  92. if (FileMgr->getFile(AltHeaderFilename))
  93. moduleMapAddHeader(AltHeaderFilename);
  94. }
  95. }
  96. };
  97. }
  98. void ModuleDependencyCollector::attachToASTReader(ASTReader &R) {
  99. R.addListener(
  100. std::make_unique<ModuleDependencyListener>(*this, R.getFileManager()));
  101. }
  102. void ModuleDependencyCollector::attachToPreprocessor(Preprocessor &PP) {
  103. PP.addPPCallbacks(std::make_unique<ModuleDependencyPPCallbacks>(
  104. *this, PP.getSourceManager()));
  105. PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
  106. std::make_unique<ModuleDependencyMMCallbacks>(*this));
  107. }
  108. static bool isCaseSensitivePath(StringRef Path) {
  109. SmallString<256> TmpDest = Path, UpperDest, RealDest;
  110. // Remove component traversals, links, etc.
  111. if (llvm::sys::fs::real_path(Path, TmpDest))
  112. return true; // Current default value in vfs.yaml
  113. Path = TmpDest;
  114. // Change path to all upper case and ask for its real path, if the latter
  115. // exists and is equal to Path, it's not case sensitive. Default to case
  116. // sensitive in the absence of realpath, since this is what the VFSWriter
  117. // already expects when sensitivity isn't setup.
  118. for (auto &C : Path)
  119. UpperDest.push_back(toUppercase(C));
  120. if (!llvm::sys::fs::real_path(UpperDest, RealDest) && Path.equals(RealDest))
  121. return false;
  122. return true;
  123. }
  124. void ModuleDependencyCollector::writeFileMap() {
  125. if (Seen.empty())
  126. return;
  127. StringRef VFSDir = getDest();
  128. // Default to use relative overlay directories in the VFS yaml file. This
  129. // allows crash reproducer scripts to work across machines.
  130. VFSWriter.setOverlayDir(VFSDir);
  131. // Explicitly set case sensitivity for the YAML writer. For that, find out
  132. // the sensitivity at the path where the headers all collected to.
  133. VFSWriter.setCaseSensitivity(isCaseSensitivePath(VFSDir));
  134. // Do not rely on real path names when executing the crash reproducer scripts
  135. // since we only want to actually use the files we have on the VFS cache.
  136. VFSWriter.setUseExternalNames(false);
  137. std::error_code EC;
  138. SmallString<256> YAMLPath = VFSDir;
  139. llvm::sys::path::append(YAMLPath, "vfs.yaml");
  140. llvm::raw_fd_ostream OS(YAMLPath, EC, llvm::sys::fs::OF_TextWithCRLF);
  141. if (EC) {
  142. HasErrors = true;
  143. return;
  144. }
  145. VFSWriter.write(OS);
  146. }
  147. std::error_code ModuleDependencyCollector::copyToRoot(StringRef Src,
  148. StringRef Dst) {
  149. using namespace llvm::sys;
  150. llvm::FileCollector::PathCanonicalizer::PathStorage Paths =
  151. Canonicalizer.canonicalize(Src);
  152. SmallString<256> CacheDst = getDest();
  153. if (Dst.empty()) {
  154. // The common case is to map the virtual path to the same path inside the
  155. // cache.
  156. path::append(CacheDst, path::relative_path(Paths.CopyFrom));
  157. } else {
  158. // When collecting entries from input vfsoverlays, copy the external
  159. // contents into the cache but still map from the source.
  160. if (!fs::exists(Dst))
  161. return std::error_code();
  162. path::append(CacheDst, Dst);
  163. Paths.CopyFrom = Dst;
  164. }
  165. // Copy the file into place.
  166. if (std::error_code EC = fs::create_directories(path::parent_path(CacheDst),
  167. /*IgnoreExisting=*/true))
  168. return EC;
  169. if (std::error_code EC = fs::copy_file(Paths.CopyFrom, CacheDst))
  170. return EC;
  171. // Always map a canonical src path to its real path into the YAML, by doing
  172. // this we map different virtual src paths to the same entry in the VFS
  173. // overlay, which is a way to emulate symlink inside the VFS; this is also
  174. // needed for correctness, not doing that can lead to module redefinition
  175. // errors.
  176. addFileMapping(Paths.VirtualPath, CacheDst);
  177. return std::error_code();
  178. }
  179. void ModuleDependencyCollector::addFile(StringRef Filename, StringRef FileDst) {
  180. if (insertSeen(Filename))
  181. if (copyToRoot(Filename, FileDst))
  182. HasErrors = true;
  183. }