1 //===-- FileCollector.cpp ---------------------------------------*- C++ -*-===// 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 #include "llvm/Support/FileCollector.h" 10 #include "llvm/ADT/SmallString.h" 11 #include "llvm/Support/FileSystem.h" 12 #include "llvm/Support/Path.h" 13 #include "llvm/Support/Process.h" 14 15 using namespace llvm; 16 17 static bool isCaseSensitivePath(StringRef Path) { 18 SmallString<256> TmpDest = Path, UpperDest, RealDest; 19 20 // Remove component traversals, links, etc. 21 if (!sys::fs::real_path(Path, TmpDest)) 22 return true; // Current default value in vfs.yaml 23 Path = TmpDest; 24 25 // Change path to all upper case and ask for its real path, if the latter 26 // exists and is equal to path, it's not case sensitive. Default to case 27 // sensitive in the absence of real_path, since this is the YAMLVFSWriter 28 // default. 29 UpperDest = Path.upper(); 30 if (sys::fs::real_path(UpperDest, RealDest) && Path.equals(RealDest)) 31 return false; 32 return true; 33 } 34 35 FileCollector::FileCollector(std::string Root, std::string OverlayRoot) 36 : Root(std::move(Root)), OverlayRoot(std::move(OverlayRoot)) { 37 sys::fs::create_directories(this->Root, true); 38 } 39 40 bool FileCollector::getRealPath(StringRef SrcPath, 41 SmallVectorImpl<char> &Result) { 42 SmallString<256> RealPath; 43 StringRef FileName = sys::path::filename(SrcPath); 44 std::string Directory = sys::path::parent_path(SrcPath).str(); 45 auto DirWithSymlink = SymlinkMap.find(Directory); 46 47 // Use real_path to fix any symbolic link component present in a path. 48 // Computing the real path is expensive, cache the search through the parent 49 // path Directory. 50 if (DirWithSymlink == SymlinkMap.end()) { 51 auto EC = sys::fs::real_path(Directory, RealPath); 52 if (EC) 53 return false; 54 SymlinkMap[Directory] = std::string(RealPath.str()); 55 } else { 56 RealPath = DirWithSymlink->second; 57 } 58 59 sys::path::append(RealPath, FileName); 60 Result.swap(RealPath); 61 return true; 62 } 63 64 void FileCollector::addFile(const Twine &File) { 65 std::lock_guard<std::mutex> lock(Mutex); 66 std::string FileStr = File.str(); 67 if (markAsSeen(FileStr)) 68 addFileImpl(FileStr); 69 } 70 71 void FileCollector::addDirectory(const Twine &Dir) { 72 assert(sys::fs::is_directory(Dir)); 73 std::error_code EC; 74 addDirectoryImpl(Dir, vfs::getRealFileSystem(), EC); 75 } 76 77 void FileCollector::addFileImpl(StringRef SrcPath) { 78 // We need an absolute src path to append to the root. 79 SmallString<256> AbsoluteSrc = SrcPath; 80 sys::fs::make_absolute(AbsoluteSrc); 81 82 // Canonicalize src to a native path to avoid mixed separator styles. 83 sys::path::native(AbsoluteSrc); 84 85 // Remove redundant leading "./" pieces and consecutive separators. 86 AbsoluteSrc = sys::path::remove_leading_dotslash(AbsoluteSrc); 87 88 // Canonicalize the source path by removing "..", "." components. 89 SmallString<256> VirtualPath = AbsoluteSrc; 90 sys::path::remove_dots(VirtualPath, /*remove_dot_dot=*/true); 91 92 // If a ".." component is present after a symlink component, remove_dots may 93 // lead to the wrong real destination path. Let the source be canonicalized 94 // like that but make sure we always use the real path for the destination. 95 SmallString<256> CopyFrom; 96 if (!getRealPath(AbsoluteSrc, CopyFrom)) 97 CopyFrom = VirtualPath; 98 99 SmallString<256> DstPath = StringRef(Root); 100 sys::path::append(DstPath, sys::path::relative_path(CopyFrom)); 101 102 // Always map a canonical src path to its real path into the YAML, by doing 103 // this we map different virtual src paths to the same entry in the VFS 104 // overlay, which is a way to emulate symlink inside the VFS; this is also 105 // needed for correctness, not doing that can lead to module redefinition 106 // errors. 107 addFileToMapping(VirtualPath, DstPath); 108 } 109 110 llvm::vfs::directory_iterator 111 FileCollector::addDirectoryImpl(const llvm::Twine &Dir, 112 IntrusiveRefCntPtr<vfs::FileSystem> FS, 113 std::error_code &EC) { 114 auto It = FS->dir_begin(Dir, EC); 115 if (EC) 116 return It; 117 addFile(Dir); 118 for (; !EC && It != llvm::vfs::directory_iterator(); It.increment(EC)) { 119 if (It->type() == sys::fs::file_type::regular_file || 120 It->type() == sys::fs::file_type::directory_file || 121 It->type() == sys::fs::file_type::symlink_file) { 122 addFile(It->path()); 123 } 124 } 125 if (EC) 126 return It; 127 // Return a new iterator. 128 return FS->dir_begin(Dir, EC); 129 } 130 131 /// Set the access and modification time for the given file from the given 132 /// status object. 133 static std::error_code 134 copyAccessAndModificationTime(StringRef Filename, 135 const sys::fs::file_status &Stat) { 136 int FD; 137 138 if (auto EC = 139 sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting)) 140 return EC; 141 142 if (auto EC = sys::fs::setLastAccessAndModificationTime( 143 FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime())) 144 return EC; 145 146 if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD)) 147 return EC; 148 149 return {}; 150 } 151 152 std::error_code FileCollector::copyFiles(bool StopOnError) { 153 for (auto &entry : VFSWriter.getMappings()) { 154 // Create directory tree. 155 if (std::error_code EC = 156 sys::fs::create_directories(sys::path::parent_path(entry.RPath), 157 /*IgnoreExisting=*/true)) { 158 if (StopOnError) 159 return EC; 160 } 161 162 // Get the status of the original file/directory. 163 sys::fs::file_status Stat; 164 if (std::error_code EC = sys::fs::status(entry.VPath, Stat)) { 165 if (StopOnError) 166 return EC; 167 continue; 168 } 169 170 if (Stat.type() == sys::fs::file_type::directory_file) { 171 // Construct a directory when it's just a directory entry. 172 if (std::error_code EC = 173 sys::fs::create_directories(entry.RPath, 174 /*IgnoreExisting=*/true)) { 175 if (StopOnError) 176 return EC; 177 } 178 continue; 179 } 180 181 // Copy file over. 182 if (std::error_code EC = sys::fs::copy_file(entry.VPath, entry.RPath)) { 183 if (StopOnError) 184 return EC; 185 } 186 187 // Copy over permissions. 188 if (auto perms = sys::fs::getPermissions(entry.VPath)) { 189 if (std::error_code EC = sys::fs::setPermissions(entry.RPath, *perms)) { 190 if (StopOnError) 191 return EC; 192 } 193 } 194 195 // Copy over modification time. 196 copyAccessAndModificationTime(entry.RPath, Stat); 197 } 198 return {}; 199 } 200 201 std::error_code FileCollector::writeMapping(StringRef MappingFile) { 202 std::lock_guard<std::mutex> lock(Mutex); 203 204 VFSWriter.setOverlayDir(OverlayRoot); 205 VFSWriter.setCaseSensitivity(isCaseSensitivePath(OverlayRoot)); 206 VFSWriter.setUseExternalNames(false); 207 208 std::error_code EC; 209 raw_fd_ostream os(MappingFile, EC, sys::fs::OF_Text); 210 if (EC) 211 return EC; 212 213 VFSWriter.write(os); 214 215 return {}; 216 } 217 218 namespace llvm { 219 220 class FileCollectorFileSystem : public vfs::FileSystem { 221 public: 222 explicit FileCollectorFileSystem(IntrusiveRefCntPtr<vfs::FileSystem> FS, 223 std::shared_ptr<FileCollector> Collector) 224 : FS(std::move(FS)), Collector(std::move(Collector)) {} 225 226 llvm::ErrorOr<llvm::vfs::Status> status(const Twine &Path) override { 227 auto Result = FS->status(Path); 228 if (Result && Result->exists()) 229 Collector->addFile(Path); 230 return Result; 231 } 232 233 llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>> 234 openFileForRead(const Twine &Path) override { 235 auto Result = FS->openFileForRead(Path); 236 if (Result && *Result) 237 Collector->addFile(Path); 238 return Result; 239 } 240 241 llvm::vfs::directory_iterator dir_begin(const llvm::Twine &Dir, 242 std::error_code &EC) override { 243 return Collector->addDirectoryImpl(Dir, FS, EC); 244 } 245 246 std::error_code getRealPath(const Twine &Path, 247 SmallVectorImpl<char> &Output) const override { 248 auto EC = FS->getRealPath(Path, Output); 249 if (!EC) { 250 Collector->addFile(Path); 251 if (Output.size() > 0) 252 Collector->addFile(Output); 253 } 254 return EC; 255 } 256 257 std::error_code isLocal(const Twine &Path, bool &Result) override { 258 return FS->isLocal(Path, Result); 259 } 260 261 llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override { 262 return FS->getCurrentWorkingDirectory(); 263 } 264 265 std::error_code setCurrentWorkingDirectory(const llvm::Twine &Path) override { 266 return FS->setCurrentWorkingDirectory(Path); 267 } 268 269 private: 270 IntrusiveRefCntPtr<vfs::FileSystem> FS; 271 std::shared_ptr<FileCollector> Collector; 272 }; 273 274 } // namespace llvm 275 276 IntrusiveRefCntPtr<vfs::FileSystem> 277 FileCollector::createCollectorVFS(IntrusiveRefCntPtr<vfs::FileSystem> BaseFS, 278 std::shared_ptr<FileCollector> Collector) { 279 return new FileCollectorFileSystem(std::move(BaseFS), std::move(Collector)); 280 } 281