ToolOutputFile.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. #include "llvm/Support/ToolOutputFile.h"
  13. #include "llvm/Support/FileSystem.h"
  14. #include "llvm/Support/Signals.h"
  15. using namespace llvm;
  16. static bool isStdout(StringRef Filename) { return Filename == "-"; }
  17. ToolOutputFile::CleanupInstaller::CleanupInstaller(StringRef Filename)
  18. : Filename(std::string(Filename)), Keep(false) {
  19. // Arrange for the file to be deleted if the process is killed.
  20. if (!isStdout(Filename))
  21. sys::RemoveFileOnSignal(Filename);
  22. }
  23. ToolOutputFile::CleanupInstaller::~CleanupInstaller() {
  24. if (isStdout(Filename))
  25. return;
  26. // Delete the file if the client hasn't told us not to.
  27. if (!Keep)
  28. sys::fs::remove(Filename);
  29. // Ok, the file is successfully written and closed, or deleted. There's no
  30. // further need to clean it up on signals.
  31. sys::DontRemoveFileOnSignal(Filename);
  32. }
  33. ToolOutputFile::ToolOutputFile(StringRef Filename, std::error_code &EC,
  34. sys::fs::OpenFlags Flags)
  35. : Installer(Filename) {
  36. if (isStdout(Filename)) {
  37. OS = &outs();
  38. EC = std::error_code();
  39. return;
  40. }
  41. OSHolder.emplace(Filename, EC, Flags);
  42. OS = OSHolder.getPointer();
  43. // If open fails, no cleanup is needed.
  44. if (EC)
  45. Installer.Keep = true;
  46. }
  47. ToolOutputFile::ToolOutputFile(StringRef Filename, int FD)
  48. : Installer(Filename) {
  49. OSHolder.emplace(FD, true);
  50. OS = OSHolder.getPointer();
  51. }