ToolOutputFile.h 2.4 KB

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