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