xref: /freebsd-src/contrib/llvm-project/llvm/lib/Support/Caching.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
1*349cc55cSDimitry Andric //===-Caching.cpp - LLVM Local File Cache ---------------------------------===//
2*349cc55cSDimitry Andric //
3*349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*349cc55cSDimitry Andric //
7*349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
8*349cc55cSDimitry Andric //
9*349cc55cSDimitry Andric // This file implements the localCache function, which simplifies creating,
10*349cc55cSDimitry Andric // adding to, and querying a local file system cache. localCache takes care of
11*349cc55cSDimitry Andric // periodically pruning older files from the cache using a CachePruningPolicy.
12*349cc55cSDimitry Andric //
13*349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
14*349cc55cSDimitry Andric 
15*349cc55cSDimitry Andric #include "llvm/Support/Caching.h"
16*349cc55cSDimitry Andric #include "llvm/Support/Errc.h"
17*349cc55cSDimitry Andric #include "llvm/Support/FileSystem.h"
18*349cc55cSDimitry Andric #include "llvm/Support/MemoryBuffer.h"
19*349cc55cSDimitry Andric #include "llvm/Support/Path.h"
20*349cc55cSDimitry Andric 
21*349cc55cSDimitry Andric #if !defined(_MSC_VER) && !defined(__MINGW32__)
22*349cc55cSDimitry Andric #include <unistd.h>
23*349cc55cSDimitry Andric #else
24*349cc55cSDimitry Andric #include <io.h>
25*349cc55cSDimitry Andric #endif
26*349cc55cSDimitry Andric 
27*349cc55cSDimitry Andric using namespace llvm;
28*349cc55cSDimitry Andric 
29*349cc55cSDimitry Andric Expected<FileCache> llvm::localCache(Twine CacheNameRef,
30*349cc55cSDimitry Andric                                      Twine TempFilePrefixRef,
31*349cc55cSDimitry Andric                                      Twine CacheDirectoryPathRef,
32*349cc55cSDimitry Andric                                      AddBufferFn AddBuffer) {
33*349cc55cSDimitry Andric   if (std::error_code EC = sys::fs::create_directories(CacheDirectoryPathRef))
34*349cc55cSDimitry Andric     return errorCodeToError(EC);
35*349cc55cSDimitry Andric 
36*349cc55cSDimitry Andric   // Create local copies which are safely captured-by-copy in lambdas
37*349cc55cSDimitry Andric   SmallString<64> CacheName, TempFilePrefix, CacheDirectoryPath;
38*349cc55cSDimitry Andric   CacheNameRef.toVector(CacheName);
39*349cc55cSDimitry Andric   TempFilePrefixRef.toVector(TempFilePrefix);
40*349cc55cSDimitry Andric   CacheDirectoryPathRef.toVector(CacheDirectoryPath);
41*349cc55cSDimitry Andric 
42*349cc55cSDimitry Andric   return [=](unsigned Task, StringRef Key) -> Expected<AddStreamFn> {
43*349cc55cSDimitry Andric     // This choice of file name allows the cache to be pruned (see pruneCache()
44*349cc55cSDimitry Andric     // in include/llvm/Support/CachePruning.h).
45*349cc55cSDimitry Andric     SmallString<64> EntryPath;
46*349cc55cSDimitry Andric     sys::path::append(EntryPath, CacheDirectoryPath, "llvmcache-" + Key);
47*349cc55cSDimitry Andric     // First, see if we have a cache hit.
48*349cc55cSDimitry Andric     SmallString<64> ResultPath;
49*349cc55cSDimitry Andric     Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
50*349cc55cSDimitry Andric         Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
51*349cc55cSDimitry Andric     std::error_code EC;
52*349cc55cSDimitry Andric     if (FDOrErr) {
53*349cc55cSDimitry Andric       ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
54*349cc55cSDimitry Andric           MemoryBuffer::getOpenFile(*FDOrErr, EntryPath,
55*349cc55cSDimitry Andric                                     /*FileSize=*/-1,
56*349cc55cSDimitry Andric                                     /*RequiresNullTerminator=*/false);
57*349cc55cSDimitry Andric       sys::fs::closeFile(*FDOrErr);
58*349cc55cSDimitry Andric       if (MBOrErr) {
59*349cc55cSDimitry Andric         AddBuffer(Task, std::move(*MBOrErr));
60*349cc55cSDimitry Andric         return AddStreamFn();
61*349cc55cSDimitry Andric       }
62*349cc55cSDimitry Andric       EC = MBOrErr.getError();
63*349cc55cSDimitry Andric     } else {
64*349cc55cSDimitry Andric       EC = errorToErrorCode(FDOrErr.takeError());
65*349cc55cSDimitry Andric     }
66*349cc55cSDimitry Andric 
67*349cc55cSDimitry Andric     // On Windows we can fail to open a cache file with a permission denied
68*349cc55cSDimitry Andric     // error. This generally means that another process has requested to delete
69*349cc55cSDimitry Andric     // the file while it is still open, but it could also mean that another
70*349cc55cSDimitry Andric     // process has opened the file without the sharing permissions we need.
71*349cc55cSDimitry Andric     // Since the file is probably being deleted we handle it in the same way as
72*349cc55cSDimitry Andric     // if the file did not exist at all.
73*349cc55cSDimitry Andric     if (EC != errc::no_such_file_or_directory && EC != errc::permission_denied)
74*349cc55cSDimitry Andric       return createStringError(EC, Twine("Failed to open cache file ") +
75*349cc55cSDimitry Andric                                        EntryPath + ": " + EC.message() + "\n");
76*349cc55cSDimitry Andric 
77*349cc55cSDimitry Andric     // This file stream is responsible for commiting the resulting file to the
78*349cc55cSDimitry Andric     // cache and calling AddBuffer to add it to the link.
79*349cc55cSDimitry Andric     struct CacheStream : CachedFileStream {
80*349cc55cSDimitry Andric       AddBufferFn AddBuffer;
81*349cc55cSDimitry Andric       sys::fs::TempFile TempFile;
82*349cc55cSDimitry Andric       std::string EntryPath;
83*349cc55cSDimitry Andric       unsigned Task;
84*349cc55cSDimitry Andric 
85*349cc55cSDimitry Andric       CacheStream(std::unique_ptr<raw_pwrite_stream> OS, AddBufferFn AddBuffer,
86*349cc55cSDimitry Andric                   sys::fs::TempFile TempFile, std::string EntryPath,
87*349cc55cSDimitry Andric                   unsigned Task)
88*349cc55cSDimitry Andric           : CachedFileStream(std::move(OS)), AddBuffer(std::move(AddBuffer)),
89*349cc55cSDimitry Andric             TempFile(std::move(TempFile)), EntryPath(std::move(EntryPath)),
90*349cc55cSDimitry Andric             Task(Task) {}
91*349cc55cSDimitry Andric 
92*349cc55cSDimitry Andric       ~CacheStream() {
93*349cc55cSDimitry Andric         // TODO: Manually commit rather than using non-trivial destructor,
94*349cc55cSDimitry Andric         // allowing to replace report_fatal_errors with a return Error.
95*349cc55cSDimitry Andric 
96*349cc55cSDimitry Andric         // Make sure the stream is closed before committing it.
97*349cc55cSDimitry Andric         OS.reset();
98*349cc55cSDimitry Andric 
99*349cc55cSDimitry Andric         // Open the file first to avoid racing with a cache pruner.
100*349cc55cSDimitry Andric         ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr =
101*349cc55cSDimitry Andric             MemoryBuffer::getOpenFile(
102*349cc55cSDimitry Andric                 sys::fs::convertFDToNativeFile(TempFile.FD), TempFile.TmpName,
103*349cc55cSDimitry Andric                 /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
104*349cc55cSDimitry Andric         if (!MBOrErr)
105*349cc55cSDimitry Andric           report_fatal_error(Twine("Failed to open new cache file ") +
106*349cc55cSDimitry Andric                              TempFile.TmpName + ": " +
107*349cc55cSDimitry Andric                              MBOrErr.getError().message() + "\n");
108*349cc55cSDimitry Andric 
109*349cc55cSDimitry Andric         // On POSIX systems, this will atomically replace the destination if
110*349cc55cSDimitry Andric         // it already exists. We try to emulate this on Windows, but this may
111*349cc55cSDimitry Andric         // fail with a permission denied error (for example, if the destination
112*349cc55cSDimitry Andric         // is currently opened by another process that does not give us the
113*349cc55cSDimitry Andric         // sharing permissions we need). Since the existing file should be
114*349cc55cSDimitry Andric         // semantically equivalent to the one we are trying to write, we give
115*349cc55cSDimitry Andric         // AddBuffer a copy of the bytes we wrote in that case. We do this
116*349cc55cSDimitry Andric         // instead of just using the existing file, because the pruner might
117*349cc55cSDimitry Andric         // delete the file before we get a chance to use it.
118*349cc55cSDimitry Andric         Error E = TempFile.keep(EntryPath);
119*349cc55cSDimitry Andric         E = handleErrors(std::move(E), [&](const ECError &E) -> Error {
120*349cc55cSDimitry Andric           std::error_code EC = E.convertToErrorCode();
121*349cc55cSDimitry Andric           if (EC != errc::permission_denied)
122*349cc55cSDimitry Andric             return errorCodeToError(EC);
123*349cc55cSDimitry Andric 
124*349cc55cSDimitry Andric           auto MBCopy = MemoryBuffer::getMemBufferCopy((*MBOrErr)->getBuffer(),
125*349cc55cSDimitry Andric                                                        EntryPath);
126*349cc55cSDimitry Andric           MBOrErr = std::move(MBCopy);
127*349cc55cSDimitry Andric 
128*349cc55cSDimitry Andric           // FIXME: should we consume the discard error?
129*349cc55cSDimitry Andric           consumeError(TempFile.discard());
130*349cc55cSDimitry Andric 
131*349cc55cSDimitry Andric           return Error::success();
132*349cc55cSDimitry Andric         });
133*349cc55cSDimitry Andric 
134*349cc55cSDimitry Andric         if (E)
135*349cc55cSDimitry Andric           report_fatal_error(Twine("Failed to rename temporary file ") +
136*349cc55cSDimitry Andric                              TempFile.TmpName + " to " + EntryPath + ": " +
137*349cc55cSDimitry Andric                              toString(std::move(E)) + "\n");
138*349cc55cSDimitry Andric 
139*349cc55cSDimitry Andric         AddBuffer(Task, std::move(*MBOrErr));
140*349cc55cSDimitry Andric       }
141*349cc55cSDimitry Andric     };
142*349cc55cSDimitry Andric 
143*349cc55cSDimitry Andric     return [=](size_t Task) -> Expected<std::unique_ptr<CachedFileStream>> {
144*349cc55cSDimitry Andric       // Write to a temporary to avoid race condition
145*349cc55cSDimitry Andric       SmallString<64> TempFilenameModel;
146*349cc55cSDimitry Andric       sys::path::append(TempFilenameModel, CacheDirectoryPath,
147*349cc55cSDimitry Andric                         TempFilePrefix + "-%%%%%%.tmp.o");
148*349cc55cSDimitry Andric       Expected<sys::fs::TempFile> Temp = sys::fs::TempFile::create(
149*349cc55cSDimitry Andric           TempFilenameModel, sys::fs::owner_read | sys::fs::owner_write);
150*349cc55cSDimitry Andric       if (!Temp)
151*349cc55cSDimitry Andric         return createStringError(errc::io_error,
152*349cc55cSDimitry Andric                                  toString(Temp.takeError()) + ": " + CacheName +
153*349cc55cSDimitry Andric                                      ": Can't get a temporary file");
154*349cc55cSDimitry Andric 
155*349cc55cSDimitry Andric       // This CacheStream will move the temporary file into the cache when done.
156*349cc55cSDimitry Andric       return std::make_unique<CacheStream>(
157*349cc55cSDimitry Andric           std::make_unique<raw_fd_ostream>(Temp->FD, /* ShouldClose */ false),
158*349cc55cSDimitry Andric           AddBuffer, std::move(*Temp), std::string(EntryPath.str()), Task);
159*349cc55cSDimitry Andric     };
160*349cc55cSDimitry Andric   };
161*349cc55cSDimitry Andric }
162