14#include "llvm/ADT/ScopeExit.h"
15#include "llvm/Support/Error.h"
16#include "llvm/Support/FileSystem.h"
17#include "llvm/Support/IOSandbox.h"
18#include "llvm/Support/LockFileManager.h"
19#include "llvm/Support/MemoryBuffer.h"
20#include "llvm/Support/Path.h"
27 auto [ByNameIt, ByNameInserted] = ByPath.insert({Path,
nullptr});
28 if (!ByNameIt->second) {
30 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
34 llvm::sys::fs::file_status Status;
35 if (std::error_code EC = llvm::sys::fs::status(Path, Status)) {
37 if (EC != std::errc::no_such_file_or_directory)
40 if (llvm::sys::fs::create_directories(Path))
43 if (llvm::sys::fs::status(Path, Status))
47 llvm::sys::fs::UniqueID UID = Status.getUniqueID();
48 auto [ByUIDIt, ByUIDInserted] = ByUID.insert({UID,
nullptr});
50 ByUIDIt->second = std::make_unique<ModuleCacheDirectory>();
51 ByNameIt->second = ByUIDIt->second.get();
53 return ByNameIt->second;
59 llvm::raw_fd_ostream Out(TimestampFile.str(), EC, llvm::sys::fs::OF_None);
63 time_t PruneAfter,
bool PruneTopLevel,
64 llvm::function_ref<
void(StringRef)> OnPrune) {
65 if (PruneInterval <= 0 || PruneAfter <= 0)
69 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
72 (void)llvm::sys::fs::make_absolute(RootPath);
75 llvm::sys::path::append(TimestampFile,
"modules.timestamp");
78 llvm::sys::fs::file_status StatBuf;
79 if (std::error_code EC = llvm::sys::fs::status(TimestampFile, StatBuf)) {
81 if (EC == std::errc::no_such_file_or_directory)
88 time_t TimestampModTime =
89 llvm::sys::toTimeT(StatBuf.getLastModificationTime());
90 time_t CurrentTime = time(
nullptr);
91 if (CurrentTime - TimestampModTime <= PruneInterval)
99 auto NotifyPruned = [&](StringRef RemovedPath) {
101 OnPrune(RemovedPath);
107 auto TryPruneFile = [&](StringRef FilePath) {
109 StringRef Filename = llvm::sys::path::filename(FilePath);
110 StringRef Extension = llvm::sys::path::extension(FilePath);
111 if (Extension !=
".pcm" && Extension !=
".timestamp" &&
112 Filename !=
"modules.idx")
116 if (Filename ==
"modules.timestamp")
121 if (llvm::sys::fs::status(FilePath, StatBuf))
125 time_t FileAccessTime = llvm::sys::toTimeT(StatBuf.getLastAccessedTime());
126 if (CurrentTime - FileAccessTime <= PruneAfter)
130 if (!llvm::sys::fs::remove(FilePath))
131 NotifyPruned(FilePath);
134 std::string TimestampFilename = FilePath.str() +
".timestamp";
135 if (!llvm::sys::fs::remove(TimestampFilename))
136 NotifyPruned(TimestampFilename);
139 for (llvm::sys::fs::directory_iterator Dir(RootPath, EC), DirEnd;
140 Dir != DirEnd && !EC; Dir.increment(EC)) {
142 if (!llvm::sys::fs::is_directory(Dir->path())) {
144 TryPruneFile(Dir->path());
149 for (llvm::sys::fs::directory_iterator
File(Dir->path(), EC), FileEnd;
150 File != FileEnd && !EC;
File.increment(EC))
151 TryPruneFile(
File->path());
155 if (llvm::sys::fs::directory_iterator(Dir->path(), EC) ==
156 llvm::sys::fs::directory_iterator() &&
158 if (!llvm::sys::fs::remove(Dir->path()))
159 NotifyPruned(Dir->path());
164llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
166 time_t &ModTime,
bool ReadBack) {
167 StringRef Extension = llvm::sys::path::extension(Path);
169 ModelPath +=
"-%%%%%%%%";
170 ModelPath += Extension;
175 llvm::ErrorOr<llvm::sys::fs::TempFile> Temp =
176 llvm::sys::fs::TempFile::createWithErrorCode(ModelPath);
178 if (Temp.getError() != std::errc::no_such_file_or_directory)
179 return Temp.getError();
181 StringRef Dir = llvm::sys::path::parent_path(Path);
182 if (std::error_code InnerEC = llvm::sys::fs::create_directories(Dir))
185 Temp = llvm::sys::fs::TempFile::createWithErrorCode(ModelPath);
187 return Temp.getError();
190 llvm::sys::fs::file_status Status;
191 std::unique_ptr<llvm::MemoryBuffer> Written;
192 auto WriteContentsAndReadBack = [&]() -> std::error_code {
194 llvm::raw_fd_ostream OS(Temp->FD,
false);
195 OS << Buffer.getBuffer();
198 if (std::error_code EC = OS.error()) {
204 if (std::error_code EC = llvm::sys::fs::status(Temp->FD, Status))
207 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf =
208 llvm::MemoryBuffer::getOpenFile(
209 llvm::sys::fs::convertFDToNativeFile(Temp->FD), Path,
210 Status.getSize(),
false);
212 return Buf.getError();
213 Written = std::move(*Buf);
218 if (std::error_code EC = WriteContentsAndReadBack()) {
219 llvm::consumeError(Temp->discard());
225 if (std::error_code EC = Temp->keepWithErrorCode(Path))
228 Size = Status.getSize();
229 ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
231 return std::move(Written);
246 [[maybe_unused]]
const llvm::sys::fs::file_status &Status) {
250 llvm::sys::TimePoint<> Now = std::chrono::system_clock::now();
257 (void)llvm::sys::fs::setLastAccessAndModificationTime(
258 FD.get(), Now, Status.getLastModificationTime());
265 llvm::sys::fs::openNativeFileForRead(
FileName);
267 return FD.takeError();
268 llvm::scope_exit CloseFD([&FD]() { llvm::sys::fs::closeFile(*FD); });
269 llvm::sys::fs::file_status Status;
270 if (std::error_code EC = llvm::sys::fs::status(*FD, Status))
271 return llvm::errorCodeToError(EC);
272 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buf =
273 llvm::MemoryBuffer::getOpenFile(*FD,
FileName, Status.getSize(),
276 return llvm::errorCodeToError(Buf.getError());
277 Size = Status.getSize();
278 ModTime = llvm::sys::toTimeT(Status.getLastModificationTime());
280 return std::move(*Buf);
286class CrossProcessModuleCache :
public ModuleCache {
290 explicit CrossProcessModuleCache()
293 std::unique_ptr<llvm::AdvisoryLock>
294 getLock(StringRef ModuleFilename)
override {
295 return std::make_unique<llvm::LockFileManager>(ModuleFilename);
298 std::time_t getModuleTimestamp(StringRef ModuleFilename)
override {
300 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
302 std::string TimestampFilename =
304 llvm::sys::fs::file_status Status;
305 if (llvm::sys::fs::status(TimestampFilename, Status) != std::error_code{})
307 return llvm::sys::toTimeT(Status.getLastModificationTime());
310 void updateModuleTimestamp(StringRef ModuleFilename)
override {
312 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
316 llvm::raw_fd_ostream
OS(
318 llvm::sys::fs::OF_TextWithCRLF);
321 OS <<
"Timestamp file\n";
326 void maybePrune(StringRef Path, time_t PruneInterval,
327 time_t PruneAfter)
override {
329 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
334 InMemoryModuleCache &getInMemoryModuleCache()
override {
return InMemory; }
335 const InMemoryModuleCache &getInMemoryModuleCache()
const override {
339 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>>
340 write(StringRef Path, std::unique_ptr<llvm::MemoryBuffer> Buffer, off_t &Size,
341 time_t &ModTime)
override {
343 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
345 return writeImpl(Path, *Buffer, Size, ModTime,
true);
348 Expected<std::unique_ptr<llvm::MemoryBuffer>>
349 read(StringRef
FileName, off_t &Size, time_t &ModTime)
override {
351 auto BypassSandbox = llvm::sys::sandbox::scopedDisable();
359 return std::make_shared<CrossProcessModuleCache>();
Defines a logger where each line is written atomically to the file.
static constexpr std::chrono::seconds AccessTimeRefreshInterval(60)
The access time of a module file is only refreshed explicitly when it is older than this interval so ...
static void refreshAccessTime(llvm::sys::fs::file_t FD, const llvm::sys::fs::file_status &Status)
Record that the module file open as FD has just been used by setting its access time to now,...
static void writeTimestampFile(StringRef TimestampFile)
Write a new timestamp file with the given path.
In-memory cache for modules.
The address of an instance of this class represents the identity of a module cache directory.
The module cache used for compiling modules implicitly.
virtual const ModuleCacheDirectory * getDirectoryPtr(StringRef Path)
Returns an opaque pointer representing the module cache directory.
static std::string getTimestampFilename(StringRef FileName)
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
Top level wrappers for InstallAPI frontend operations.
Expected< std::unique_ptr< llvm::MemoryBuffer > > readImpl(StringRef FileName, off_t &Size, time_t &ModTime)
Shared implementation of ModuleCache::read().
std::shared_ptr< ModuleCache > createCrossProcessModuleCache()
Creates new ModuleCache backed by a file system directory that may be operated on by multiple process...
llvm::ErrorOr< std::unique_ptr< llvm::MemoryBuffer > > writeImpl(StringRef Path, llvm::MemoryBufferRef Buffer, off_t &Size, time_t &ModTime, bool ReadBack)
Shared implementation of ModuleCache::write().
void maybePruneImpl(StringRef Path, time_t PruneInterval, time_t PruneAfter, bool PruneTopLevel=false, llvm::function_ref< void(StringRef)> OnPrune={})
Shared implementation of ModuleCache::maybePrune().