1 //===- ToolOutputFile.h - Output files for compiler-like tools --*- C++ -*-===// 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 defines the ToolOutputFile class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_SUPPORT_TOOLOUTPUTFILE_H 14 #define LLVM_SUPPORT_TOOLOUTPUTFILE_H 15 16 #include "llvm/Support/Compiler.h" 17 #include "llvm/Support/raw_ostream.h" 18 #include <optional> 19 20 namespace llvm { 21 22 class CleanupInstaller { 23 public: 24 /// The name of the file. 25 std::string Filename; 26 27 /// The flag which indicates whether we should not delete the file. 28 bool Keep; 29 getFilename()30 StringRef getFilename() { return Filename; } 31 LLVM_ABI explicit CleanupInstaller(StringRef Filename); 32 LLVM_ABI ~CleanupInstaller(); 33 }; 34 35 /// This class contains a raw_fd_ostream and adds a few extra features commonly 36 /// needed for compiler-like tool output files: 37 /// - The file is automatically deleted if the process is killed. 38 /// - The file is automatically deleted when the ToolOutputFile 39 /// object is destroyed unless the client calls keep(). 40 class ToolOutputFile { 41 /// This class is declared before the raw_fd_ostream so that it is constructed 42 /// before the raw_fd_ostream is constructed and destructed after the 43 /// raw_fd_ostream is destructed. It installs cleanups in its constructor and 44 /// uninstalls them in its destructor. 45 CleanupInstaller Installer; 46 47 /// Storage for the stream, if we're owning our own stream. This is 48 /// intentionally declared after Installer. 49 std::optional<raw_fd_ostream> OSHolder; 50 51 /// The actual stream to use. 52 raw_fd_ostream *OS; 53 54 public: 55 /// This constructor's arguments are passed to raw_fd_ostream's 56 /// constructor. 57 LLVM_ABI ToolOutputFile(StringRef Filename, std::error_code &EC, 58 sys::fs::OpenFlags Flags); 59 60 LLVM_ABI ToolOutputFile(StringRef Filename, int FD); 61 62 /// Return the contained raw_fd_ostream. os()63 raw_fd_ostream &os() { return *OS; } 64 65 /// Return the filename initialized with. getFilename()66 StringRef getFilename() { return Installer.getFilename(); } 67 68 /// Indicate that the tool's job wrt this output file has been successful and 69 /// the file should not be deleted. keep()70 void keep() { Installer.Keep = true; } 71 outputFilename()72 const std::string &outputFilename() { return Installer.Filename; } 73 }; 74 75 } // end llvm namespace 76 77 #endif 78