1 //===- Filesystem.cpp -----------------------------------------------------===//
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 contains a few utility functions to handle files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "lld/Common/Filesystem.h"
14 #include "llvm/Config/llvm-config.h"
15 #include "llvm/Support/FileOutputBuffer.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/Parallel.h"
18 #include "llvm/Support/Path.h"
19 #if LLVM_ON_UNIX
20 #include <unistd.h>
21 #endif
22 #include <thread>
23 
24 using namespace llvm;
25 using namespace lld;
26 
27 // Removes a given file asynchronously. This is a performance hack,
28 // so remove this when operating systems are improved.
29 //
30 // On Linux (and probably on other Unix-like systems), unlink(2) is a
31 // noticeably slow system call. As of 2016, unlink takes 250
32 // milliseconds to remove a 1 GB file on ext4 filesystem on my machine.
33 //
34 // To create a new result file, we first remove existing file. So, if
35 // you repeatedly link a 1 GB program in a regular compile-link-debug
36 // cycle, every cycle wastes 250 milliseconds only to remove a file.
37 // Since LLD can link a 1 GB binary in about 5 seconds, that waste
38 // actually counts.
39 //
40 // This function spawns a background thread to remove the file.
41 // The calling thread returns almost immediately.
42 void lld::unlinkAsync(StringRef path) {
43 // Removing a file is async on windows.
44 #if defined(_WIN32)
45   // On Windows co-operative programs can be expected to open LLD's
46   // output in FILE_SHARE_DELETE mode. This allows us to delete the
47   // file (by moving it to a temporary filename and then deleting
48   // it) so that we can link another output file that overwrites
49   // the existing file, even if the current file is in use.
50   //
51   // This is done on a best effort basis - we do not error if the
52   // operation fails. The consequence is merely that the user
53   // experiences an inconvenient work-flow.
54   //
55   // The code here allows LLD to work on all versions of Windows.
56   // However, at Windows 10 1903 it seems that the behavior of
57   // Windows has changed, so that we could simply delete the output
58   // file. This code should be simplified once support for older
59   // versions of Windows is dropped.
60   //
61   // Warning: It seems that the WINVER and _WIN32_WINNT preprocessor
62   // defines affect the behavior of the Windows versions of the calls
63   // we are using here. If this code stops working this is worth
64   // bearing in mind.
65   SmallString<128> tmpName;
66   if (!sys::fs::createUniqueFile(path + "%%%%%%%%.tmp", tmpName)) {
67     if (!sys::fs::rename(path, tmpName))
68       path = tmpName;
69     else
70       sys::fs::remove(tmpName);
71   }
72   sys::fs::remove(path);
73 #else
74   if (parallel::strategy.ThreadsRequested == 1 || !sys::fs::exists(path) ||
75       !sys::fs::is_regular_file(path))
76     return;
77 
78   // We cannot just remove path from a different thread because we are now going
79   // to create path as a new file.
80   // Instead we open the file and unlink it on this thread. The unlink is fast
81   // since the open fd guarantees that it is not removing the last reference.
82   int fd;
83   std::error_code ec = sys::fs::openFileForRead(path, fd);
84   sys::fs::remove(path);
85 
86   if (ec)
87     return;
88 
89   // close and therefore remove TempPath in background.
90   std::mutex m;
91   std::condition_variable cv;
92   bool started = false;
93   std::thread([&, fd] {
94     {
95       std::lock_guard<std::mutex> l(m);
96       started = true;
97       cv.notify_all();
98     }
99     ::close(fd);
100   }).detach();
101 
102   // GLIBC 2.26 and earlier have race condition that crashes an entire process
103   // if the main thread calls exit(2) while other thread is starting up.
104   std::unique_lock<std::mutex> l(m);
105   cv.wait(l, [&] { return started; });
106 #endif
107 }
108 
109 // Simulate file creation to see if Path is writable.
110 //
111 // Determining whether a file is writable or not is amazingly hard,
112 // and after all the only reliable way of doing that is to actually
113 // create a file. But we don't want to do that in this function
114 // because LLD shouldn't update any file if it will end in a failure.
115 // We also don't want to reimplement heuristics to determine if a
116 // file is writable. So we'll let FileOutputBuffer do the work.
117 //
118 // FileOutputBuffer doesn't touch a destination file until commit()
119 // is called. We use that class without calling commit() to predict
120 // if the given file is writable.
121 std::error_code lld::tryCreateFile(StringRef path) {
122   if (path.empty())
123     return std::error_code();
124   if (path == "-")
125     return std::error_code();
126   return errorToErrorCode(FileOutputBuffer::create(path, 1).takeError());
127 }
128