1 //===- Filesystem.cpp -----------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a few utility functions to handle files.
12 //===----------------------------------------------------------------------===//
14 #include "Filesystem.h"
16 #include "llvm/Support/FileSystem.h"
17 #include "llvm/Support/FileOutputBuffer.h"
23 using namespace lld::elf;
25 // Removes a given file asynchronously. This is a performance hack,
26 // so remove this when operating systems are improved.
28 // On Linux (and probably on other Unix-like systems), unlink(2) is a
29 // noticeably slow system call. As of 2016, unlink takes 250
30 // milliseconds to remove a 1 GB file on ext4 filesystem on my machine.
32 // To create a new result file, we first remove existing file. So, if
33 // you repeatedly link a 1 GB program in a regular compile-link-debug
34 // cycle, every cycle wastes 250 milliseconds only to remove a file.
35 // Since LLD can link a 1 GB binary in about 5 seconds, that waste
38 // This function spawns a background thread to call unlink.
39 // The calling thread returns almost immediately.
40 void elf::unlinkAsync(StringRef Path) {
41 if (!Config->Threads || !sys::fs::exists(Config->OutputFile))
44 // First, rename Path to avoid race condition. We cannot remove
45 // Path from a different thread because we are now going to create
46 // Path as a new file. If we do that in a different thread, the new
47 // thread can remove the new file.
48 SmallString<128> TempPath;
49 if (sys::fs::createUniqueFile(Path + "tmp%%%%%%%%", TempPath))
51 if (sys::fs::rename(Path, TempPath)) {
52 sys::fs::remove(TempPath);
56 // Remove TempPath in background.
57 std::thread([=] { ::remove(TempPath.str().str().c_str()); }).detach();
60 // Simulate file creation to see if Path is writable.
62 // Determining whether a file is writable or not is amazingly hard,
63 // and after all the only reliable way of doing that is to actually
64 // create a file. But we don't want to do that in this function
65 // because LLD shouldn't update any file if it will end in a failure.
66 // We also don't want to reimplement heuristics to determine if a
67 // file is writable. So we'll let FileOutputBuffer do the work.
69 // FileOutputBuffer doesn't touch a desitnation file until commit()
70 // is called. We use that class without calling commit() to predict
71 // if the given file is writable.
72 std::error_code elf::tryCreateFile(StringRef Path) {
74 return std::error_code();
75 return FileOutputBuffer::create(Path, 1).getError();