xref: /freebsd-src/contrib/llvm-project/llvm/lib/Support/Caching.cpp (revision 04eeddc0aa8e0a417a16eaf9d7d095207f4a8623)
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 
29349cc55cSDimitry Andric Expected<FileCache> llvm::localCache(Twine CacheNameRef,
30349cc55cSDimitry Andric                                      Twine TempFilePrefixRef,
31349cc55cSDimitry Andric                                      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 
40349cc55cSDimitry Andric   return [=](unsigned Task, StringRef Key) -> Expected<AddStreamFn> {
41349cc55cSDimitry Andric     // This choice of file name allows the cache to be pruned (see pruneCache()
42349cc55cSDimitry Andric     // in include/llvm/Support/CachePruning.h).
43349cc55cSDimitry Andric     SmallString<64> EntryPath;
44349cc55cSDimitry Andric     sys::path::append(EntryPath, CacheDirectoryPath, "llvmcache-" + Key);
45349cc55cSDimitry Andric     // First, see if we have a cache hit.
46349cc55cSDimitry Andric     SmallString<64> ResultPath;
47349cc55cSDimitry Andric     Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
48349cc55cSDimitry Andric         Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
49349cc55cSDimitry Andric     std::error_code EC;
50349cc55cSDimitry Andric     if (FDOrErr) {
51349cc55cSDimitry Andric       ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
52349cc55cSDimitry Andric           MemoryBuffer::getOpenFile(*FDOrErr, EntryPath,
53349cc55cSDimitry Andric                                     /*FileSize=*/-1,
54349cc55cSDimitry Andric                                     /*RequiresNullTerminator=*/false);
55349cc55cSDimitry Andric       sys::fs::closeFile(*FDOrErr);
56349cc55cSDimitry Andric       if (MBOrErr) {
57349cc55cSDimitry Andric         AddBuffer(Task, std::move(*MBOrErr));
58349cc55cSDimitry Andric         return AddStreamFn();
59349cc55cSDimitry Andric       }
60349cc55cSDimitry Andric       EC = MBOrErr.getError();
61349cc55cSDimitry Andric     } else {
62349cc55cSDimitry Andric       EC = errorToErrorCode(FDOrErr.takeError());
63349cc55cSDimitry Andric     }
64349cc55cSDimitry Andric 
65349cc55cSDimitry Andric     // On Windows we can fail to open a cache file with a permission denied
66349cc55cSDimitry Andric     // error. This generally means that another process has requested to delete
67349cc55cSDimitry Andric     // the file while it is still open, but it could also mean that another
68349cc55cSDimitry Andric     // process has opened the file without the sharing permissions we need.
69349cc55cSDimitry Andric     // Since the file is probably being deleted we handle it in the same way as
70349cc55cSDimitry Andric     // if the file did not exist at all.
71349cc55cSDimitry Andric     if (EC != errc::no_such_file_or_directory && EC != errc::permission_denied)
72349cc55cSDimitry Andric       return createStringError(EC, Twine("Failed to open cache file ") +
73349cc55cSDimitry Andric                                        EntryPath + ": " + EC.message() + "\n");
74349cc55cSDimitry Andric 
75349cc55cSDimitry Andric     // This file stream is responsible for commiting the resulting file to the
76349cc55cSDimitry Andric     // cache and calling AddBuffer to add it to the link.
77349cc55cSDimitry Andric     struct CacheStream : CachedFileStream {
78349cc55cSDimitry Andric       AddBufferFn AddBuffer;
79349cc55cSDimitry Andric       sys::fs::TempFile TempFile;
80349cc55cSDimitry Andric       unsigned Task;
81349cc55cSDimitry Andric 
82349cc55cSDimitry Andric       CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddBufferFn AddBuffer,
83349cc55cSDimitry Andric                   sys::fs::TempFile TempFile, std::string EntryPath,
84349cc55cSDimitry Andric                   unsigned Task)
850eae32dcSDimitry Andric           : CachedFileStream(std::move(OS), std::move(EntryPath)),
860eae32dcSDimitry Andric             AddBuffer(std::move(AddBuffer)), TempFile(std::move(TempFile)),
87349cc55cSDimitry Andric             Task(Task) {}
88349cc55cSDimitry Andric 
89349cc55cSDimitry Andric       ~CacheStream() {
90349cc55cSDimitry Andric         // TODO: Manually commit rather than using non-trivial destructor,
91349cc55cSDimitry Andric         // allowing to replace report_fatal_errors with a return Error.
92349cc55cSDimitry Andric 
93349cc55cSDimitry Andric         // Make sure the stream is closed before committing it.
94349cc55cSDimitry Andric         OS.reset();
95349cc55cSDimitry Andric 
96349cc55cSDimitry Andric         // Open the file first to avoid racing with a cache pruner.
97349cc55cSDimitry Andric         ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
98349cc55cSDimitry Andric             MemoryBuffer::getOpenFile(
990eae32dcSDimitry Andric                 sys::fs::convertFDToNativeFile(TempFile.FD), ObjectPathName,
100349cc55cSDimitry Andric                 /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
101349cc55cSDimitry Andric         if (!MBOrErr)
102349cc55cSDimitry Andric           report_fatal_error(Twine("Failed to open new cache file ") +
103349cc55cSDimitry Andric                              TempFile.TmpName + ": " +
104349cc55cSDimitry Andric                              MBOrErr.getError().message() + "\n");
105349cc55cSDimitry Andric 
106349cc55cSDimitry Andric         // On POSIX systems, this will atomically replace the destination if
107349cc55cSDimitry Andric         // it already exists. We try to emulate this on Windows, but this may
108349cc55cSDimitry Andric         // fail with a permission denied error (for example, if the destination
109349cc55cSDimitry Andric         // is currently opened by another process that does not give us the
110349cc55cSDimitry Andric         // sharing permissions we need). Since the existing file should be
111349cc55cSDimitry Andric         // semantically equivalent to the one we are trying to write, we give
112349cc55cSDimitry Andric         // AddBuffer a copy of the bytes we wrote in that case. We do this
113349cc55cSDimitry Andric         // instead of just using the existing file, because the pruner might
114349cc55cSDimitry Andric         // delete the file before we get a chance to use it.
1150eae32dcSDimitry Andric         Error E = TempFile.keep(ObjectPathName);
116349cc55cSDimitry Andric         E = handleErrors(std::move(E), [&](const ECError &E) -> Error {
117349cc55cSDimitry Andric           std::error_code EC = E.convertToErrorCode();
118349cc55cSDimitry Andric           if (EC != errc::permission_denied)
119349cc55cSDimitry Andric             return errorCodeToError(EC);
120349cc55cSDimitry Andric 
121349cc55cSDimitry Andric           auto MBCopy = MemoryBuffer::getMemBufferCopy((*MBOrErr)->getBuffer(),
1220eae32dcSDimitry Andric                                                        ObjectPathName);
123349cc55cSDimitry Andric           MBOrErr = std::move(MBCopy);
124349cc55cSDimitry Andric 
125349cc55cSDimitry Andric           // FIXME: should we consume the discard error?
126349cc55cSDimitry Andric           consumeError(TempFile.discard());
127349cc55cSDimitry Andric 
128349cc55cSDimitry Andric           return Error::success();
129349cc55cSDimitry Andric         });
130349cc55cSDimitry Andric 
131349cc55cSDimitry Andric         if (E)
132349cc55cSDimitry Andric           report_fatal_error(Twine("Failed to rename temporary file ") +
1330eae32dcSDimitry Andric                              TempFile.TmpName + " to " + ObjectPathName + ": " +
134349cc55cSDimitry Andric                              toString(std::move(E)) + "\n");
135349cc55cSDimitry Andric 
136349cc55cSDimitry Andric         AddBuffer(Task, std::move(*MBOrErr));
137349cc55cSDimitry Andric       }
138349cc55cSDimitry Andric     };
139349cc55cSDimitry Andric 
140349cc55cSDimitry Andric     return [=](size_t Task) -> Expected<std::unique_ptr<CachedFileStream>> {
141*04eeddc0SDimitry Andric       // Create the cache directory if not already done. Doing this lazily
142*04eeddc0SDimitry Andric       // ensures the filesystem isn't mutated until the cache is.
143*04eeddc0SDimitry Andric       if (std::error_code EC = sys::fs::create_directories(
144*04eeddc0SDimitry Andric               CacheDirectoryPath, /*IgnoreExisting=*/true))
145*04eeddc0SDimitry Andric         return errorCodeToError(EC);
146*04eeddc0SDimitry Andric 
147349cc55cSDimitry Andric       // Write to a temporary to avoid race condition
148349cc55cSDimitry Andric       SmallString<64> TempFilenameModel;
149349cc55cSDimitry Andric       sys::path::append(TempFilenameModel, CacheDirectoryPath,
150349cc55cSDimitry Andric                         TempFilePrefix + "-%%%%%%.tmp.o");
151349cc55cSDimitry Andric       Expected<sys::fs::TempFile> Temp = sys::fs::TempFile::create(
152349cc55cSDimitry Andric           TempFilenameModel, sys::fs::owner_read | sys::fs::owner_write);
153349cc55cSDimitry Andric       if (!Temp)
154349cc55cSDimitry Andric         return createStringError(errc::io_error,
155349cc55cSDimitry Andric                                  toString(Temp.takeError()) + ": " + CacheName +
156349cc55cSDimitry Andric                                      ": Can't get a temporary file");
157349cc55cSDimitry Andric 
158349cc55cSDimitry Andric       // This CacheStream will move the temporary file into the cache when done.
159349cc55cSDimitry Andric       return std::make_unique<CacheStream>(
160349cc55cSDimitry Andric           std::make_unique<raw_fd_ostream>(Temp->FD, /* ShouldClose */ false),
161349cc55cSDimitry Andric           AddBuffer, std::move(*Temp), std::string(EntryPath.str()), Task);
162349cc55cSDimitry Andric     };
163349cc55cSDimitry Andric   };
164349cc55cSDimitry Andric }
165