InitLLVM.cpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //===-- InitLLVM.cpp -----------------------------------------------------===//
  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. #include "llvm/Support/InitLLVM.h"
  9. #include "llvm/ADT/StringRef.h"
  10. #include "llvm/Support/ErrorHandling.h"
  11. #include "llvm/Support/ManagedStatic.h"
  12. #include "llvm/Support/PrettyStackTrace.h"
  13. #include "llvm/Support/Signals.h"
  14. #include "llvm/Support/SwapByteOrder.h"
  15. #ifdef _WIN32
  16. #include "llvm/Support/Error.h"
  17. #include "llvm/Support/Windows/WindowsSupport.h"
  18. #endif
  19. using namespace llvm;
  20. using namespace llvm::sys;
  21. InitLLVM::InitLLVM(int &Argc, const char **&Argv,
  22. bool InstallPipeSignalExitHandler) {
  23. if (InstallPipeSignalExitHandler)
  24. // The pipe signal handler must be installed before any other handlers are
  25. // registered. This is because the Unix \ref RegisterHandlers function does
  26. // not perform a sigaction() for SIGPIPE unless a one-shot handler is
  27. // present, to allow long-lived processes (like lldb) to fully opt-out of
  28. // llvm's SIGPIPE handling and ignore the signal safely.
  29. sys::SetOneShotPipeSignalFunction(sys::DefaultOneShotPipeSignalHandler);
  30. // Initialize the stack printer after installing the one-shot pipe signal
  31. // handler, so we can perform a sigaction() for SIGPIPE on Unix if requested.
  32. StackPrinter.emplace(Argc, Argv);
  33. sys::PrintStackTraceOnErrorSignal(Argv[0]);
  34. install_out_of_memory_new_handler();
  35. #ifdef _WIN32
  36. // We use UTF-8 as the internal character encoding. On Windows,
  37. // arguments passed to main() may not be encoded in UTF-8. In order
  38. // to reliably detect encoding of command line arguments, we use an
  39. // Windows API to obtain arguments, convert them to UTF-8, and then
  40. // write them back to the Argv vector.
  41. //
  42. // There's probably other way to do the same thing (e.g. using
  43. // wmain() instead of main()), but this way seems less intrusive
  44. // than that.
  45. std::string Banner = std::string(Argv[0]) + ": ";
  46. ExitOnError ExitOnErr(Banner);
  47. ExitOnErr(errorCodeToError(windows::GetCommandLineArguments(Args, Alloc)));
  48. // GetCommandLineArguments doesn't terminate the vector with a
  49. // nullptr. Do it to make it compatible with the real argv.
  50. Args.push_back(nullptr);
  51. Argc = Args.size() - 1;
  52. Argv = Args.data();
  53. #endif
  54. }
  55. InitLLVM::~InitLLVM() { llvm_shutdown(); }