Process.inc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. #include "llvm/Support/Allocator.h"
  13. #include "llvm/Support/CommandLine.h"
  14. #include "llvm/Support/ConvertUTF.h"
  15. #include "llvm/Support/ErrorHandling.h"
  16. #include "llvm/Support/StringSaver.h"
  17. #include "llvm/Support/WindowsError.h"
  18. #include <malloc.h>
  19. #include <optional>
  20. // The Windows.h header must be after LLVM and standard headers.
  21. #include "llvm/Support/Windows/WindowsSupport.h"
  22. #include <direct.h>
  23. #include <io.h>
  24. #include <psapi.h>
  25. #include <shellapi.h>
  26. #if !defined(__MINGW32__)
  27. #pragma comment(lib, "psapi.lib")
  28. #pragma comment(lib, "shell32.lib")
  29. #endif
  30. //===----------------------------------------------------------------------===//
  31. //=== WARNING: Implementation here must contain only Win32 specific code
  32. //=== and must not be UNIX code
  33. //===----------------------------------------------------------------------===//
  34. #ifdef __MINGW32__
  35. // This ban should be lifted when MinGW 1.0+ has defined this value.
  36. #define _HEAPOK (-2)
  37. #endif
  38. using namespace llvm;
  39. Process::Pid Process::getProcessId() {
  40. static_assert(sizeof(Pid) >= sizeof(DWORD),
  41. "Process::Pid should be big enough to store DWORD");
  42. return Pid(::GetCurrentProcessId());
  43. }
  44. // This function retrieves the page size using GetNativeSystemInfo() and is
  45. // present solely so it can be called once to initialize the self_process member
  46. // below.
  47. static unsigned computePageSize() {
  48. // GetNativeSystemInfo() provides the physical page size which may differ
  49. // from GetSystemInfo() in 32-bit applications running under WOW64.
  50. SYSTEM_INFO info;
  51. GetNativeSystemInfo(&info);
  52. // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
  53. // but dwAllocationGranularity.
  54. return static_cast<unsigned>(info.dwPageSize);
  55. }
  56. Expected<unsigned> Process::getPageSize() {
  57. static unsigned Ret = computePageSize();
  58. return Ret;
  59. }
  60. size_t Process::GetMallocUsage() {
  61. _HEAPINFO hinfo;
  62. hinfo._pentry = NULL;
  63. size_t size = 0;
  64. while (_heapwalk(&hinfo) == _HEAPOK)
  65. size += hinfo._size;
  66. return size;
  67. }
  68. void Process::GetTimeUsage(TimePoint<> &elapsed,
  69. std::chrono::nanoseconds &user_time,
  70. std::chrono::nanoseconds &sys_time) {
  71. elapsed = std::chrono::system_clock::now();
  72. ;
  73. FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
  74. if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
  75. &UserTime) == 0)
  76. return;
  77. user_time = toDuration(UserTime);
  78. sys_time = toDuration(KernelTime);
  79. }
  80. // Some LLVM programs such as bugpoint produce core files as a normal part of
  81. // their operation. To prevent the disk from filling up, this configuration
  82. // item does what's necessary to prevent their generation.
  83. void Process::PreventCoreFiles() {
  84. // Windows does have the concept of core files, called minidumps. However,
  85. // disabling minidumps for a particular application extends past the lifetime
  86. // of that application, which is the incorrect behavior for this API.
  87. // Additionally, the APIs require elevated privileges to disable and re-
  88. // enable minidumps, which makes this untenable. For more information, see
  89. // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
  90. // later).
  91. //
  92. // Windows also has modal pop-up message boxes. As this method is used by
  93. // bugpoint, preventing these pop-ups is additionally important.
  94. SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
  95. SEM_NOOPENFILEERRORBOX);
  96. coreFilesPrevented = true;
  97. }
  98. /// Returns the environment variable \arg Name's value as a string encoded in
  99. /// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
  100. std::optional<std::string> Process::GetEnv(StringRef Name) {
  101. // Convert the argument to UTF-16 to pass it to _wgetenv().
  102. SmallVector<wchar_t, 128> NameUTF16;
  103. if (windows::UTF8ToUTF16(Name, NameUTF16))
  104. return std::nullopt;
  105. // Environment variable can be encoded in non-UTF8 encoding, and there's no
  106. // way to know what the encoding is. The only reliable way to look up
  107. // multibyte environment variable is to use GetEnvironmentVariableW().
  108. SmallVector<wchar_t, MAX_PATH> Buf;
  109. size_t Size = MAX_PATH;
  110. do {
  111. Buf.resize_for_overwrite(Size);
  112. SetLastError(NO_ERROR);
  113. Size = GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.size());
  114. if (Size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
  115. return std::nullopt;
  116. // Try again with larger buffer.
  117. } while (Size > Buf.size());
  118. Buf.truncate(Size);
  119. // Convert the result from UTF-16 to UTF-8.
  120. SmallVector<char, MAX_PATH> Res;
  121. if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
  122. return std::nullopt;
  123. return std::string(Res.data());
  124. }
  125. /// Perform wildcard expansion of Arg, or just push it into Args if it doesn't
  126. /// have wildcards or doesn't match any files.
  127. static std::error_code WildcardExpand(StringRef Arg,
  128. SmallVectorImpl<const char *> &Args,
  129. StringSaver &Saver) {
  130. std::error_code EC;
  131. // Don't expand Arg if it does not contain any wildcard characters. This is
  132. // the common case. Also don't wildcard expand /?. Always treat it as an
  133. // option. Paths that start with \\?\ are absolute paths, and aren't
  134. // expected to be used with wildcard expressions.
  135. if (Arg.find_first_of("*?") == StringRef::npos || Arg == "/?" ||
  136. Arg == "-?" || Arg.startswith("\\\\?\\")) {
  137. Args.push_back(Arg.data());
  138. return EC;
  139. }
  140. // Convert back to UTF-16 so we can call FindFirstFileW.
  141. SmallVector<wchar_t, MAX_PATH> ArgW;
  142. EC = windows::UTF8ToUTF16(Arg, ArgW);
  143. if (EC)
  144. return EC;
  145. // Search for matching files.
  146. // FIXME: This assumes the wildcard is only in the file name and not in the
  147. // directory portion of the file path. For example, it doesn't handle
  148. // "*\foo.c" nor "s?c\bar.cpp".
  149. WIN32_FIND_DATAW FileData;
  150. HANDLE FindHandle = FindFirstFileW(ArgW.data(), &FileData);
  151. if (FindHandle == INVALID_HANDLE_VALUE) {
  152. Args.push_back(Arg.data());
  153. return EC;
  154. }
  155. // Extract any directory part of the argument.
  156. SmallString<MAX_PATH> Dir = Arg;
  157. sys::path::remove_filename(Dir);
  158. const int DirSize = Dir.size();
  159. do {
  160. SmallString<MAX_PATH> FileName;
  161. EC = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
  162. FileName);
  163. if (EC)
  164. break;
  165. // Append FileName to Dir, and remove it afterwards.
  166. llvm::sys::path::append(Dir, FileName);
  167. Args.push_back(Saver.save(Dir.str()).data());
  168. Dir.resize(DirSize);
  169. } while (FindNextFileW(FindHandle, &FileData));
  170. FindClose(FindHandle);
  171. return EC;
  172. }
  173. static std::error_code GetExecutableName(SmallVectorImpl<char> &Filename) {
  174. // The first argument may contain just the name of the executable (e.g.,
  175. // "clang") rather than the full path, so swap it with the full path.
  176. wchar_t ModuleName[MAX_PATH];
  177. size_t Length = ::GetModuleFileNameW(NULL, ModuleName, MAX_PATH);
  178. if (Length == 0 || Length == MAX_PATH) {
  179. return mapWindowsError(GetLastError());
  180. }
  181. // If the first argument is a shortened (8.3) name (which is possible even
  182. // if we got the module name), the driver will have trouble distinguishing it
  183. // (e.g., clang.exe v. clang++.exe), so expand it now.
  184. Length = GetLongPathNameW(ModuleName, ModuleName, MAX_PATH);
  185. if (Length == 0)
  186. return mapWindowsError(GetLastError());
  187. if (Length > MAX_PATH) {
  188. // We're not going to try to deal with paths longer than MAX_PATH, so we'll
  189. // treat this as an error. GetLastError() returns ERROR_SUCCESS, which
  190. // isn't useful, so we'll hardcode an appropriate error value.
  191. return mapWindowsError(ERROR_INSUFFICIENT_BUFFER);
  192. }
  193. std::error_code EC = windows::UTF16ToUTF8(ModuleName, Length, Filename);
  194. if (EC)
  195. return EC;
  196. // Make a copy of the filename since assign makes the StringRef invalid.
  197. std::string Base = sys::path::filename(Filename.data()).str();
  198. Filename.assign(Base.begin(), Base.end());
  199. return std::error_code();
  200. }
  201. std::error_code
  202. windows::GetCommandLineArguments(SmallVectorImpl<const char *> &Args,
  203. BumpPtrAllocator &Alloc) {
  204. const wchar_t *CmdW = GetCommandLineW();
  205. assert(CmdW);
  206. std::error_code EC;
  207. SmallString<MAX_PATH> Cmd;
  208. EC = windows::UTF16ToUTF8(CmdW, wcslen(CmdW), Cmd);
  209. if (EC)
  210. return EC;
  211. SmallVector<const char *, 20> TmpArgs;
  212. StringSaver Saver(Alloc);
  213. cl::TokenizeWindowsCommandLineFull(Cmd, Saver, TmpArgs, /*MarkEOLs=*/false);
  214. for (const char *Arg : TmpArgs) {
  215. EC = WildcardExpand(Arg, Args, Saver);
  216. if (EC)
  217. return EC;
  218. }
  219. if (Args.size() == 0)
  220. return std::make_error_code(std::errc::invalid_argument);
  221. SmallVector<char, MAX_PATH> Arg0(Args[0], Args[0] + strlen(Args[0]));
  222. SmallVector<char, MAX_PATH> Filename;
  223. sys::path::remove_filename(Arg0);
  224. EC = GetExecutableName(Filename);
  225. if (EC)
  226. return EC;
  227. sys::path::make_preferred(Arg0);
  228. sys::path::append(Arg0, Filename);
  229. Args[0] = Saver.save(Arg0).data();
  230. return std::error_code();
  231. }
  232. std::error_code Process::FixupStandardFileDescriptors() {
  233. return std::error_code();
  234. }
  235. std::error_code Process::SafelyCloseFileDescriptor(int FD) {
  236. if (::close(FD) < 0)
  237. return std::error_code(errno, std::generic_category());
  238. return std::error_code();
  239. }
  240. bool Process::StandardInIsUserInput() { return FileDescriptorIsDisplayed(0); }
  241. bool Process::StandardOutIsDisplayed() { return FileDescriptorIsDisplayed(1); }
  242. bool Process::StandardErrIsDisplayed() { return FileDescriptorIsDisplayed(2); }
  243. bool Process::FileDescriptorIsDisplayed(int fd) {
  244. DWORD Mode; // Unused
  245. return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
  246. }
  247. unsigned Process::StandardOutColumns() {
  248. unsigned Columns = 0;
  249. CONSOLE_SCREEN_BUFFER_INFO csbi;
  250. if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
  251. Columns = csbi.dwSize.X;
  252. return Columns;
  253. }
  254. unsigned Process::StandardErrColumns() {
  255. unsigned Columns = 0;
  256. CONSOLE_SCREEN_BUFFER_INFO csbi;
  257. if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
  258. Columns = csbi.dwSize.X;
  259. return Columns;
  260. }
  261. // The terminal always has colors.
  262. bool Process::FileDescriptorHasColors(int fd) {
  263. return FileDescriptorIsDisplayed(fd);
  264. }
  265. bool Process::StandardOutHasColors() { return FileDescriptorHasColors(1); }
  266. bool Process::StandardErrHasColors() { return FileDescriptorHasColors(2); }
  267. static bool UseANSI = false;
  268. void Process::UseANSIEscapeCodes(bool enable) {
  269. #if defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
  270. if (enable) {
  271. HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE);
  272. DWORD Mode;
  273. GetConsoleMode(Console, &Mode);
  274. Mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  275. SetConsoleMode(Console, Mode);
  276. }
  277. #endif
  278. UseANSI = enable;
  279. }
  280. namespace {
  281. class DefaultColors {
  282. private:
  283. WORD defaultColor;
  284. public:
  285. DefaultColors() : defaultColor(GetCurrentColor()) {}
  286. static unsigned GetCurrentColor() {
  287. CONSOLE_SCREEN_BUFFER_INFO csbi;
  288. if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
  289. return csbi.wAttributes;
  290. return 0;
  291. }
  292. WORD operator()() const { return defaultColor; }
  293. };
  294. DefaultColors defaultColors;
  295. WORD fg_color(WORD color) {
  296. return color & (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY |
  297. FOREGROUND_RED);
  298. }
  299. WORD bg_color(WORD color) {
  300. return color & (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_INTENSITY |
  301. BACKGROUND_RED);
  302. }
  303. } // namespace
  304. bool Process::ColorNeedsFlush() { return !UseANSI; }
  305. const char *Process::OutputBold(bool bg) {
  306. if (UseANSI)
  307. return "\033[1m";
  308. WORD colors = DefaultColors::GetCurrentColor();
  309. if (bg)
  310. colors |= BACKGROUND_INTENSITY;
  311. else
  312. colors |= FOREGROUND_INTENSITY;
  313. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
  314. return 0;
  315. }
  316. const char *Process::OutputColor(char code, bool bold, bool bg) {
  317. if (UseANSI)
  318. return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 7];
  319. WORD current = DefaultColors::GetCurrentColor();
  320. WORD colors;
  321. if (bg) {
  322. colors = ((code & 1) ? BACKGROUND_RED : 0) |
  323. ((code & 2) ? BACKGROUND_GREEN : 0) |
  324. ((code & 4) ? BACKGROUND_BLUE : 0);
  325. if (bold)
  326. colors |= BACKGROUND_INTENSITY;
  327. colors |= fg_color(current);
  328. } else {
  329. colors = ((code & 1) ? FOREGROUND_RED : 0) |
  330. ((code & 2) ? FOREGROUND_GREEN : 0) |
  331. ((code & 4) ? FOREGROUND_BLUE : 0);
  332. if (bold)
  333. colors |= FOREGROUND_INTENSITY;
  334. colors |= bg_color(current);
  335. }
  336. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
  337. return 0;
  338. }
  339. static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
  340. CONSOLE_SCREEN_BUFFER_INFO info;
  341. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
  342. return info.wAttributes;
  343. }
  344. const char *Process::OutputReverse() {
  345. if (UseANSI)
  346. return "\033[7m";
  347. const WORD attributes =
  348. GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
  349. const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
  350. FOREGROUND_RED | FOREGROUND_INTENSITY;
  351. const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
  352. BACKGROUND_RED | BACKGROUND_INTENSITY;
  353. const WORD color_mask = foreground_mask | background_mask;
  354. WORD new_attributes =
  355. ((attributes & FOREGROUND_BLUE) ? BACKGROUND_BLUE : 0) |
  356. ((attributes & FOREGROUND_GREEN) ? BACKGROUND_GREEN : 0) |
  357. ((attributes & FOREGROUND_RED) ? BACKGROUND_RED : 0) |
  358. ((attributes & FOREGROUND_INTENSITY) ? BACKGROUND_INTENSITY : 0) |
  359. ((attributes & BACKGROUND_BLUE) ? FOREGROUND_BLUE : 0) |
  360. ((attributes & BACKGROUND_GREEN) ? FOREGROUND_GREEN : 0) |
  361. ((attributes & BACKGROUND_RED) ? FOREGROUND_RED : 0) |
  362. ((attributes & BACKGROUND_INTENSITY) ? FOREGROUND_INTENSITY : 0) | 0;
  363. new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
  364. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
  365. return 0;
  366. }
  367. const char *Process::ResetColor() {
  368. if (UseANSI)
  369. return "\033[0m";
  370. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
  371. return 0;
  372. }
  373. static unsigned GetRandomNumberSeed() {
  374. // Generate a random number seed from the millisecond-resolution Windows
  375. // system clock and the current process id.
  376. FILETIME Time;
  377. GetSystemTimeAsFileTime(&Time);
  378. DWORD Pid = GetCurrentProcessId();
  379. return hash_combine(Time.dwHighDateTime, Time.dwLowDateTime, Pid);
  380. }
  381. static unsigned GetPseudoRandomNumber() {
  382. // Arrange to call srand once when this function is first used, and
  383. // otherwise (if GetRandomNumber always succeeds in using
  384. // CryptGenRandom) don't bother at all.
  385. static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0);
  386. (void)x;
  387. return ::rand();
  388. }
  389. unsigned Process::GetRandomNumber() {
  390. // Try to use CryptGenRandom.
  391. HCRYPTPROV HCPC;
  392. if (::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
  393. CRYPT_VERIFYCONTEXT)) {
  394. ScopedCryptContext CryptoProvider(HCPC);
  395. unsigned Ret;
  396. if (::CryptGenRandom(CryptoProvider, sizeof(Ret),
  397. reinterpret_cast<BYTE *>(&Ret)))
  398. return Ret;
  399. }
  400. // If that fails, fall back to pseudo-random numbers.
  401. return GetPseudoRandomNumber();
  402. }
  403. typedef NTSTATUS(WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
  404. #define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
  405. static RTL_OSVERSIONINFOEXW GetWindowsVer() {
  406. auto getVer = []() -> RTL_OSVERSIONINFOEXW {
  407. HMODULE hMod = ::GetModuleHandleW(L"ntdll.dll");
  408. assert(hMod);
  409. auto getVer = (RtlGetVersionPtr)::GetProcAddress(hMod, "RtlGetVersion");
  410. assert(getVer);
  411. RTL_OSVERSIONINFOEXW info{};
  412. info.dwOSVersionInfoSize = sizeof(info);
  413. NTSTATUS r = getVer((PRTL_OSVERSIONINFOW)&info);
  414. (void)r;
  415. assert(r == STATUS_SUCCESS);
  416. return info;
  417. };
  418. static RTL_OSVERSIONINFOEXW info = getVer();
  419. return info;
  420. }
  421. llvm::VersionTuple llvm::GetWindowsOSVersion() {
  422. RTL_OSVERSIONINFOEXW info = GetWindowsVer();
  423. return llvm::VersionTuple(info.dwMajorVersion, info.dwMinorVersion, 0,
  424. info.dwBuildNumber);
  425. }
  426. bool llvm::RunningWindows8OrGreater() {
  427. // Windows 8 is version 6.2, service pack 0.
  428. return GetWindowsOSVersion() >= llvm::VersionTuple(6, 2, 0, 0);
  429. }
  430. bool llvm::RunningWindows11OrGreater() {
  431. RTL_OSVERSIONINFOEXW info = GetWindowsVer();
  432. auto ver = llvm::VersionTuple(info.dwMajorVersion, info.dwMinorVersion, 0,
  433. info.dwBuildNumber);
  434. // Windows Server 2022
  435. if (info.wProductType == VER_NT_SERVER)
  436. return ver >= llvm::VersionTuple(10, 0, 0, 20348);
  437. // Windows 11
  438. return ver >= llvm::VersionTuple(10, 0, 0, 22000);
  439. }
  440. [[noreturn]] void Process::ExitNoCleanup(int RetCode) {
  441. TerminateProcess(GetCurrentProcess(), RetCode);
  442. llvm_unreachable("TerminateProcess doesn't return");
  443. }