xref: /freebsd-src/contrib/llvm-project/llvm/lib/Support/Caching.cpp (revision 7a6dacaca14b62ca4b74406814becb87a3fefac0)
1349cc55cSDimitry Andric //===-Caching.cpp - LLVM Local File Cache ---------------------------------===//
2349cc55cSDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6349cc55cSDimitry Andric //
7349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
8349cc55cSDimitry Andric //
9349cc55cSDimitry Andric // This file implements the localCache function, which simplifies creating,
10349cc55cSDimitry Andric // adding to, and querying a local file system cache. localCache takes care of
11349cc55cSDimitry Andric // periodically pruning older files from the cache using a CachePruningPolicy.
12349cc55cSDimitry Andric //
13349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
14349cc55cSDimitry Andric 
15349cc55cSDimitry Andric #include "llvm/Support/Caching.h"
16349cc55cSDimitry Andric #include "llvm/Support/Errc.h"
17349cc55cSDimitry Andric #include "llvm/Support/FileSystem.h"
18349cc55cSDimitry Andric #include "llvm/Support/MemoryBuffer.h"
19349cc55cSDimitry Andric #include "llvm/Support/Path.h"
20349cc55cSDimitry Andric 
21349cc55cSDimitry Andric #if !defined(_MSC_VER) && !defined(__MINGW32__)
22349cc55cSDimitry Andric #include <unistd.h>
23349cc55cSDimitry Andric #else
24349cc55cSDimitry Andric #include <io.h>
25349cc55cSDimitry Andric #endif
26349cc55cSDimitry Andric 
27349cc55cSDimitry Andric using namespace llvm;
28349cc55cSDimitry Andric 
localCache(const Twine & CacheNameRef,const Twine & TempFilePrefixRef,const Twine & CacheDirectoryPathRef,AddBufferFn AddBuffer)29bdd1243dSDimitry Andric Expected<FileCache> llvm::localCache(const Twine &CacheNameRef,
30bdd1243dSDimitry Andric                                      const Twine &TempFilePrefixRef,
31bdd1243dSDimitry Andric                                      const Twine &CacheDirectoryPathRef,
32349cc55cSDimitry Andric                                      AddBufferFn AddBuffer) {
33349cc55cSDimitry Andric 
34349cc55cSDimitry Andric   // Create local copies which are safely captured-by-copy in lambdas
35349cc55cSDimitry Andric   SmallString<64> CacheName, TempFilePrefix, CacheDirectoryPath;
36349cc55cSDimitry Andric   CacheNameRef.toVector(CacheName);
37349cc55cSDimitry Andric   TempFilePrefixRef.toVector(TempFilePrefix);
38349cc55cSDimitry Andric   CacheDirectoryPathRef.toVector(CacheDirectoryPath);
39349cc55cSDimitry Andric 
40bdd1243dSDimitry Andric   return [=](unsigned Task, StringRef Key,
41bdd1243dSDimitry Andric              const Twine &ModuleName) -> Expected<AddStreamFn> {
42349cc55cSDimitry Andric     // This choice of file name allows the cache to be pruned (see pruneCache()
43349cc55cSDimitry Andric     // in include/llvm/Support/CachePruning.h).
44349cc55cSDimitry Andric     SmallString<64> EntryPath;
45349cc55cSDimitry Andric     sys::path::append(EntryPath, CacheDirectoryPath, "llvmcache-" + Key);
46349cc55cSDimitry Andric     // First, see if we have a cache hit.
47349cc55cSDimitry Andric     SmallString<64> ResultPath;
48349cc55cSDimitry Andric     Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
49349cc55cSDimitry Andric         Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
50349cc55cSDimitry Andric     std::error_code EC;
51349cc55cSDimitry Andric     if (FDOrErr) {
52349cc55cSDimitry Andric       ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
53349cc55cSDimitry Andric           MemoryBuffer::getOpenFile(*FDOrErr, EntryPath,
54349cc55cSDimitry Andric                                     /*FileSize=*/-1,
55349cc55cSDimitry Andric                                     /*RequiresNullTerminator=*/false);
56349cc55cSDimitry Andric       sys::fs::closeFile(*FDOrErr);
57349cc55cSDimitry Andric       if (MBOrErr) {
58bdd1243dSDimitry Andric         AddBuffer(Task, ModuleName, std::move(*MBOrErr));
59349cc55cSDimitry Andric         return AddStreamFn();
60349cc55cSDimitry Andric       }
61349cc55cSDimitry Andric       EC = MBOrErr.getError();
62349cc55cSDimitry Andric     } else {
63349cc55cSDimitry Andric       EC = errorToErrorCode(FDOrErr.takeError());
64349cc55cSDimitry Andric     }
65349cc55cSDimitry Andric 
66349cc55cSDimitry Andric     // On Windows we can fail to open a cache file with a permission denied
67349cc55cSDimitry Andric     // error. This generally means that another process has requested to delete
68349cc55cSDimitry Andric     // the file while it is still open, but it could also mean that another
69349cc55cSDimitry Andric     // process has opened the file without the sharing permissions we need.
70349cc55cSDimitry Andric     // Since the file is probably being deleted we handle it in the same way as
71349cc55cSDimitry Andric     // if the file did not exist at all.
72349cc55cSDimitry Andric     if (EC != errc::no_such_file_or_directory && EC != errc::permission_denied)
73349cc55cSDimitry Andric       return createStringError(EC, Twine("Failed to open cache file ") +
74349cc55cSDimitry Andric                                        EntryPath + ": " + EC.message() + "\n");
75349cc55cSDimitry Andric 
76349cc55cSDimitry Andric     // This file stream is responsible for commiting the resulting file to the
77349cc55cSDimitry Andric     // cache and calling AddBuffer to add it to the link.
78349cc55cSDimitry Andric     struct CacheStream : CachedFileStream {
79349cc55cSDimitry Andric       AddBufferFn AddBuffer;
80349cc55cSDimitry Andric       sys::fs::TempFile TempFile;
81bdd1243dSDimitry Andric       std::string ModuleName;
82349cc55cSDimitry Andric       unsigned Task;
83349cc55cSDimitry Andric 
84349cc55cSDimitry Andric       CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddBufferFn AddBuffer,
85349cc55cSDimitry Andric                   sys::fs::TempFile TempFile, std::string EntryPath,
86bdd1243dSDimitry Andric                   std::string ModuleName, unsigned Task)
870eae32dcSDimitry Andric           : CachedFileStream(std::move(OS), std::move(EntryPath)),
880eae32dcSDimitry Andric             AddBuffer(std::move(AddBuffer)), TempFile(std::move(TempFile)),
89bdd1243dSDimitry Andric             ModuleName(ModuleName), Task(Task) {}
90349cc55cSDimitry Andric 
91349cc55cSDimitry Andric       ~CacheStream() {
92349cc55cSDimitry Andric         // TODO: Manually commit rather than using non-trivial destructor,
93349cc55cSDimitry Andric         // allowing to replace report_fatal_errors with a return Error.
94349cc55cSDimitry Andric 
95349cc55cSDimitry Andric         // Make sure the stream is closed before committing it.
96349cc55cSDimitry Andric         OS.reset();
97349cc55cSDimitry Andric 
98349cc55cSDimitry Andric         // Open the file first to avoid racing with a cache pruner.
99349cc55cSDimitry Andric         ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
100349cc55cSDimitry Andric             MemoryBuffer::getOpenFile(
1010eae32dcSDimitry Andric                 sys::fs::convertFDToNativeFile(TempFile.FD), ObjectPathName,
102349cc55cSDimitry Andric                 /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
103349cc55cSDimitry Andric         if (!MBOrErr)
104349cc55cSDimitry Andric           report_fatal_error(Twine("Failed to open new cache file ") +
105349cc55cSDimitry Andric                              TempFile.TmpName + ": " +
106349cc55cSDimitry Andric                              MBOrErr.getError().message() + "\n");
107349cc55cSDimitry Andric 
108349cc55cSDimitry Andric         // On POSIX systems, this will atomically replace the destination if
109349cc55cSDimitry Andric         // it already exists. We try to emulate this on Windows, but this may
110349cc55cSDimitry Andric         // fail with a permission denied error (for example, if the destination
111349cc55cSDimitry Andric         // is currently opened by another process that does not give us the
112349cc55cSDimitry Andric         // sharing permissions we need). Since the existing file should be
113349cc55cSDimitry Andric         // semantically equivalent to the one we are trying to write, we give
114349cc55cSDimitry Andric         // AddBuffer a copy of the bytes we wrote in that case. We do this
115349cc55cSDimitry Andric         // instead of just using the existing file, because the pruner might
116349cc55cSDimitry Andric         // delete the file before we get a chance to use it.
1170eae32dcSDimitry Andric         Error E = TempFile.keep(ObjectPathName);
118349cc55cSDimitry Andric         E = handleErrors(std::move(E), [&](const ECError &E) -> Error {
119349cc55cSDimitry Andric           std::error_code EC = E.convertToErrorCode();
120349cc55cSDimitry Andric           if (EC != errc::permission_denied)
121349cc55cSDimitry Andric             return errorCodeToError(EC);
122349cc55cSDimitry Andric 
123349cc55cSDimitry Andric           auto MBCopy = MemoryBuffer::getMemBufferCopy((*MBOrErr)->getBuffer(),
1240eae32dcSDimitry Andric                                                        ObjectPathName);
125349cc55cSDimitry Andric           MBOrErr = std::move(MBCopy);
126349cc55cSDimitry Andric 
127349cc55cSDimitry Andric           // FIXME: should we consume the discard error?
128349cc55cSDimitry Andric           consumeError(TempFile.discard());
129349cc55cSDimitry Andric 
130349cc55cSDimitry Andric           return Error::success();
131349cc55cSDimitry Andric         });
132349cc55cSDimitry Andric 
133349cc55cSDimitry Andric         if (E)
134349cc55cSDimitry Andric           report_fatal_error(Twine("Failed to rename temporary file ") +
1350eae32dcSDimitry Andric                              TempFile.TmpName + " to " + ObjectPathName + ": " +
136349cc55cSDimitry Andric                              toString(std::move(E)) + "\n");
137349cc55cSDimitry Andric 
138bdd1243dSDimitry Andric         AddBuffer(Task, ModuleName, std::move(*MBOrErr));
139349cc55cSDimitry Andric       }
140349cc55cSDimitry Andric     };
141349cc55cSDimitry Andric 
142bdd1243dSDimitry Andric     return [=](size_t Task, const Twine &ModuleName)
143bdd1243dSDimitry Andric                -> Expected<std::unique_ptr<CachedFileStream>> {
14404eeddc0SDimitry Andric       // Create the cache directory if not already done. Doing this lazily
14504eeddc0SDimitry Andric       // ensures the filesystem isn't mutated until the cache is.
14604eeddc0SDimitry Andric       if (std::error_code EC = sys::fs::create_directories(
14704eeddc0SDimitry Andric               CacheDirectoryPath, /*IgnoreExisting=*/true))
1485f757f3fSDimitry Andric         return createStringError(EC, Twine("can't create cache directory ") +
1495f757f3fSDimitry Andric                                          CacheDirectoryPath + ": " +
1505f757f3fSDimitry Andric                                          EC.message());
15104eeddc0SDimitry Andric 
152349cc55cSDimitry Andric       // Write to a temporary to avoid race condition
153349cc55cSDimitry Andric       SmallString<64> TempFilenameModel;
154349cc55cSDimitry Andric       sys::path::append(TempFilenameModel, CacheDirectoryPath,
155349cc55cSDimitry Andric                         TempFilePrefix + "-%%%%%%.tmp.o");
156349cc55cSDimitry Andric       Expected<sys::fs::TempFile> Temp = sys::fs::TempFile::create(
157349cc55cSDimitry Andric           TempFilenameModel, sys::fs::owner_read | sys::fs::owner_write);
158349cc55cSDimitry Andric       if (!Temp)
159349cc55cSDimitry Andric         return createStringError(errc::io_error,
160349cc55cSDimitry Andric                                  toString(Temp.takeError()) + ": " + CacheName +
161349cc55cSDimitry Andric                                      ": Can't get a temporary file");
162349cc55cSDimitry Andric 
163349cc55cSDimitry Andric       // This CacheStream will move the temporary file into the cache when done.
164349cc55cSDimitry Andric       return std::make_unique<CacheStream>(
165349cc55cSDimitry Andric           std::make_unique<raw_fd_ostream>(Temp->FD, /* ShouldClose */ false),
166*7a6dacacSDimitry Andric           AddBuffer, std::move(*Temp), std::string(EntryPath), ModuleName.str(),
167*7a6dacacSDimitry Andric           Task);
168349cc55cSDimitry Andric     };
169349cc55cSDimitry Andric   };
170349cc55cSDimitry Andric }
171