Process.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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. // The Windows.h header must be after LLVM and standard headers.
  20. #include "llvm/Support/Windows/WindowsSupport.h"
  21. #include <direct.h>
  22. #include <io.h>
  23. #include <psapi.h>
  24. #include <shellapi.h>
  25. #if !defined(__MINGW32__)
  26. #pragma comment(lib, "psapi.lib")
  27. #pragma comment(lib, "shell32.lib")
  28. #endif
  29. //===----------------------------------------------------------------------===//
  30. //=== WARNING: Implementation here must contain only Win32 specific code
  31. //=== and must not be UNIX code
  32. //===----------------------------------------------------------------------===//
  33. #ifdef __MINGW32__
  34. // This ban should be lifted when MinGW 1.0+ has defined this value.
  35. # define _HEAPOK (-2)
  36. #endif
  37. using namespace llvm;
  38. Process::Pid Process::getProcessId() {
  39. static_assert(sizeof(Pid) >= sizeof(DWORD),
  40. "Process::Pid should be big enough to store DWORD");
  41. return Pid(::GetCurrentProcessId());
  42. }
  43. // This function retrieves the page size using GetNativeSystemInfo() and is
  44. // present solely so it can be called once to initialize the self_process member
  45. // below.
  46. static unsigned computePageSize() {
  47. // GetNativeSystemInfo() provides the physical page size which may differ
  48. // from GetSystemInfo() in 32-bit applications running under WOW64.
  49. SYSTEM_INFO info;
  50. GetNativeSystemInfo(&info);
  51. // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
  52. // but dwAllocationGranularity.
  53. return static_cast<unsigned>(info.dwPageSize);
  54. }
  55. Expected<unsigned> Process::getPageSize() {
  56. static unsigned Ret = computePageSize();
  57. return Ret;
  58. }
  59. size_t
  60. Process::GetMallocUsage()
  61. {
  62. _HEAPINFO hinfo;
  63. hinfo._pentry = NULL;
  64. size_t size = 0;
  65. while (_heapwalk(&hinfo) == _HEAPOK)
  66. size += hinfo._size;
  67. return size;
  68. }
  69. void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
  70. std::chrono::nanoseconds &sys_time) {
  71. elapsed = std::chrono::system_clock::now();;
  72. FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
  73. if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
  74. &UserTime) == 0)
  75. return;
  76. user_time = toDuration(UserTime);
  77. sys_time = toDuration(KernelTime);
  78. }
  79. // Some LLVM programs such as bugpoint produce core files as a normal part of
  80. // their operation. To prevent the disk from filling up, this configuration
  81. // item does what's necessary to prevent their generation.
  82. void Process::PreventCoreFiles() {
  83. // Windows does have the concept of core files, called minidumps. However,
  84. // disabling minidumps for a particular application extends past the lifetime
  85. // of that application, which is the incorrect behavior for this API.
  86. // Additionally, the APIs require elevated privileges to disable and re-
  87. // enable minidumps, which makes this untenable. For more information, see
  88. // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
  89. // later).
  90. //
  91. // Windows also has modal pop-up message boxes. As this method is used by
  92. // bugpoint, preventing these pop-ups is additionally important.
  93. SetErrorMode(SEM_FAILCRITICALERRORS |
  94. 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. 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 None;
  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 =
  114. GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.size());
  115. if (Size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
  116. return None;
  117. // Try again with larger buffer.
  118. } while (Size > Buf.size());
  119. Buf.truncate(Size);
  120. // Convert the result from UTF-16 to UTF-8.
  121. SmallVector<char, MAX_PATH> Res;
  122. if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
  123. return None;
  124. return std::string(Res.data());
  125. }
  126. /// Perform wildcard expansion of Arg, or just push it into Args if it doesn't
  127. /// have wildcards or doesn't match any files.
  128. static std::error_code WildcardExpand(StringRef Arg,
  129. SmallVectorImpl<const char *> &Args,
  130. StringSaver &Saver) {
  131. std::error_code EC;
  132. // Don't expand Arg if it does not contain any wildcard characters. This is
  133. // the common case. Also don't wildcard expand /?. Always treat it as an
  134. // option.
  135. if (Arg.find_first_of("*?") == StringRef::npos || Arg == "/?" ||
  136. Arg == "-?") {
  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::TokenizeWindowsCommandLine(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. SmallVector<char, MAX_PATH> Arg0(Args[0], Args[0] + strlen(Args[0]));
  220. SmallVector<char, MAX_PATH> Filename;
  221. sys::path::remove_filename(Arg0);
  222. EC = GetExecutableName(Filename);
  223. if (EC)
  224. return EC;
  225. sys::path::make_preferred(Arg0);
  226. sys::path::append(Arg0, Filename);
  227. Args[0] = Saver.save(Arg0).data();
  228. return std::error_code();
  229. }
  230. std::error_code Process::FixupStandardFileDescriptors() {
  231. return std::error_code();
  232. }
  233. std::error_code Process::SafelyCloseFileDescriptor(int FD) {
  234. if (::close(FD) < 0)
  235. return std::error_code(errno, std::generic_category());
  236. return std::error_code();
  237. }
  238. bool Process::StandardInIsUserInput() {
  239. return FileDescriptorIsDisplayed(0);
  240. }
  241. bool Process::StandardOutIsDisplayed() {
  242. return FileDescriptorIsDisplayed(1);
  243. }
  244. bool Process::StandardErrIsDisplayed() {
  245. return FileDescriptorIsDisplayed(2);
  246. }
  247. bool Process::FileDescriptorIsDisplayed(int fd) {
  248. DWORD Mode; // Unused
  249. return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
  250. }
  251. unsigned Process::StandardOutColumns() {
  252. unsigned Columns = 0;
  253. CONSOLE_SCREEN_BUFFER_INFO csbi;
  254. if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
  255. Columns = csbi.dwSize.X;
  256. return Columns;
  257. }
  258. unsigned Process::StandardErrColumns() {
  259. unsigned Columns = 0;
  260. CONSOLE_SCREEN_BUFFER_INFO csbi;
  261. if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
  262. Columns = csbi.dwSize.X;
  263. return Columns;
  264. }
  265. // The terminal always has colors.
  266. bool Process::FileDescriptorHasColors(int fd) {
  267. return FileDescriptorIsDisplayed(fd);
  268. }
  269. bool Process::StandardOutHasColors() {
  270. return FileDescriptorHasColors(1);
  271. }
  272. bool Process::StandardErrHasColors() {
  273. return FileDescriptorHasColors(2);
  274. }
  275. static bool UseANSI = false;
  276. void Process::UseANSIEscapeCodes(bool enable) {
  277. #if defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
  278. if (enable) {
  279. HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE);
  280. DWORD Mode;
  281. GetConsoleMode(Console, &Mode);
  282. Mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
  283. SetConsoleMode(Console, Mode);
  284. }
  285. #endif
  286. UseANSI = enable;
  287. }
  288. namespace {
  289. class DefaultColors
  290. {
  291. private:
  292. WORD defaultColor;
  293. public:
  294. DefaultColors()
  295. :defaultColor(GetCurrentColor()) {}
  296. static unsigned GetCurrentColor() {
  297. CONSOLE_SCREEN_BUFFER_INFO csbi;
  298. if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
  299. return csbi.wAttributes;
  300. return 0;
  301. }
  302. WORD operator()() const { return defaultColor; }
  303. };
  304. DefaultColors defaultColors;
  305. WORD fg_color(WORD color) {
  306. return color & (FOREGROUND_BLUE | FOREGROUND_GREEN |
  307. FOREGROUND_INTENSITY | FOREGROUND_RED);
  308. }
  309. WORD bg_color(WORD color) {
  310. return color & (BACKGROUND_BLUE | BACKGROUND_GREEN |
  311. BACKGROUND_INTENSITY | BACKGROUND_RED);
  312. }
  313. }
  314. bool Process::ColorNeedsFlush() {
  315. return !UseANSI;
  316. }
  317. const char *Process::OutputBold(bool bg) {
  318. if (UseANSI) return "\033[1m";
  319. WORD colors = DefaultColors::GetCurrentColor();
  320. if (bg)
  321. colors |= BACKGROUND_INTENSITY;
  322. else
  323. colors |= FOREGROUND_INTENSITY;
  324. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
  325. return 0;
  326. }
  327. const char *Process::OutputColor(char code, bool bold, bool bg) {
  328. if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
  329. WORD current = DefaultColors::GetCurrentColor();
  330. WORD colors;
  331. if (bg) {
  332. colors = ((code&1) ? BACKGROUND_RED : 0) |
  333. ((code&2) ? BACKGROUND_GREEN : 0 ) |
  334. ((code&4) ? BACKGROUND_BLUE : 0);
  335. if (bold)
  336. colors |= BACKGROUND_INTENSITY;
  337. colors |= fg_color(current);
  338. } else {
  339. colors = ((code&1) ? FOREGROUND_RED : 0) |
  340. ((code&2) ? FOREGROUND_GREEN : 0 ) |
  341. ((code&4) ? FOREGROUND_BLUE : 0);
  342. if (bold)
  343. colors |= FOREGROUND_INTENSITY;
  344. colors |= bg_color(current);
  345. }
  346. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
  347. return 0;
  348. }
  349. static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
  350. CONSOLE_SCREEN_BUFFER_INFO info;
  351. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
  352. return info.wAttributes;
  353. }
  354. const char *Process::OutputReverse() {
  355. if (UseANSI) return "\033[7m";
  356. const WORD attributes
  357. = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
  358. const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
  359. FOREGROUND_RED | FOREGROUND_INTENSITY;
  360. const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
  361. BACKGROUND_RED | BACKGROUND_INTENSITY;
  362. const WORD color_mask = foreground_mask | background_mask;
  363. WORD new_attributes =
  364. ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
  365. ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
  366. ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
  367. ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
  368. ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
  369. ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
  370. ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
  371. ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
  372. 0;
  373. new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
  374. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
  375. return 0;
  376. }
  377. const char *Process::ResetColor() {
  378. if (UseANSI) return "\033[0m";
  379. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
  380. return 0;
  381. }
  382. static unsigned GetRandomNumberSeed() {
  383. // Generate a random number seed from the millisecond-resolution Windows
  384. // system clock and the current process id.
  385. FILETIME Time;
  386. GetSystemTimeAsFileTime(&Time);
  387. DWORD Pid = GetCurrentProcessId();
  388. return hash_combine(Time.dwHighDateTime, Time.dwLowDateTime, Pid);
  389. }
  390. static unsigned GetPseudoRandomNumber() {
  391. // Arrange to call srand once when this function is first used, and
  392. // otherwise (if GetRandomNumber always succeeds in using
  393. // CryptGenRandom) don't bother at all.
  394. static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0);
  395. (void)x;
  396. return ::rand();
  397. }
  398. unsigned Process::GetRandomNumber() {
  399. // Try to use CryptGenRandom.
  400. HCRYPTPROV HCPC;
  401. if (::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
  402. CRYPT_VERIFYCONTEXT)) {
  403. ScopedCryptContext CryptoProvider(HCPC);
  404. unsigned Ret;
  405. if (::CryptGenRandom(CryptoProvider, sizeof(Ret),
  406. reinterpret_cast<BYTE *>(&Ret)))
  407. return Ret;
  408. }
  409. // If that fails, fall back to pseudo-random numbers.
  410. return GetPseudoRandomNumber();
  411. }
  412. typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
  413. #define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
  414. llvm::VersionTuple llvm::GetWindowsOSVersion() {
  415. HMODULE hMod = ::GetModuleHandleW(L"ntdll.dll");
  416. if (hMod) {
  417. auto getVer = (RtlGetVersionPtr)::GetProcAddress(hMod, "RtlGetVersion");
  418. if (getVer) {
  419. RTL_OSVERSIONINFOEXW info{};
  420. info.dwOSVersionInfoSize = sizeof(info);
  421. if (getVer((PRTL_OSVERSIONINFOW)&info) == STATUS_SUCCESS) {
  422. return llvm::VersionTuple(info.dwMajorVersion, info.dwMinorVersion, 0,
  423. info.dwBuildNumber);
  424. }
  425. }
  426. }
  427. return llvm::VersionTuple(0, 0, 0, 0);
  428. }
  429. bool llvm::RunningWindows8OrGreater() {
  430. // Windows 8 is version 6.2, service pack 0.
  431. return GetWindowsOSVersion() >= llvm::VersionTuple(6, 2, 0, 0);
  432. }
  433. [[noreturn]] void Process::ExitNoCleanup(int RetCode) {
  434. TerminateProcess(GetCurrentProcess(), RetCode);
  435. llvm_unreachable("TerminateProcess doesn't return");
  436. }