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