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