1 //===- Win32/Process.cpp - Win32 Process Implementation ------- -*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file provides the Win32 specific implementation of the Process class.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Support/Allocator.h"
14 #include "llvm/Support/CommandLine.h"
15 #include "llvm/Support/ConvertUTF.h"
16 #include "llvm/Support/ErrorHandling.h"
17 #include "llvm/Support/StringSaver.h"
18 #include "llvm/Support/WindowsError.h"
21 // The Windows.h header must be after LLVM and standard headers.
22 #include "llvm/Support/Windows/WindowsSupport.h"
29 #if !defined(__MINGW32__)
30 #pragma comment(lib, "psapi.lib")
31 #pragma comment(lib, "shell32.lib")
34 //===----------------------------------------------------------------------===//
35 //=== WARNING: Implementation here must contain only Win32 specific code
36 //=== and must not be UNIX code
37 //===----------------------------------------------------------------------===//
40 // This ban should be lifted when MinGW 1.0+ has defined this value.
46 Process::Pid Process::getProcessId() {
47 static_assert(sizeof(Pid) >= sizeof(DWORD),
48 "Process::Pid should be big enough to store DWORD");
49 return Pid(::GetCurrentProcessId());
52 // This function retrieves the page size using GetNativeSystemInfo() and is
53 // present solely so it can be called once to initialize the self_process member
55 static unsigned computePageSize() {
56 // GetNativeSystemInfo() provides the physical page size which may differ
57 // from GetSystemInfo() in 32-bit applications running under WOW64.
59 GetNativeSystemInfo(&info);
60 // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
61 // but dwAllocationGranularity.
62 return static_cast<unsigned>(info.dwPageSize);
65 Expected<unsigned> Process::getPageSize() {
66 static unsigned Ret = computePageSize();
71 Process::GetMallocUsage()
78 while (_heapwalk(&hinfo) == _HEAPOK)
84 void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
85 std::chrono::nanoseconds &sys_time) {
86 elapsed = std::chrono::system_clock::now();;
88 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
89 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
93 user_time = toDuration(UserTime);
94 sys_time = toDuration(KernelTime);
97 // Some LLVM programs such as bugpoint produce core files as a normal part of
98 // their operation. To prevent the disk from filling up, this configuration
99 // item does what's necessary to prevent their generation.
100 void Process::PreventCoreFiles() {
101 // Windows does have the concept of core files, called minidumps. However,
102 // disabling minidumps for a particular application extends past the lifetime
103 // of that application, which is the incorrect behavior for this API.
104 // Additionally, the APIs require elevated privileges to disable and re-
105 // enable minidumps, which makes this untenable. For more information, see
106 // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
109 // Windows also has modal pop-up message boxes. As this method is used by
110 // bugpoint, preventing these pop-ups is additionally important.
111 SetErrorMode(SEM_FAILCRITICALERRORS |
112 SEM_NOGPFAULTERRORBOX |
113 SEM_NOOPENFILEERRORBOX);
115 coreFilesPrevented = true;
118 /// Returns the environment variable \arg Name's value as a string encoded in
119 /// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
120 Optional<std::string> Process::GetEnv(StringRef Name) {
121 // Convert the argument to UTF-16 to pass it to _wgetenv().
122 SmallVector<wchar_t, 128> NameUTF16;
123 if (windows::UTF8ToUTF16(Name, NameUTF16))
126 // Environment variable can be encoded in non-UTF8 encoding, and there's no
127 // way to know what the encoding is. The only reliable way to look up
128 // multibyte environment variable is to use GetEnvironmentVariableW().
129 SmallVector<wchar_t, MAX_PATH> Buf;
130 size_t Size = MAX_PATH;
133 SetLastError(NO_ERROR);
135 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
136 if (Size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
139 // Try again with larger buffer.
140 } while (Size > Buf.capacity());
143 // Convert the result from UTF-16 to UTF-8.
144 SmallVector<char, MAX_PATH> Res;
145 if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
147 return std::string(Res.data());
150 /// Perform wildcard expansion of Arg, or just push it into Args if it doesn't
151 /// have wildcards or doesn't match any files.
152 static std::error_code WildcardExpand(StringRef Arg,
153 SmallVectorImpl<const char *> &Args,
154 StringSaver &Saver) {
157 // Don't expand Arg if it does not contain any wildcard characters. This is
158 // the common case. Also don't wildcard expand /?. Always treat it as an
160 if (Arg.find_first_of("*?") == StringRef::npos || Arg == "/?" ||
162 Args.push_back(Arg.data());
166 // Convert back to UTF-16 so we can call FindFirstFileW.
167 SmallVector<wchar_t, MAX_PATH> ArgW;
168 EC = windows::UTF8ToUTF16(Arg, ArgW);
172 // Search for matching files.
173 // FIXME: This assumes the wildcard is only in the file name and not in the
174 // directory portion of the file path. For example, it doesn't handle
175 // "*\foo.c" nor "s?c\bar.cpp".
176 WIN32_FIND_DATAW FileData;
177 HANDLE FindHandle = FindFirstFileW(ArgW.data(), &FileData);
178 if (FindHandle == INVALID_HANDLE_VALUE) {
179 Args.push_back(Arg.data());
183 // Extract any directory part of the argument.
184 SmallString<MAX_PATH> Dir = Arg;
185 sys::path::remove_filename(Dir);
186 const int DirSize = Dir.size();
189 SmallString<MAX_PATH> FileName;
190 EC = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
195 // Append FileName to Dir, and remove it afterwards.
196 llvm::sys::path::append(Dir, FileName);
197 Args.push_back(Saver.save(Dir.str()).data());
199 } while (FindNextFileW(FindHandle, &FileData));
201 FindClose(FindHandle);
205 static std::error_code GetExecutableName(SmallVectorImpl<char> &Filename) {
206 // The first argument may contain just the name of the executable (e.g.,
207 // "clang") rather than the full path, so swap it with the full path.
208 wchar_t ModuleName[MAX_PATH];
209 size_t Length = ::GetModuleFileNameW(NULL, ModuleName, MAX_PATH);
210 if (Length == 0 || Length == MAX_PATH) {
211 return mapWindowsError(GetLastError());
214 // If the first argument is a shortened (8.3) name (which is possible even
215 // if we got the module name), the driver will have trouble distinguishing it
216 // (e.g., clang.exe v. clang++.exe), so expand it now.
217 Length = GetLongPathNameW(ModuleName, ModuleName, MAX_PATH);
219 return mapWindowsError(GetLastError());
220 if (Length > MAX_PATH) {
221 // We're not going to try to deal with paths longer than MAX_PATH, so we'll
222 // treat this as an error. GetLastError() returns ERROR_SUCCESS, which
223 // isn't useful, so we'll hardcode an appropriate error value.
224 return mapWindowsError(ERROR_INSUFFICIENT_BUFFER);
227 std::error_code EC = windows::UTF16ToUTF8(ModuleName, Length, Filename);
231 // Make a copy of the filename since assign makes the StringRef invalid.
232 std::string Base = sys::path::filename(Filename.data()).str();
233 Filename.assign(Base.begin(), Base.end());
234 return std::error_code();
238 windows::GetCommandLineArguments(SmallVectorImpl<const char *> &Args,
239 BumpPtrAllocator &Alloc) {
240 const wchar_t *CmdW = GetCommandLineW();
243 SmallString<MAX_PATH> Cmd;
244 EC = windows::UTF16ToUTF8(CmdW, wcslen(CmdW), Cmd);
248 SmallVector<const char *, 20> TmpArgs;
249 StringSaver Saver(Alloc);
250 cl::TokenizeWindowsCommandLine(Cmd, Saver, TmpArgs, /*MarkEOLs=*/false);
252 for (const char *Arg : TmpArgs) {
253 EC = WildcardExpand(Arg, Args, Saver);
258 SmallVector<char, MAX_PATH> Arg0(Args[0], Args[0] + strlen(Args[0]));
259 SmallVector<char, MAX_PATH> Filename;
260 sys::path::remove_filename(Arg0);
261 EC = GetExecutableName(Filename);
264 sys::path::append(Arg0, Filename);
265 Args[0] = Saver.save(Arg0).data();
266 return std::error_code();
269 std::error_code Process::FixupStandardFileDescriptors() {
270 return std::error_code();
273 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
275 return std::error_code(errno, std::generic_category());
276 return std::error_code();
279 bool Process::StandardInIsUserInput() {
280 return FileDescriptorIsDisplayed(0);
283 bool Process::StandardOutIsDisplayed() {
284 return FileDescriptorIsDisplayed(1);
287 bool Process::StandardErrIsDisplayed() {
288 return FileDescriptorIsDisplayed(2);
291 bool Process::FileDescriptorIsDisplayed(int fd) {
292 DWORD Mode; // Unused
293 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
296 unsigned Process::StandardOutColumns() {
297 unsigned Columns = 0;
298 CONSOLE_SCREEN_BUFFER_INFO csbi;
299 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
300 Columns = csbi.dwSize.X;
304 unsigned Process::StandardErrColumns() {
305 unsigned Columns = 0;
306 CONSOLE_SCREEN_BUFFER_INFO csbi;
307 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
308 Columns = csbi.dwSize.X;
312 // The terminal always has colors.
313 bool Process::FileDescriptorHasColors(int fd) {
314 return FileDescriptorIsDisplayed(fd);
317 bool Process::StandardOutHasColors() {
318 return FileDescriptorHasColors(1);
321 bool Process::StandardErrHasColors() {
322 return FileDescriptorHasColors(2);
325 static bool UseANSI = false;
326 void Process::UseANSIEscapeCodes(bool enable) {
327 #if defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
329 HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE);
331 GetConsoleMode(Console, &Mode);
332 Mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
333 SetConsoleMode(Console, Mode);
346 :defaultColor(GetCurrentColor()) {}
347 static unsigned GetCurrentColor() {
348 CONSOLE_SCREEN_BUFFER_INFO csbi;
349 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
350 return csbi.wAttributes;
353 WORD operator()() const { return defaultColor; }
356 DefaultColors defaultColors;
358 WORD fg_color(WORD color) {
359 return color & (FOREGROUND_BLUE | FOREGROUND_GREEN |
360 FOREGROUND_INTENSITY | FOREGROUND_RED);
363 WORD bg_color(WORD color) {
364 return color & (BACKGROUND_BLUE | BACKGROUND_GREEN |
365 BACKGROUND_INTENSITY | BACKGROUND_RED);
369 bool Process::ColorNeedsFlush() {
373 const char *Process::OutputBold(bool bg) {
374 if (UseANSI) return "\033[1m";
376 WORD colors = DefaultColors::GetCurrentColor();
378 colors |= BACKGROUND_INTENSITY;
380 colors |= FOREGROUND_INTENSITY;
381 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
385 const char *Process::OutputColor(char code, bool bold, bool bg) {
386 if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
388 WORD current = DefaultColors::GetCurrentColor();
391 colors = ((code&1) ? BACKGROUND_RED : 0) |
392 ((code&2) ? BACKGROUND_GREEN : 0 ) |
393 ((code&4) ? BACKGROUND_BLUE : 0);
395 colors |= BACKGROUND_INTENSITY;
396 colors |= fg_color(current);
398 colors = ((code&1) ? FOREGROUND_RED : 0) |
399 ((code&2) ? FOREGROUND_GREEN : 0 ) |
400 ((code&4) ? FOREGROUND_BLUE : 0);
402 colors |= FOREGROUND_INTENSITY;
403 colors |= bg_color(current);
405 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
409 static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
410 CONSOLE_SCREEN_BUFFER_INFO info;
411 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
412 return info.wAttributes;
415 const char *Process::OutputReverse() {
416 if (UseANSI) return "\033[7m";
418 const WORD attributes
419 = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
421 const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
422 FOREGROUND_RED | FOREGROUND_INTENSITY;
423 const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
424 BACKGROUND_RED | BACKGROUND_INTENSITY;
425 const WORD color_mask = foreground_mask | background_mask;
427 WORD new_attributes =
428 ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
429 ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
430 ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
431 ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
432 ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
433 ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
434 ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
435 ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
437 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
439 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
443 const char *Process::ResetColor() {
444 if (UseANSI) return "\033[0m";
445 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
449 static unsigned GetRandomNumberSeed() {
450 // Generate a random number seed from the millisecond-resolution Windows
451 // system clock and the current process id.
453 GetSystemTimeAsFileTime(&Time);
454 DWORD Pid = GetCurrentProcessId();
455 return hash_combine(Time.dwHighDateTime, Time.dwLowDateTime, Pid);
458 static unsigned GetPseudoRandomNumber() {
459 // Arrange to call srand once when this function is first used, and
460 // otherwise (if GetRandomNumber always succeeds in using
461 // CryptGenRandom) don't bother at all.
462 static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0);
467 unsigned Process::GetRandomNumber() {
468 // Try to use CryptGenRandom.
470 if (::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
471 CRYPT_VERIFYCONTEXT)) {
472 ScopedCryptContext CryptoProvider(HCPC);
474 if (::CryptGenRandom(CryptoProvider, sizeof(Ret),
475 reinterpret_cast<BYTE *>(&Ret)))
479 // If that fails, fall back to pseudo-random numbers.
480 return GetPseudoRandomNumber();
483 typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
484 #define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
486 llvm::VersionTuple llvm::GetWindowsOSVersion() {
487 HMODULE hMod = ::GetModuleHandleW(L"ntdll.dll");
489 auto getVer = (RtlGetVersionPtr)::GetProcAddress(hMod, "RtlGetVersion");
491 RTL_OSVERSIONINFOEXW info{};
492 info.dwOSVersionInfoSize = sizeof(info);
493 if (getVer((PRTL_OSVERSIONINFOW)&info) == STATUS_SUCCESS) {
494 return llvm::VersionTuple(info.dwMajorVersion, info.dwMinorVersion, 0,
499 return llvm::VersionTuple(0, 0, 0, 0);
502 bool llvm::RunningWindows8OrGreater() {
503 // Windows 8 is version 6.2, service pack 0.
504 return GetWindowsOSVersion() >= llvm::VersionTuple(6, 2, 0, 0);
507 [[noreturn]] void Process::ExitNoCleanup(int RetCode) {
508 TerminateProcess(GetCurrentProcess(), RetCode);
509 llvm_unreachable("TerminateProcess doesn't return");