ModuleDependencyCollector.cpp 9.7 KB

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