ModuleDependencyCollector.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. public:
  27. ModuleDependencyListener(ModuleDependencyCollector &Collector)
  28. : Collector(Collector) {}
  29. bool needsInputFileVisitation() override { return true; }
  30. bool needsSystemInputFileVisitation() override { return true; }
  31. bool visitInputFile(StringRef Filename, bool IsSystem, bool IsOverridden,
  32. bool IsExplicitModule) override {
  33. Collector.addFile(Filename);
  34. return true;
  35. }
  36. };
  37. struct ModuleDependencyPPCallbacks : public PPCallbacks {
  38. ModuleDependencyCollector &Collector;
  39. SourceManager &SM;
  40. ModuleDependencyPPCallbacks(ModuleDependencyCollector &Collector,
  41. SourceManager &SM)
  42. : Collector(Collector), SM(SM) {}
  43. void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
  44. StringRef FileName, bool IsAngled,
  45. CharSourceRange FilenameRange, const FileEntry *File,
  46. StringRef SearchPath, StringRef RelativePath,
  47. const Module *Imported,
  48. SrcMgr::CharacteristicKind FileType) override {
  49. if (!File)
  50. return;
  51. Collector.addFile(File->getName());
  52. }
  53. };
  54. struct ModuleDependencyMMCallbacks : public ModuleMapCallbacks {
  55. ModuleDependencyCollector &Collector;
  56. ModuleDependencyMMCallbacks(ModuleDependencyCollector &Collector)
  57. : Collector(Collector) {}
  58. void moduleMapAddHeader(StringRef HeaderPath) override {
  59. if (llvm::sys::path::is_absolute(HeaderPath))
  60. Collector.addFile(HeaderPath);
  61. }
  62. void moduleMapAddUmbrellaHeader(FileManager *FileMgr,
  63. const FileEntry *Header) override {
  64. StringRef HeaderFilename = Header->getName();
  65. moduleMapAddHeader(HeaderFilename);
  66. // The FileManager can find and cache the symbolic link for a framework
  67. // header before its real path, this means a module can have some of its
  68. // headers to use other paths. Although this is usually not a problem, it's
  69. // inconsistent, and not collecting the original path header leads to
  70. // umbrella clashes while rebuilding modules in the crash reproducer. For
  71. // example:
  72. // ApplicationServices.framework/Frameworks/ImageIO.framework/ImageIO.h
  73. // instead of:
  74. // ImageIO.framework/ImageIO.h
  75. //
  76. // FIXME: this shouldn't be necessary once we have FileName instances
  77. // around instead of FileEntry ones. For now, make sure we collect all
  78. // that we need for the reproducer to work correctly.
  79. StringRef UmbreallDirFromHeader =
  80. llvm::sys::path::parent_path(HeaderFilename);
  81. StringRef UmbrellaDir = Header->getDir()->getName();
  82. if (!UmbrellaDir.equals(UmbreallDirFromHeader)) {
  83. SmallString<128> AltHeaderFilename;
  84. llvm::sys::path::append(AltHeaderFilename, UmbrellaDir,
  85. llvm::sys::path::filename(HeaderFilename));
  86. if (FileMgr->getFile(AltHeaderFilename))
  87. moduleMapAddHeader(AltHeaderFilename);
  88. }
  89. }
  90. };
  91. }
  92. void ModuleDependencyCollector::attachToASTReader(ASTReader &R) {
  93. R.addListener(llvm::make_unique<ModuleDependencyListener>(*this));
  94. }
  95. void ModuleDependencyCollector::attachToPreprocessor(Preprocessor &PP) {
  96. PP.addPPCallbacks(llvm::make_unique<ModuleDependencyPPCallbacks>(
  97. *this, PP.getSourceManager()));
  98. PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
  99. llvm::make_unique<ModuleDependencyMMCallbacks>(*this));
  100. }
  101. static bool isCaseSensitivePath(StringRef Path) {
  102. SmallString<256> TmpDest = Path, UpperDest, RealDest;
  103. // Remove component traversals, links, etc.
  104. if (llvm::sys::fs::real_path(Path, TmpDest))
  105. return true; // Current default value in vfs.yaml
  106. Path = TmpDest;
  107. // Change path to all upper case and ask for its real path, if the latter
  108. // exists and is equal to Path, it's not case sensitive. Default to case
  109. // sensitive in the absence of realpath, since this is what the VFSWriter
  110. // already expects when sensitivity isn't setup.
  111. for (auto &C : Path)
  112. UpperDest.push_back(toUppercase(C));
  113. if (!llvm::sys::fs::real_path(UpperDest, RealDest) && Path.equals(RealDest))
  114. return false;
  115. return true;
  116. }
  117. void ModuleDependencyCollector::writeFileMap() {
  118. if (Seen.empty())
  119. return;
  120. StringRef VFSDir = getDest();
  121. // Default to use relative overlay directories in the VFS yaml file. This
  122. // allows crash reproducer scripts to work across machines.
  123. VFSWriter.setOverlayDir(VFSDir);
  124. // Explicitly set case sensitivity for the YAML writer. For that, find out
  125. // the sensitivity at the path where the headers all collected to.
  126. VFSWriter.setCaseSensitivity(isCaseSensitivePath(VFSDir));
  127. // Do not rely on real path names when executing the crash reproducer scripts
  128. // since we only want to actually use the files we have on the VFS cache.
  129. VFSWriter.setUseExternalNames(false);
  130. std::error_code EC;
  131. SmallString<256> YAMLPath = VFSDir;
  132. llvm::sys::path::append(YAMLPath, "vfs.yaml");
  133. llvm::raw_fd_ostream OS(YAMLPath, EC, llvm::sys::fs::OF_Text);
  134. if (EC) {
  135. HasErrors = true;
  136. return;
  137. }
  138. VFSWriter.write(OS);
  139. }
  140. bool ModuleDependencyCollector::getRealPath(StringRef SrcPath,
  141. SmallVectorImpl<char> &Result) {
  142. using namespace llvm::sys;
  143. SmallString<256> RealPath;
  144. StringRef FileName = path::filename(SrcPath);
  145. std::string Dir = path::parent_path(SrcPath).str();
  146. auto DirWithSymLink = SymLinkMap.find(Dir);
  147. // Use real_path to fix any symbolic link component present in a path.
  148. // Computing the real path is expensive, cache the search through the
  149. // parent path directory.
  150. if (DirWithSymLink == SymLinkMap.end()) {
  151. if (llvm::sys::fs::real_path(Dir, RealPath))
  152. return false;
  153. SymLinkMap[Dir] = RealPath.str();
  154. } else {
  155. RealPath = DirWithSymLink->second;
  156. }
  157. path::append(RealPath, FileName);
  158. Result.swap(RealPath);
  159. return true;
  160. }
  161. std::error_code ModuleDependencyCollector::copyToRoot(StringRef Src,
  162. StringRef Dst) {
  163. using namespace llvm::sys;
  164. // We need an absolute src path to append to the root.
  165. SmallString<256> AbsoluteSrc = Src;
  166. fs::make_absolute(AbsoluteSrc);
  167. // Canonicalize src to a native path to avoid mixed separator styles.
  168. path::native(AbsoluteSrc);
  169. // Remove redundant leading "./" pieces and consecutive separators.
  170. AbsoluteSrc = path::remove_leading_dotslash(AbsoluteSrc);
  171. // Canonicalize the source path by removing "..", "." components.
  172. SmallString<256> VirtualPath = AbsoluteSrc;
  173. path::remove_dots(VirtualPath, /*remove_dot_dot=*/true);
  174. // If a ".." component is present after a symlink component, remove_dots may
  175. // lead to the wrong real destination path. Let the source be canonicalized
  176. // like that but make sure we always use the real path for the destination.
  177. SmallString<256> CopyFrom;
  178. if (!getRealPath(AbsoluteSrc, CopyFrom))
  179. CopyFrom = VirtualPath;
  180. SmallString<256> CacheDst = getDest();
  181. if (Dst.empty()) {
  182. // The common case is to map the virtual path to the same path inside the
  183. // cache.
  184. path::append(CacheDst, path::relative_path(CopyFrom));
  185. } else {
  186. // When collecting entries from input vfsoverlays, copy the external
  187. // contents into the cache but still map from the source.
  188. if (!fs::exists(Dst))
  189. return std::error_code();
  190. path::append(CacheDst, Dst);
  191. CopyFrom = Dst;
  192. }
  193. // Copy the file into place.
  194. if (std::error_code EC = fs::create_directories(path::parent_path(CacheDst),
  195. /*IgnoreExisting=*/true))
  196. return EC;
  197. if (std::error_code EC = fs::copy_file(CopyFrom, CacheDst))
  198. return EC;
  199. // Always map a canonical src path to its real path into the YAML, by doing
  200. // this we map different virtual src paths to the same entry in the VFS
  201. // overlay, which is a way to emulate symlink inside the VFS; this is also
  202. // needed for correctness, not doing that can lead to module redefinition
  203. // errors.
  204. addFileMapping(VirtualPath, CacheDst);
  205. return std::error_code();
  206. }
  207. void ModuleDependencyCollector::addFile(StringRef Filename, StringRef FileDst) {
  208. if (insertSeen(Filename))
  209. if (copyToRoot(Filename, FileDst))
  210. HasErrors = true;
  211. }