ModuleDependencyCollector.cpp 9.6 KB

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