xref: /llvm-project/llvm/lib/Support/ToolOutputFile.cpp (revision 4f750f6ebc412869ce6bb28331313a9c9a9d9af7)
1 //===--- ToolOutputFile.cpp - Implement the ToolOutputFile class --------===//
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 implements the ToolOutputFile class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Support/ToolOutputFile.h"
14 #include "llvm/ADT/Triple.h"
15 #include "llvm/Support/FileSystem.h"
16 #include "llvm/Support/Signals.h"
17 using namespace llvm;
18 
19 static bool isStdout(StringRef Filename) { return Filename == "-"; }
20 
21 ToolOutputFile::CleanupInstaller::CleanupInstaller(StringRef Filename)
22     : Filename(std::string(Filename)), Keep(false) {
23   // Arrange for the file to be deleted if the process is killed.
24   if (!isStdout(Filename))
25     sys::RemoveFileOnSignal(Filename);
26 }
27 
28 ToolOutputFile::CleanupInstaller::~CleanupInstaller() {
29   if (isStdout(Filename))
30     return;
31 
32   // Delete the file if the client hasn't told us not to.
33   if (!Keep)
34     sys::fs::remove(Filename);
35 
36   // Ok, the file is successfully written and closed, or deleted. There's no
37   // further need to clean it up on signals.
38   sys::DontRemoveFileOnSignal(Filename);
39 }
40 
41 ToolOutputFile::ToolOutputFile(StringRef Filename, std::error_code &EC,
42                                sys::fs::OpenFlags Flags)
43     : Installer(Filename) {
44   if (isStdout(Filename)) {
45     OS = &outs();
46     EC = std::error_code();
47     return;
48   }
49 
50   // On Windows, we set the OF_None flag even for text files to avoid
51   // CRLF translation.
52   OSHolder.emplace(
53       Filename, EC,
54       llvm::Triple(LLVM_HOST_TRIPLE).isOSWindows() ? sys::fs::OF_None : Flags);
55   OS = OSHolder.getPointer();
56   // If open fails, no cleanup is needed.
57   if (EC)
58     Installer.Keep = true;
59 }
60 
61 ToolOutputFile::ToolOutputFile(StringRef Filename, int FD)
62     : Installer(Filename) {
63   OSHolder.emplace(FD, true);
64   OS = OSHolder.getPointer();
65 }
66