xref: /llvm-project/clang/lib/Frontend/ModuleDependencyCollector.cpp (revision 4c20bef1ef1d29e8824dbf68ee91f072dd1b2f09)
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/Frontend/Utils.h"
15 #include "clang/Lex/Preprocessor.h"
16 #include "clang/Serialization/ASTReader.h"
17 #include "llvm/ADT/StringMap.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(const FileEntry &File) override {
47     StringRef HeaderPath = File.getName();
48     if (llvm::sys::path::is_absolute(HeaderPath))
49       Collector.addFile(HeaderPath);
50   }
51 };
52 
53 }
54 
55 // TODO: move this to Support/Path.h and check for HAVE_REALPATH?
56 static bool real_path(StringRef SrcPath, SmallVectorImpl<char> &RealPath) {
57 #ifdef LLVM_ON_UNIX
58   char CanonicalPath[PATH_MAX];
59 
60   // TODO: emit a warning in case this fails...?
61   if (!realpath(SrcPath.str().c_str(), CanonicalPath))
62     return false;
63 
64   SmallString<256> RPath(CanonicalPath);
65   RealPath.swap(RPath);
66   return true;
67 #else
68   // FIXME: Add support for systems without realpath.
69   return false;
70 #endif
71 }
72 
73 void ModuleDependencyCollector::attachToASTReader(ASTReader &R) {
74   R.addListener(llvm::make_unique<ModuleDependencyListener>(*this));
75 }
76 
77 void ModuleDependencyCollector::attachToPreprocessor(Preprocessor &PP) {
78   PP.getHeaderSearchInfo().getModuleMap().addModuleMapCallbacks(
79       llvm::make_unique<ModuleDependencyMMCallbacks>(*this));
80 }
81 
82 static bool isCaseSensitivePath(StringRef Path) {
83   SmallString<PATH_MAX> TmpDest = Path, UpperDest, RealDest;
84   // Remove component traversals, links, etc.
85   if (!real_path(Path, TmpDest))
86     return true; // Current default value in vfs.yaml
87   Path = TmpDest;
88 
89   // Change path to all upper case and ask for its real path, if the latter
90   // exists and is equal to Path, it's not case sensitive. Default to case
91   // sensitive in the absense of realpath, since this is what the VFSWriter
92   // already expects when sensitivity isn't setup.
93   for (auto &C : Path)
94     UpperDest.push_back(std::toupper(C));
95   if (real_path(UpperDest, RealDest) && Path.equals(RealDest))
96     return false;
97   return true;
98 }
99 
100 void ModuleDependencyCollector::writeFileMap() {
101   if (Seen.empty())
102     return;
103 
104   StringRef VFSDir = getDest();
105 
106   // Default to use relative overlay directories in the VFS yaml file. This
107   // allows crash reproducer scripts to work across machines.
108   VFSWriter.setOverlayDir(VFSDir);
109 
110   // Explicitly set case sensitivity for the YAML writer. For that, find out
111   // the sensitivity at the path where the headers all collected to.
112   VFSWriter.setCaseSensitivity(isCaseSensitivePath(VFSDir));
113 
114   std::error_code EC;
115   SmallString<256> YAMLPath = VFSDir;
116   llvm::sys::path::append(YAMLPath, "vfs.yaml");
117   llvm::raw_fd_ostream OS(YAMLPath, EC, llvm::sys::fs::F_Text);
118   if (EC) {
119     HasErrors = true;
120     return;
121   }
122   VFSWriter.write(OS);
123 }
124 
125 bool ModuleDependencyCollector::getRealPath(StringRef SrcPath,
126                                             SmallVectorImpl<char> &Result) {
127   using namespace llvm::sys;
128   SmallString<256> RealPath;
129   StringRef FileName = path::filename(SrcPath);
130   std::string Dir = path::parent_path(SrcPath).str();
131   auto DirWithSymLink = SymLinkMap.find(Dir);
132 
133   // Use real_path to fix any symbolic link component present in a path.
134   // Computing the real path is expensive, cache the search through the
135   // parent path directory.
136   if (DirWithSymLink == SymLinkMap.end()) {
137     if (!real_path(Dir, RealPath))
138       return false;
139     SymLinkMap[Dir] = RealPath.str();
140   } else {
141     RealPath = DirWithSymLink->second;
142   }
143 
144   path::append(RealPath, FileName);
145   Result.swap(RealPath);
146   return true;
147 }
148 
149 std::error_code ModuleDependencyCollector::copyToRoot(StringRef Src) {
150   using namespace llvm::sys;
151 
152   // We need an absolute path to append to the root.
153   SmallString<256> AbsoluteSrc = Src;
154   fs::make_absolute(AbsoluteSrc);
155   // Canonicalize to a native path to avoid mixed separator styles.
156   path::native(AbsoluteSrc);
157   // Remove redundant leading "./" pieces and consecutive separators.
158   AbsoluteSrc = path::remove_leading_dotslash(AbsoluteSrc);
159 
160   // Canonicalize path by removing "..", "." components.
161   SmallString<256> CanonicalPath = AbsoluteSrc;
162   path::remove_dots(CanonicalPath, /*remove_dot_dot=*/true);
163 
164   // If a ".." component is present after a symlink component, remove_dots may
165   // lead to the wrong real destination path. Let the source be canonicalized
166   // like that but make sure the destination uses the real path.
167   bool HasDotDotInPath =
168       std::count(path::begin(AbsoluteSrc), path::end(AbsoluteSrc), "..") > 0;
169   SmallString<256> RealPath;
170   bool HasRemovedSymlinkComponent = HasDotDotInPath &&
171                              getRealPath(AbsoluteSrc, RealPath) &&
172                              !StringRef(CanonicalPath).equals(RealPath);
173 
174   // Build the destination path.
175   SmallString<256> Dest = getDest();
176   path::append(Dest, path::relative_path(HasRemovedSymlinkComponent ? RealPath
177                                                              : CanonicalPath));
178 
179   // Copy the file into place.
180   if (std::error_code EC = fs::create_directories(path::parent_path(Dest),
181                                                    /*IgnoreExisting=*/true))
182     return EC;
183   if (std::error_code EC = fs::copy_file(
184           HasRemovedSymlinkComponent ? RealPath : CanonicalPath, Dest))
185     return EC;
186 
187   // Use the canonical path under the root for the file mapping. Also create
188   // an additional entry for the real path.
189   addFileMapping(CanonicalPath, Dest);
190   if (HasRemovedSymlinkComponent)
191     addFileMapping(RealPath, Dest);
192 
193   return std::error_code();
194 }
195 
196 void ModuleDependencyCollector::addFile(StringRef Filename) {
197   if (insertSeen(Filename))
198     if (copyToRoot(Filename))
199       HasErrors = true;
200 }
201