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 OSHolder.emplace(Filename, EC, Flags); 50 OS = OSHolder.getPointer(); 51 // If open fails, no cleanup is needed. 52 if (EC) 53 Installer.Keep = true; 54 } 55 56 ToolOutputFile::ToolOutputFile(StringRef Filename, int FD) 57 : Installer(Filename) { 58 OSHolder.emplace(FD, true); 59 OS = OSHolder.getPointer(); 60 } 61