FileCollector.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. #include "llvm/Support/FileCollector.h"
  9. #include "llvm/ADT/SmallString.h"
  10. #include "llvm/ADT/Twine.h"
  11. #include "llvm/Support/FileSystem.h"
  12. #include "llvm/Support/Path.h"
  13. #include "llvm/Support/Process.h"
  14. using namespace llvm;
  15. FileCollectorBase::FileCollectorBase() = default;
  16. FileCollectorBase::~FileCollectorBase() = default;
  17. void FileCollectorBase::addFile(const Twine &File) {
  18. std::lock_guard<std::mutex> lock(Mutex);
  19. std::string FileStr = File.str();
  20. if (markAsSeen(FileStr))
  21. addFileImpl(FileStr);
  22. }
  23. void FileCollectorBase::addDirectory(const Twine &Dir) {
  24. assert(sys::fs::is_directory(Dir));
  25. std::error_code EC;
  26. addDirectoryImpl(Dir, vfs::getRealFileSystem(), EC);
  27. }
  28. static bool isCaseSensitivePath(StringRef Path) {
  29. SmallString<256> TmpDest = Path, UpperDest, RealDest;
  30. // Remove component traversals, links, etc.
  31. if (sys::fs::real_path(Path, TmpDest))
  32. return true; // Current default value in vfs.yaml
  33. Path = TmpDest;
  34. // Change path to all upper case and ask for its real path, if the latter
  35. // exists and is equal to path, it's not case sensitive. Default to case
  36. // sensitive in the absence of real_path, since this is the YAMLVFSWriter
  37. // default.
  38. UpperDest = Path.upper();
  39. if (!sys::fs::real_path(UpperDest, RealDest) && Path.equals(RealDest))
  40. return false;
  41. return true;
  42. }
  43. FileCollector::FileCollector(std::string Root, std::string OverlayRoot)
  44. : Root(std::move(Root)), OverlayRoot(std::move(OverlayRoot)) {
  45. }
  46. void FileCollector::PathCanonicalizer::updateWithRealPath(
  47. SmallVectorImpl<char> &Path) {
  48. StringRef SrcPath(Path.begin(), Path.size());
  49. StringRef Filename = sys::path::filename(SrcPath);
  50. StringRef Directory = sys::path::parent_path(SrcPath);
  51. // Use real_path to fix any symbolic link component present in the directory
  52. // part of the path, caching the search because computing the real path is
  53. // expensive.
  54. SmallString<256> RealPath;
  55. auto DirWithSymlink = CachedDirs.find(Directory);
  56. if (DirWithSymlink == CachedDirs.end()) {
  57. // FIXME: Should this be a call to FileSystem::getRealpath(), in some
  58. // cases? What if there is nothing on disk?
  59. if (sys::fs::real_path(Directory, RealPath))
  60. return;
  61. CachedDirs[Directory] = std::string(RealPath.str());
  62. } else {
  63. RealPath = DirWithSymlink->second;
  64. }
  65. // Finish recreating the path by appending the original filename, since we
  66. // don't need to resolve symlinks in the filename.
  67. //
  68. // FIXME: If we can cope with this, maybe we can cope without calling
  69. // getRealPath() at all when there's no ".." component.
  70. sys::path::append(RealPath, Filename);
  71. // Swap to create the output.
  72. Path.swap(RealPath);
  73. }
  74. /// Make Path absolute.
  75. static void makeAbsolute(SmallVectorImpl<char> &Path) {
  76. // We need an absolute src path to append to the root.
  77. sys::fs::make_absolute(Path);
  78. // Canonicalize src to a native path to avoid mixed separator styles.
  79. sys::path::native(Path);
  80. // Remove redundant leading "./" pieces and consecutive separators.
  81. Path.erase(Path.begin(), sys::path::remove_leading_dotslash(
  82. StringRef(Path.begin(), Path.size()))
  83. .begin());
  84. }
  85. FileCollector::PathCanonicalizer::PathStorage
  86. FileCollector::PathCanonicalizer::canonicalize(StringRef SrcPath) {
  87. PathStorage Paths;
  88. Paths.VirtualPath = SrcPath;
  89. makeAbsolute(Paths.VirtualPath);
  90. // If a ".." component is present after a symlink component, remove_dots may
  91. // lead to the wrong real destination path. Let the source be canonicalized
  92. // like that but make sure we always use the real path for the destination.
  93. Paths.CopyFrom = Paths.VirtualPath;
  94. updateWithRealPath(Paths.CopyFrom);
  95. // Canonicalize the virtual path by removing "..", "." components.
  96. sys::path::remove_dots(Paths.VirtualPath, /*remove_dot_dot=*/true);
  97. return Paths;
  98. }
  99. void FileCollector::addFileImpl(StringRef SrcPath) {
  100. PathCanonicalizer::PathStorage Paths = Canonicalizer.canonicalize(SrcPath);
  101. SmallString<256> DstPath = StringRef(Root);
  102. sys::path::append(DstPath, sys::path::relative_path(Paths.CopyFrom));
  103. // Always map a canonical src path to its real path into the YAML, by doing
  104. // this we map different virtual src paths to the same entry in the VFS
  105. // overlay, which is a way to emulate symlink inside the VFS; this is also
  106. // needed for correctness, not doing that can lead to module redefinition
  107. // errors.
  108. addFileToMapping(Paths.VirtualPath, DstPath);
  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. /// Set the access and modification time for the given file from the given
  131. /// status object.
  132. static std::error_code
  133. copyAccessAndModificationTime(StringRef Filename,
  134. const sys::fs::file_status &Stat) {
  135. int FD;
  136. if (auto EC =
  137. sys::fs::openFileForWrite(Filename, FD, sys::fs::CD_OpenExisting))
  138. return EC;
  139. if (auto EC = sys::fs::setLastAccessAndModificationTime(
  140. FD, Stat.getLastAccessedTime(), Stat.getLastModificationTime()))
  141. return EC;
  142. if (auto EC = sys::Process::SafelyCloseFileDescriptor(FD))
  143. return EC;
  144. return {};
  145. }
  146. std::error_code FileCollector::copyFiles(bool StopOnError) {
  147. auto Err = sys::fs::create_directories(Root, /*IgnoreExisting=*/true);
  148. if (Err) {
  149. return Err;
  150. }
  151. std::lock_guard<std::mutex> lock(Mutex);
  152. for (auto &entry : VFSWriter.getMappings()) {
  153. // Get the status of the original file/directory.
  154. sys::fs::file_status Stat;
  155. if (std::error_code EC = sys::fs::status(entry.VPath, Stat)) {
  156. if (StopOnError)
  157. return EC;
  158. continue;
  159. }
  160. // Continue if the file doesn't exist.
  161. if (Stat.type() == sys::fs::file_type::file_not_found)
  162. continue;
  163. // Create directory tree.
  164. if (std::error_code EC =
  165. sys::fs::create_directories(sys::path::parent_path(entry.RPath),
  166. /*IgnoreExisting=*/true)) {
  167. if (StopOnError)
  168. return EC;
  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. // Copy file over.
  181. if (std::error_code EC = sys::fs::copy_file(entry.VPath, entry.RPath)) {
  182. if (StopOnError)
  183. return EC;
  184. }
  185. // Copy over permissions.
  186. if (auto perms = sys::fs::getPermissions(entry.VPath)) {
  187. if (std::error_code EC = sys::fs::setPermissions(entry.RPath, *perms)) {
  188. if (StopOnError)
  189. return EC;
  190. }
  191. }
  192. // Copy over modification time.
  193. copyAccessAndModificationTime(entry.RPath, Stat);
  194. }
  195. return {};
  196. }
  197. std::error_code FileCollector::writeMapping(StringRef MappingFile) {
  198. std::lock_guard<std::mutex> lock(Mutex);
  199. VFSWriter.setOverlayDir(OverlayRoot);
  200. VFSWriter.setCaseSensitivity(isCaseSensitivePath(OverlayRoot));
  201. VFSWriter.setUseExternalNames(false);
  202. std::error_code EC;
  203. raw_fd_ostream os(MappingFile, EC, sys::fs::OF_TextWithCRLF);
  204. if (EC)
  205. return EC;
  206. VFSWriter.write(os);
  207. return {};
  208. }
  209. namespace llvm {
  210. class FileCollectorFileSystem : public vfs::FileSystem {
  211. public:
  212. explicit FileCollectorFileSystem(IntrusiveRefCntPtr<vfs::FileSystem> FS,
  213. std::shared_ptr<FileCollector> Collector)
  214. : FS(std::move(FS)), Collector(std::move(Collector)) {}
  215. llvm::ErrorOr<llvm::vfs::Status> status(const Twine &Path) override {
  216. auto Result = FS->status(Path);
  217. if (Result && Result->exists())
  218. Collector->addFile(Path);
  219. return Result;
  220. }
  221. llvm::ErrorOr<std::unique_ptr<llvm::vfs::File>>
  222. openFileForRead(const Twine &Path) override {
  223. auto Result = FS->openFileForRead(Path);
  224. if (Result && *Result)
  225. Collector->addFile(Path);
  226. return Result;
  227. }
  228. llvm::vfs::directory_iterator dir_begin(const llvm::Twine &Dir,
  229. std::error_code &EC) override {
  230. return Collector->addDirectoryImpl(Dir, FS, EC);
  231. }
  232. std::error_code getRealPath(const Twine &Path,
  233. SmallVectorImpl<char> &Output) const override {
  234. auto EC = FS->getRealPath(Path, Output);
  235. if (!EC) {
  236. Collector->addFile(Path);
  237. if (Output.size() > 0)
  238. Collector->addFile(Output);
  239. }
  240. return EC;
  241. }
  242. std::error_code isLocal(const Twine &Path, bool &Result) override {
  243. return FS->isLocal(Path, Result);
  244. }
  245. llvm::ErrorOr<std::string> getCurrentWorkingDirectory() const override {
  246. return FS->getCurrentWorkingDirectory();
  247. }
  248. std::error_code setCurrentWorkingDirectory(const llvm::Twine &Path) override {
  249. return FS->setCurrentWorkingDirectory(Path);
  250. }
  251. private:
  252. IntrusiveRefCntPtr<vfs::FileSystem> FS;
  253. std::shared_ptr<FileCollector> Collector;
  254. };
  255. } // namespace llvm
  256. IntrusiveRefCntPtr<vfs::FileSystem>
  257. FileCollector::createCollectorVFS(IntrusiveRefCntPtr<vfs::FileSystem> BaseFS,
  258. std::shared_ptr<FileCollector> Collector) {
  259. return new FileCollectorFileSystem(std::move(BaseFS), std::move(Collector));
  260. }