1//===- Win32/Process.cpp - Win32 Process Implementation ------- -*- C++ -*-===// 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 provides the Win32 specific implementation of the Process class. 10// 11//===----------------------------------------------------------------------===// 12 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" 19#include <malloc.h> 20 21// The Windows.h header must be after LLVM and standard headers. 22#include "llvm/Support/Windows/WindowsSupport.h" 23 24#include <direct.h> 25#include <io.h> 26#include <psapi.h> 27#include <shellapi.h> 28 29#if !defined(__MINGW32__) 30 #pragma comment(lib, "psapi.lib") 31 #pragma comment(lib, "shell32.lib") 32#endif 33 34//===----------------------------------------------------------------------===// 35//=== WARNING: Implementation here must contain only Win32 specific code 36//=== and must not be UNIX code 37//===----------------------------------------------------------------------===// 38 39#ifdef __MINGW32__ 40// This ban should be lifted when MinGW 1.0+ has defined this value. 41# define _HEAPOK (-2) 42#endif 43 44using namespace llvm; 45 46Process::Pid Process::getProcessId() { 47 static_assert(sizeof(Pid) >= sizeof(DWORD), 48 "Process::Pid should be big enough to store DWORD"); 49 return Pid(::GetCurrentProcessId()); 50} 51 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 54// below. 55static unsigned computePageSize() { 56 // GetNativeSystemInfo() provides the physical page size which may differ 57 // from GetSystemInfo() in 32-bit applications running under WOW64. 58 SYSTEM_INFO info; 59 GetNativeSystemInfo(&info); 60 // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize, 61 // but dwAllocationGranularity. 62 return static_cast<unsigned>(info.dwPageSize); 63} 64 65Expected<unsigned> Process::getPageSize() { 66 static unsigned Ret = computePageSize(); 67 return Ret; 68} 69 70size_t 71Process::GetMallocUsage() 72{ 73 _HEAPINFO hinfo; 74 hinfo._pentry = NULL; 75 76 size_t size = 0; 77 78 while (_heapwalk(&hinfo) == _HEAPOK) 79 size += hinfo._size; 80 81 return size; 82} 83 84void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time, 85 std::chrono::nanoseconds &sys_time) { 86 elapsed = std::chrono::system_clock::now();; 87 88 FILETIME ProcCreate, ProcExit, KernelTime, UserTime; 89 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime, 90 &UserTime) == 0) 91 return; 92 93 user_time = toDuration(UserTime); 94 sys_time = toDuration(KernelTime); 95} 96 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. 100void 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 107 // later). 108 // 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); 114 115 coreFilesPrevented = true; 116} 117 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. 120Optional<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)) 124 return None; 125 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; 131 do { 132 Buf.resize_for_overwrite(Size); 133 SetLastError(NO_ERROR); 134 Size = 135 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.size()); 136 if (Size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND) 137 return None; 138 139 // Try again with larger buffer. 140 } while (Size > Buf.size()); 141 Buf.truncate(Size); 142 143 // Convert the result from UTF-16 to UTF-8. 144 SmallVector<char, MAX_PATH> Res; 145 if (windows::UTF16ToUTF8(Buf.data(), Size, Res)) 146 return None; 147 return std::string(Res.data()); 148} 149 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. 152static std::error_code WildcardExpand(StringRef Arg, 153 SmallVectorImpl<const char *> &Args, 154 StringSaver &Saver) { 155 std::error_code EC; 156 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 159 // option. Paths that start with \\?\ are absolute paths, and aren't 160 // expected to be used with wildcard expressions. 161 if (Arg.find_first_of("*?") == StringRef::npos || Arg == "/?" || 162 Arg == "-?" || Arg.startswith("\\\\?\\")) { 163 Args.push_back(Arg.data()); 164 return EC; 165 } 166 167 // Convert back to UTF-16 so we can call FindFirstFileW. 168 SmallVector<wchar_t, MAX_PATH> ArgW; 169 EC = windows::UTF8ToUTF16(Arg, ArgW); 170 if (EC) 171 return EC; 172 173 // Search for matching files. 174 // FIXME: This assumes the wildcard is only in the file name and not in the 175 // directory portion of the file path. For example, it doesn't handle 176 // "*\foo.c" nor "s?c\bar.cpp". 177 WIN32_FIND_DATAW FileData; 178 HANDLE FindHandle = FindFirstFileW(ArgW.data(), &FileData); 179 if (FindHandle == INVALID_HANDLE_VALUE) { 180 Args.push_back(Arg.data()); 181 return EC; 182 } 183 184 // Extract any directory part of the argument. 185 SmallString<MAX_PATH> Dir = Arg; 186 sys::path::remove_filename(Dir); 187 const int DirSize = Dir.size(); 188 189 do { 190 SmallString<MAX_PATH> FileName; 191 EC = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName), 192 FileName); 193 if (EC) 194 break; 195 196 // Append FileName to Dir, and remove it afterwards. 197 llvm::sys::path::append(Dir, FileName); 198 Args.push_back(Saver.save(Dir.str()).data()); 199 Dir.resize(DirSize); 200 } while (FindNextFileW(FindHandle, &FileData)); 201 202 FindClose(FindHandle); 203 return EC; 204} 205 206static std::error_code GetExecutableName(SmallVectorImpl<char> &Filename) { 207 // The first argument may contain just the name of the executable (e.g., 208 // "clang") rather than the full path, so swap it with the full path. 209 wchar_t ModuleName[MAX_PATH]; 210 size_t Length = ::GetModuleFileNameW(NULL, ModuleName, MAX_PATH); 211 if (Length == 0 || Length == MAX_PATH) { 212 return mapWindowsError(GetLastError()); 213 } 214 215 // If the first argument is a shortened (8.3) name (which is possible even 216 // if we got the module name), the driver will have trouble distinguishing it 217 // (e.g., clang.exe v. clang++.exe), so expand it now. 218 Length = GetLongPathNameW(ModuleName, ModuleName, MAX_PATH); 219 if (Length == 0) 220 return mapWindowsError(GetLastError()); 221 if (Length > MAX_PATH) { 222 // We're not going to try to deal with paths longer than MAX_PATH, so we'll 223 // treat this as an error. GetLastError() returns ERROR_SUCCESS, which 224 // isn't useful, so we'll hardcode an appropriate error value. 225 return mapWindowsError(ERROR_INSUFFICIENT_BUFFER); 226 } 227 228 std::error_code EC = windows::UTF16ToUTF8(ModuleName, Length, Filename); 229 if (EC) 230 return EC; 231 232 // Make a copy of the filename since assign makes the StringRef invalid. 233 std::string Base = sys::path::filename(Filename.data()).str(); 234 Filename.assign(Base.begin(), Base.end()); 235 return std::error_code(); 236} 237 238std::error_code 239windows::GetCommandLineArguments(SmallVectorImpl<const char *> &Args, 240 BumpPtrAllocator &Alloc) { 241 const wchar_t *CmdW = GetCommandLineW(); 242 assert(CmdW); 243 std::error_code EC; 244 SmallString<MAX_PATH> Cmd; 245 EC = windows::UTF16ToUTF8(CmdW, wcslen(CmdW), Cmd); 246 if (EC) 247 return EC; 248 249 SmallVector<const char *, 20> TmpArgs; 250 StringSaver Saver(Alloc); 251 cl::TokenizeWindowsCommandLineFull(Cmd, Saver, TmpArgs, /*MarkEOLs=*/false); 252 253 for (const char *Arg : TmpArgs) { 254 EC = WildcardExpand(Arg, Args, Saver); 255 if (EC) 256 return EC; 257 } 258 259 if (Args.size() == 0) 260 return std::make_error_code(std::errc::invalid_argument); 261 262 SmallVector<char, MAX_PATH> Arg0(Args[0], Args[0] + strlen(Args[0])); 263 SmallVector<char, MAX_PATH> Filename; 264 sys::path::remove_filename(Arg0); 265 EC = GetExecutableName(Filename); 266 if (EC) 267 return EC; 268 sys::path::make_preferred(Arg0); 269 sys::path::append(Arg0, Filename); 270 Args[0] = Saver.save(Arg0).data(); 271 return std::error_code(); 272} 273 274std::error_code Process::FixupStandardFileDescriptors() { 275 return std::error_code(); 276} 277 278std::error_code Process::SafelyCloseFileDescriptor(int FD) { 279 if (::close(FD) < 0) 280 return std::error_code(errno, std::generic_category()); 281 return std::error_code(); 282} 283 284bool Process::StandardInIsUserInput() { 285 return FileDescriptorIsDisplayed(0); 286} 287 288bool Process::StandardOutIsDisplayed() { 289 return FileDescriptorIsDisplayed(1); 290} 291 292bool Process::StandardErrIsDisplayed() { 293 return FileDescriptorIsDisplayed(2); 294} 295 296bool Process::FileDescriptorIsDisplayed(int fd) { 297 DWORD Mode; // Unused 298 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0); 299} 300 301unsigned Process::StandardOutColumns() { 302 unsigned Columns = 0; 303 CONSOLE_SCREEN_BUFFER_INFO csbi; 304 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) 305 Columns = csbi.dwSize.X; 306 return Columns; 307} 308 309unsigned Process::StandardErrColumns() { 310 unsigned Columns = 0; 311 CONSOLE_SCREEN_BUFFER_INFO csbi; 312 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi)) 313 Columns = csbi.dwSize.X; 314 return Columns; 315} 316 317// The terminal always has colors. 318bool Process::FileDescriptorHasColors(int fd) { 319 return FileDescriptorIsDisplayed(fd); 320} 321 322bool Process::StandardOutHasColors() { 323 return FileDescriptorHasColors(1); 324} 325 326bool Process::StandardErrHasColors() { 327 return FileDescriptorHasColors(2); 328} 329 330static bool UseANSI = false; 331void Process::UseANSIEscapeCodes(bool enable) { 332#if defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING) 333 if (enable) { 334 HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE); 335 DWORD Mode; 336 GetConsoleMode(Console, &Mode); 337 Mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; 338 SetConsoleMode(Console, Mode); 339 } 340#endif 341 UseANSI = enable; 342} 343 344namespace { 345class DefaultColors 346{ 347 private: 348 WORD defaultColor; 349 public: 350 DefaultColors() 351 :defaultColor(GetCurrentColor()) {} 352 static unsigned GetCurrentColor() { 353 CONSOLE_SCREEN_BUFFER_INFO csbi; 354 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi)) 355 return csbi.wAttributes; 356 return 0; 357 } 358 WORD operator()() const { return defaultColor; } 359}; 360 361DefaultColors defaultColors; 362 363WORD fg_color(WORD color) { 364 return color & (FOREGROUND_BLUE | FOREGROUND_GREEN | 365 FOREGROUND_INTENSITY | FOREGROUND_RED); 366} 367 368WORD bg_color(WORD color) { 369 return color & (BACKGROUND_BLUE | BACKGROUND_GREEN | 370 BACKGROUND_INTENSITY | BACKGROUND_RED); 371} 372} 373 374bool Process::ColorNeedsFlush() { 375 return !UseANSI; 376} 377 378const char *Process::OutputBold(bool bg) { 379 if (UseANSI) return "\033[1m"; 380 381 WORD colors = DefaultColors::GetCurrentColor(); 382 if (bg) 383 colors |= BACKGROUND_INTENSITY; 384 else 385 colors |= FOREGROUND_INTENSITY; 386 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors); 387 return 0; 388} 389 390const char *Process::OutputColor(char code, bool bold, bool bg) { 391 if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7]; 392 393 WORD current = DefaultColors::GetCurrentColor(); 394 WORD colors; 395 if (bg) { 396 colors = ((code&1) ? BACKGROUND_RED : 0) | 397 ((code&2) ? BACKGROUND_GREEN : 0 ) | 398 ((code&4) ? BACKGROUND_BLUE : 0); 399 if (bold) 400 colors |= BACKGROUND_INTENSITY; 401 colors |= fg_color(current); 402 } else { 403 colors = ((code&1) ? FOREGROUND_RED : 0) | 404 ((code&2) ? FOREGROUND_GREEN : 0 ) | 405 ((code&4) ? FOREGROUND_BLUE : 0); 406 if (bold) 407 colors |= FOREGROUND_INTENSITY; 408 colors |= bg_color(current); 409 } 410 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors); 411 return 0; 412} 413 414static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) { 415 CONSOLE_SCREEN_BUFFER_INFO info; 416 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info); 417 return info.wAttributes; 418} 419 420const char *Process::OutputReverse() { 421 if (UseANSI) return "\033[7m"; 422 423 const WORD attributes 424 = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE)); 425 426 const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN | 427 FOREGROUND_RED | FOREGROUND_INTENSITY; 428 const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN | 429 BACKGROUND_RED | BACKGROUND_INTENSITY; 430 const WORD color_mask = foreground_mask | background_mask; 431 432 WORD new_attributes = 433 ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) | 434 ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) | 435 ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) | 436 ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) | 437 ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) | 438 ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) | 439 ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) | 440 ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) | 441 0; 442 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask); 443 444 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes); 445 return 0; 446} 447 448const char *Process::ResetColor() { 449 if (UseANSI) return "\033[0m"; 450 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors()); 451 return 0; 452} 453 454static unsigned GetRandomNumberSeed() { 455 // Generate a random number seed from the millisecond-resolution Windows 456 // system clock and the current process id. 457 FILETIME Time; 458 GetSystemTimeAsFileTime(&Time); 459 DWORD Pid = GetCurrentProcessId(); 460 return hash_combine(Time.dwHighDateTime, Time.dwLowDateTime, Pid); 461} 462 463static unsigned GetPseudoRandomNumber() { 464 // Arrange to call srand once when this function is first used, and 465 // otherwise (if GetRandomNumber always succeeds in using 466 // CryptGenRandom) don't bother at all. 467 static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0); 468 (void)x; 469 return ::rand(); 470} 471 472unsigned Process::GetRandomNumber() { 473 // Try to use CryptGenRandom. 474 HCRYPTPROV HCPC; 475 if (::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL, 476 CRYPT_VERIFYCONTEXT)) { 477 ScopedCryptContext CryptoProvider(HCPC); 478 unsigned Ret; 479 if (::CryptGenRandom(CryptoProvider, sizeof(Ret), 480 reinterpret_cast<BYTE *>(&Ret))) 481 return Ret; 482 } 483 484 // If that fails, fall back to pseudo-random numbers. 485 return GetPseudoRandomNumber(); 486} 487 488typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW); 489#define STATUS_SUCCESS ((NTSTATUS)0x00000000L) 490 491llvm::VersionTuple llvm::GetWindowsOSVersion() { 492 HMODULE hMod = ::GetModuleHandleW(L"ntdll.dll"); 493 if (hMod) { 494 auto getVer = (RtlGetVersionPtr)::GetProcAddress(hMod, "RtlGetVersion"); 495 if (getVer) { 496 RTL_OSVERSIONINFOEXW info{}; 497 info.dwOSVersionInfoSize = sizeof(info); 498 if (getVer((PRTL_OSVERSIONINFOW)&info) == STATUS_SUCCESS) { 499 return llvm::VersionTuple(info.dwMajorVersion, info.dwMinorVersion, 0, 500 info.dwBuildNumber); 501 } 502 } 503 } 504 return llvm::VersionTuple(0, 0, 0, 0); 505} 506 507bool llvm::RunningWindows8OrGreater() { 508 // Windows 8 is version 6.2, service pack 0. 509 return GetWindowsOSVersion() >= llvm::VersionTuple(6, 2, 0, 0); 510} 511 512[[noreturn]] void Process::ExitNoCleanup(int RetCode) { 513 TerminateProcess(GetCurrentProcess(), RetCode); 514 llvm_unreachable("TerminateProcess doesn't return"); 515} 516