xref: /llvm-project/llvm/lib/Support/InitLLVM.cpp (revision 2946cd701067404b99c39fb29dc9c74bd7193eb3)
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 
9 #include "llvm/Support/InitLLVM.h"
10 #include "llvm/Support/Error.h"
11 #include "llvm/Support/ManagedStatic.h"
12 #include "llvm/Support/PrettyStackTrace.h"
13 #include "llvm/Support/Process.h"
14 #include "llvm/Support/Signals.h"
15 #include <string>
16 
17 #ifdef _WIN32
18 #include "Windows/WindowsSupport.h"
19 #endif
20 
21 using namespace llvm;
22 using namespace llvm::sys;
23 
24 InitLLVM::InitLLVM(int &Argc, const char **&Argv) : StackPrinter(Argc, Argv) {
25   sys::PrintStackTraceOnErrorSignal(Argv[0]);
26 
27 #ifdef _WIN32
28   // We use UTF-8 as the internal character encoding. On Windows,
29   // arguments passed to main() may not be encoded in UTF-8. In order
30   // to reliably detect encoding of command line arguments, we use an
31   // Windows API to obtain arguments, convert them to UTF-8, and then
32   // write them back to the Argv vector.
33   //
34   // There's probably other way to do the same thing (e.g. using
35   // wmain() instead of main()), but this way seems less intrusive
36   // than that.
37   std::string Banner = std::string(Argv[0]) + ": ";
38   ExitOnError ExitOnErr(Banner);
39 
40   ExitOnErr(errorCodeToError(windows::GetCommandLineArguments(Args, Alloc)));
41 
42   // GetCommandLineArguments doesn't terminate the vector with a
43   // nullptr.  Do it to make it compatible with the real argv.
44   Args.push_back(nullptr);
45 
46   Argc = Args.size() - 1;
47   Argv = Args.data();
48 #endif
49 }
50 
51 InitLLVM::~InitLLVM() { llvm_shutdown(); }
52