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