xref: /llvm-project/lld/Common/Filesystem.cpp (revision 356139bd027d65b6843cbd4eda642104cfe6cf8f)
17fd99fc4SRui Ueyama //===- Filesystem.cpp -----------------------------------------------------===//
27fd99fc4SRui Ueyama //
37fd99fc4SRui Ueyama // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47fd99fc4SRui Ueyama // See https://llvm.org/LICENSE.txt for license information.
57fd99fc4SRui Ueyama // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67fd99fc4SRui Ueyama //
77fd99fc4SRui Ueyama //===----------------------------------------------------------------------===//
87fd99fc4SRui Ueyama //
97fd99fc4SRui Ueyama // This file contains a few utility functions to handle files.
107fd99fc4SRui Ueyama //
117fd99fc4SRui Ueyama //===----------------------------------------------------------------------===//
127fd99fc4SRui Ueyama 
137fd99fc4SRui Ueyama #include "lld/Common/Filesystem.h"
148ff77a8fSMatheus Izvekov #include "lld/Common/ErrorHandler.h"
157fd99fc4SRui Ueyama #include "llvm/Config/llvm-config.h"
167fd99fc4SRui Ueyama #include "llvm/Support/FileOutputBuffer.h"
177fd99fc4SRui Ueyama #include "llvm/Support/FileSystem.h"
18932f0276SReid Kleckner #include "llvm/Support/Parallel.h"
19f42f599dSBen Dunbobbin #include "llvm/Support/Path.h"
20*356139bdSAlexandre Ganea #include "llvm/Support/TimeProfiler.h"
217fd99fc4SRui Ueyama #if LLVM_ON_UNIX
227fd99fc4SRui Ueyama #include <unistd.h>
237fd99fc4SRui Ueyama #endif
247fd99fc4SRui Ueyama #include <thread>
257fd99fc4SRui Ueyama 
267fd99fc4SRui Ueyama using namespace llvm;
277fd99fc4SRui Ueyama using namespace lld;
287fd99fc4SRui Ueyama 
297fd99fc4SRui Ueyama // Removes a given file asynchronously. This is a performance hack,
307fd99fc4SRui Ueyama // so remove this when operating systems are improved.
317fd99fc4SRui Ueyama //
327fd99fc4SRui Ueyama // On Linux (and probably on other Unix-like systems), unlink(2) is a
337fd99fc4SRui Ueyama // noticeably slow system call. As of 2016, unlink takes 250
347fd99fc4SRui Ueyama // milliseconds to remove a 1 GB file on ext4 filesystem on my machine.
357fd99fc4SRui Ueyama //
367fd99fc4SRui Ueyama // To create a new result file, we first remove existing file. So, if
377fd99fc4SRui Ueyama // you repeatedly link a 1 GB program in a regular compile-link-debug
387fd99fc4SRui Ueyama // cycle, every cycle wastes 250 milliseconds only to remove a file.
397fd99fc4SRui Ueyama // Since LLD can link a 1 GB binary in about 5 seconds, that waste
407fd99fc4SRui Ueyama // actually counts.
417fd99fc4SRui Ueyama //
427fd99fc4SRui Ueyama // This function spawns a background thread to remove the file.
437fd99fc4SRui Ueyama // The calling thread returns almost immediately.
unlinkAsync(StringRef path)44136d27abSRui Ueyama void lld::unlinkAsync(StringRef path) {
456bda276fSBen Dunbobbin   if (!sys::fs::exists(path) || !sys::fs::is_regular_file(path))
466bda276fSBen Dunbobbin     return;
476bda276fSBen Dunbobbin 
487fd99fc4SRui Ueyama // Removing a file is async on windows.
497fd99fc4SRui Ueyama #if defined(_WIN32)
50f42f599dSBen Dunbobbin   // On Windows co-operative programs can be expected to open LLD's
51f42f599dSBen Dunbobbin   // output in FILE_SHARE_DELETE mode. This allows us to delete the
52f42f599dSBen Dunbobbin   // file (by moving it to a temporary filename and then deleting
53f42f599dSBen Dunbobbin   // it) so that we can link another output file that overwrites
54f42f599dSBen Dunbobbin   // the existing file, even if the current file is in use.
55f42f599dSBen Dunbobbin   //
56f42f599dSBen Dunbobbin   // This is done on a best effort basis - we do not error if the
57f42f599dSBen Dunbobbin   // operation fails. The consequence is merely that the user
58f42f599dSBen Dunbobbin   // experiences an inconvenient work-flow.
59f42f599dSBen Dunbobbin   //
60f42f599dSBen Dunbobbin   // The code here allows LLD to work on all versions of Windows.
61f42f599dSBen Dunbobbin   // However, at Windows 10 1903 it seems that the behavior of
62f42f599dSBen Dunbobbin   // Windows has changed, so that we could simply delete the output
63f42f599dSBen Dunbobbin   // file. This code should be simplified once support for older
64f42f599dSBen Dunbobbin   // versions of Windows is dropped.
65f42f599dSBen Dunbobbin   //
66f42f599dSBen Dunbobbin   // Warning: It seems that the WINVER and _WIN32_WINNT preprocessor
67f42f599dSBen Dunbobbin   // defines affect the behavior of the Windows versions of the calls
68f42f599dSBen Dunbobbin   // we are using here. If this code stops working this is worth
69f42f599dSBen Dunbobbin   // bearing in mind.
70f42f599dSBen Dunbobbin   SmallString<128> tmpName;
71f42f599dSBen Dunbobbin   if (!sys::fs::createUniqueFile(path + "%%%%%%%%.tmp", tmpName)) {
72f42f599dSBen Dunbobbin     if (!sys::fs::rename(path, tmpName))
73f42f599dSBen Dunbobbin       path = tmpName;
74f42f599dSBen Dunbobbin     else
75f42f599dSBen Dunbobbin       sys::fs::remove(tmpName);
76f42f599dSBen Dunbobbin   }
7776c3f6cdSRui Ueyama   sys::fs::remove(path);
787fd99fc4SRui Ueyama #else
796bda276fSBen Dunbobbin   if (parallel::strategy.ThreadsRequested == 1)
807fd99fc4SRui Ueyama     return;
817fd99fc4SRui Ueyama 
827fd99fc4SRui Ueyama   // We cannot just remove path from a different thread because we are now going
837fd99fc4SRui Ueyama   // to create path as a new file.
847fd99fc4SRui Ueyama   // Instead we open the file and unlink it on this thread. The unlink is fast
857fd99fc4SRui Ueyama   // since the open fd guarantees that it is not removing the last reference.
86136d27abSRui Ueyama   int fd;
87136d27abSRui Ueyama   std::error_code ec = sys::fs::openFileForRead(path, fd);
88136d27abSRui Ueyama   sys::fs::remove(path);
897fd99fc4SRui Ueyama 
90136d27abSRui Ueyama   if (ec)
917fd99fc4SRui Ueyama     return;
927fd99fc4SRui Ueyama 
937fd99fc4SRui Ueyama   // close and therefore remove TempPath in background.
94136d27abSRui Ueyama   std::mutex m;
95136d27abSRui Ueyama   std::condition_variable cv;
96136d27abSRui Ueyama   bool started = false;
97136d27abSRui Ueyama   std::thread([&, fd] {
987fd99fc4SRui Ueyama     {
99136d27abSRui Ueyama       std::lock_guard<std::mutex> l(m);
100136d27abSRui Ueyama       started = true;
101136d27abSRui Ueyama       cv.notify_all();
1027fd99fc4SRui Ueyama     }
103136d27abSRui Ueyama     ::close(fd);
1047fd99fc4SRui Ueyama   }).detach();
1057fd99fc4SRui Ueyama 
1067fd99fc4SRui Ueyama   // GLIBC 2.26 and earlier have race condition that crashes an entire process
1077fd99fc4SRui Ueyama   // if the main thread calls exit(2) while other thread is starting up.
108136d27abSRui Ueyama   std::unique_lock<std::mutex> l(m);
109136d27abSRui Ueyama   cv.wait(l, [&] { return started; });
1107fd99fc4SRui Ueyama #endif
1117fd99fc4SRui Ueyama }
1127fd99fc4SRui Ueyama 
1137fd99fc4SRui Ueyama // Simulate file creation to see if Path is writable.
1147fd99fc4SRui Ueyama //
1157fd99fc4SRui Ueyama // Determining whether a file is writable or not is amazingly hard,
1167fd99fc4SRui Ueyama // and after all the only reliable way of doing that is to actually
1177fd99fc4SRui Ueyama // create a file. But we don't want to do that in this function
1187fd99fc4SRui Ueyama // because LLD shouldn't update any file if it will end in a failure.
1197fd99fc4SRui Ueyama // We also don't want to reimplement heuristics to determine if a
1207fd99fc4SRui Ueyama // file is writable. So we'll let FileOutputBuffer do the work.
1217fd99fc4SRui Ueyama //
1227ae3d335SKazuaki Ishizaki // FileOutputBuffer doesn't touch a destination file until commit()
1237fd99fc4SRui Ueyama // is called. We use that class without calling commit() to predict
1247fd99fc4SRui Ueyama // if the given file is writable.
tryCreateFile(StringRef path)125136d27abSRui Ueyama std::error_code lld::tryCreateFile(StringRef path) {
126*356139bdSAlexandre Ganea   llvm::TimeTraceScope timeScope("Try create output file");
127136d27abSRui Ueyama   if (path.empty())
1287fd99fc4SRui Ueyama     return std::error_code();
129136d27abSRui Ueyama   if (path == "-")
1307fd99fc4SRui Ueyama     return std::error_code();
131136d27abSRui Ueyama   return errorToErrorCode(FileOutputBuffer::create(path, 1).takeError());
1327fd99fc4SRui Ueyama }
1338ff77a8fSMatheus Izvekov 
1348ff77a8fSMatheus Izvekov // Creates an empty file to and returns a raw_fd_ostream to write to it.
openFile(StringRef file)1358ff77a8fSMatheus Izvekov std::unique_ptr<raw_fd_ostream> lld::openFile(StringRef file) {
1368ff77a8fSMatheus Izvekov   std::error_code ec;
1378ff77a8fSMatheus Izvekov   auto ret =
1388ff77a8fSMatheus Izvekov       std::make_unique<raw_fd_ostream>(file, ec, sys::fs::OpenFlags::OF_None);
1398ff77a8fSMatheus Izvekov   if (ec) {
1408ff77a8fSMatheus Izvekov     error("cannot open " + file + ": " + ec.message());
1418ff77a8fSMatheus Izvekov     return nullptr;
1428ff77a8fSMatheus Izvekov   }
1438ff77a8fSMatheus Izvekov   return ret;
1448ff77a8fSMatheus Izvekov }
1458ff77a8fSMatheus Izvekov 
1468ff77a8fSMatheus Izvekov // The merged bitcode after LTO is large. Try opening a file stream that
1478ff77a8fSMatheus Izvekov // supports reading, seeking and writing. Such a file allows BitcodeWriter to
1488ff77a8fSMatheus Izvekov // flush buffered data to reduce memory consumption. If this fails, open a file
1498ff77a8fSMatheus Izvekov // stream that supports only write.
openLTOOutputFile(StringRef file)1508ff77a8fSMatheus Izvekov std::unique_ptr<raw_fd_ostream> lld::openLTOOutputFile(StringRef file) {
1518ff77a8fSMatheus Izvekov   std::error_code ec;
1528ff77a8fSMatheus Izvekov   std::unique_ptr<raw_fd_ostream> fs =
1538ff77a8fSMatheus Izvekov       std::make_unique<raw_fd_stream>(file, ec);
1548ff77a8fSMatheus Izvekov   if (!ec)
1558ff77a8fSMatheus Izvekov     return fs;
1568ff77a8fSMatheus Izvekov   return openFile(file);
1578ff77a8fSMatheus Izvekov }
158