Process.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. //===- Win32/Process.cpp - Win32 Process Implementation ------- -*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file provides the Win32 specific implementation of the Process class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Support/Allocator.h"
  14. #include "llvm/Support/ErrorHandling.h"
  15. #include "llvm/Support/WindowsError.h"
  16. #include <malloc.h>
  17. // The Windows.h header must be after LLVM and standard headers.
  18. #include "WindowsSupport.h"
  19. #include <direct.h>
  20. #include <io.h>
  21. #include <psapi.h>
  22. // #include <shellapi.h> // HLSL Change
  23. #ifdef __MINGW32__
  24. #if (HAVE_LIBPSAPI != 1)
  25. #error "libpsapi.a should be present"
  26. #endif
  27. #if (HAVE_LIBSHELL32 != 1)
  28. #error "libshell32.a should be present"
  29. #endif
  30. #else
  31. // #pragma comment(lib, "psapi.lib") // HLSL Change
  32. // #pragma comment(lib, "shell32.lib") // HLSL Change
  33. #endif
  34. //===----------------------------------------------------------------------===//
  35. //=== WARNING: Implementation here must contain only Win32 specific code
  36. //=== and must not be UNIX code
  37. //===----------------------------------------------------------------------===//
  38. #ifdef __MINGW32__
  39. // This ban should be lifted when MinGW 1.0+ has defined this value.
  40. # define _HEAPOK (-2)
  41. #endif
  42. using namespace llvm;
  43. using namespace sys;
  44. static TimeValue getTimeValueFromFILETIME(FILETIME Time) {
  45. ULARGE_INTEGER TimeInteger;
  46. TimeInteger.LowPart = Time.dwLowDateTime;
  47. TimeInteger.HighPart = Time.dwHighDateTime;
  48. // FILETIME's are # of 100 nanosecond ticks (1/10th of a microsecond)
  49. return TimeValue(
  50. static_cast<TimeValue::SecondsType>(TimeInteger.QuadPart / 10000000),
  51. static_cast<TimeValue::NanoSecondsType>(
  52. (TimeInteger.QuadPart % 10000000) * 100));
  53. }
  54. // This function retrieves the page size using GetNativeSystemInfo() and is
  55. // present solely so it can be called once to initialize the self_process member
  56. // below.
  57. static unsigned computePageSize() {
  58. // GetNativeSystemInfo() provides the physical page size which may differ
  59. // from GetSystemInfo() in 32-bit applications running under WOW64.
  60. SYSTEM_INFO info;
  61. GetNativeSystemInfo(&info);
  62. // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
  63. // but dwAllocationGranularity.
  64. return static_cast<unsigned>(info.dwPageSize);
  65. }
  66. unsigned Process::getPageSize() {
  67. static unsigned Ret = computePageSize();
  68. return Ret;
  69. }
  70. size_t
  71. Process::GetMallocUsage()
  72. {
  73. _HEAPINFO hinfo;
  74. hinfo._pentry = NULL;
  75. size_t size = 0;
  76. while (_heapwalk(&hinfo) == _HEAPOK)
  77. size += hinfo._size;
  78. return size;
  79. }
  80. void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
  81. TimeValue &sys_time) {
  82. elapsed = TimeValue::now();
  83. FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
  84. if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
  85. &UserTime) == 0)
  86. return;
  87. user_time = getTimeValueFromFILETIME(UserTime);
  88. sys_time = getTimeValueFromFILETIME(KernelTime);
  89. }
  90. // Some LLVM programs such as bugpoint produce core files as a normal part of
  91. // their operation. To prevent the disk from filling up, this configuration
  92. // item does what's necessary to prevent their generation.
  93. void Process::PreventCoreFiles() {
  94. // Windows does have the concept of core files, called minidumps. However,
  95. // disabling minidumps for a particular application extends past the lifetime
  96. // of that application, which is the incorrect behavior for this API.
  97. // Additionally, the APIs require elevated privileges to disable and re-
  98. // enable minidumps, which makes this untenable. For more information, see
  99. // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
  100. // later).
  101. //
  102. // Windows also has modal pop-up message boxes. As this method is used by
  103. // bugpoint, preventing these pop-ups is additionally important.
  104. SetErrorMode(SEM_FAILCRITICALERRORS |
  105. SEM_NOGPFAULTERRORBOX |
  106. SEM_NOOPENFILEERRORBOX);
  107. }
  108. /// Returns the environment variable \arg Name's value as a string encoded in
  109. /// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
  110. Optional<std::string> Process::GetEnv(StringRef Name) {
  111. // Convert the argument to UTF-16 to pass it to _wgetenv().
  112. SmallVector<wchar_t, 128> NameUTF16;
  113. if (windows::UTF8ToUTF16(Name, NameUTF16))
  114. return None;
  115. // Environment variable can be encoded in non-UTF8 encoding, and there's no
  116. // way to know what the encoding is. The only reliable way to look up
  117. // multibyte environment variable is to use GetEnvironmentVariableW().
  118. SmallVector<wchar_t, MAX_PATH> Buf;
  119. size_t Size = MAX_PATH;
  120. do {
  121. Buf.reserve(Size);
  122. Size =
  123. GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
  124. if (Size == 0)
  125. return None;
  126. // Try again with larger buffer.
  127. } while (Size > Buf.capacity());
  128. Buf.set_size(Size);
  129. // Convert the result from UTF-16 to UTF-8.
  130. SmallVector<char, MAX_PATH> Res;
  131. if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
  132. return None;
  133. return std::string(Res.data());
  134. }
  135. static void AllocateAndPush(const SmallVectorImpl<char> &S,
  136. SmallVectorImpl<const char *> &Vector,
  137. SpecificBumpPtrAllocator<char> &Allocator) {
  138. char *Buffer = Allocator.Allocate(S.size() + 1);
  139. ::memcpy(Buffer, S.data(), S.size());
  140. Buffer[S.size()] = '\0';
  141. Vector.push_back(Buffer);
  142. }
  143. /// Convert Arg from UTF-16 to UTF-8 and push it onto Args.
  144. static std::error_code
  145. ConvertAndPushArg(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
  146. SpecificBumpPtrAllocator<char> &Allocator) {
  147. SmallVector<char, MAX_PATH> ArgString;
  148. if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), ArgString))
  149. return ec;
  150. AllocateAndPush(ArgString, Args, Allocator);
  151. return std::error_code();
  152. }
  153. /// \brief Perform wildcard expansion of Arg, or just push it into Args if it
  154. /// doesn't have wildcards or doesn't match any files.
  155. static std::error_code
  156. WildcardExpand(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
  157. SpecificBumpPtrAllocator<char> &Allocator) {
  158. if (!wcspbrk(Arg, L"*?")) {
  159. // Arg does not contain any wildcard characters. This is the common case.
  160. return ConvertAndPushArg(Arg, Args, Allocator);
  161. }
  162. if (wcscmp(Arg, L"/?") == 0 || wcscmp(Arg, L"-?") == 0) {
  163. // Don't wildcard expand /?. Always treat it as an option.
  164. return ConvertAndPushArg(Arg, Args, Allocator);
  165. }
  166. // Extract any directory part of the argument.
  167. SmallVector<char, MAX_PATH> Dir;
  168. if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), Dir))
  169. return ec;
  170. sys::path::remove_filename(Dir);
  171. const int DirSize = Dir.size();
  172. // Search for matching files.
  173. WIN32_FIND_DATAW FileData;
  174. HANDLE FindHandle = FindFirstFileW(Arg, &FileData);
  175. if (FindHandle == INVALID_HANDLE_VALUE) {
  176. return ConvertAndPushArg(Arg, Args, Allocator);
  177. }
  178. std::error_code ec;
  179. do {
  180. SmallVector<char, MAX_PATH> FileName;
  181. ec = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
  182. FileName);
  183. if (ec)
  184. break;
  185. // Push the filename onto Dir, and remove it afterwards.
  186. llvm::sys::path::append(Dir, StringRef(FileName.data(), FileName.size()));
  187. AllocateAndPush(Dir, Args, Allocator);
  188. Dir.resize(DirSize);
  189. } while (FindNextFileW(FindHandle, &FileData));
  190. FindClose(FindHandle);
  191. return ec;
  192. }
  193. std::error_code
  194. Process::GetArgumentVector(SmallVectorImpl<const char *> &Args,
  195. ArrayRef<const char *> ArgsIn,
  196. SpecificBumpPtrAllocator<char> &ArgAllocator) {
  197. #if 0 // HLSL Change - use the arguments from the C library and avoid pulling in shell32
  198. int ArgCount;
  199. wchar_t **UnicodeCommandLine =
  200. CommandLineToArgvW(GetCommandLineW(), &ArgCount);
  201. if (!UnicodeCommandLine)
  202. return mapWindowsError(::GetLastError());
  203. Args.reserve(ArgCount);
  204. std::error_code ec;
  205. for (int i = 0; i < ArgCount; ++i) {
  206. ec = WildcardExpand(UnicodeCommandLine[i], Args, ArgAllocator);
  207. if (ec)
  208. break;
  209. }
  210. LocalFree(UnicodeCommandLine);
  211. #else
  212. std::error_code ec;
  213. Args.reserve(ArgsIn.size());
  214. for (size_t i = 0; i < ArgsIn.size(); ++i) {
  215. SmallVector<char, MAX_PATH> NewArgString;
  216. ec = windows::ACPToUTF8(ArgsIn[i], strlen(ArgsIn[i]), NewArgString);
  217. if (ec)
  218. break;
  219. char *Buffer = ArgAllocator.Allocate(NewArgString.size() + 1);
  220. ::memcpy(Buffer, NewArgString.data(), NewArgString.size() + 1);
  221. Args.push_back(Buffer);
  222. }
  223. #endif
  224. return ec;
  225. }
  226. std::error_code Process::FixupStandardFileDescriptors() {
  227. return std::error_code();
  228. }
  229. std::error_code Process::SafelyCloseFileDescriptor(int FD) {
  230. if (llvm::sys::fs::msf_close(FD) < 0) // HLSL Change
  231. return std::error_code(errno, std::generic_category());
  232. return std::error_code();
  233. }
  234. bool Process::StandardInIsUserInput() {
  235. return FileDescriptorIsDisplayed(0);
  236. }
  237. bool Process::StandardOutIsDisplayed() {
  238. return FileDescriptorIsDisplayed(1);
  239. }
  240. bool Process::StandardErrIsDisplayed() {
  241. return FileDescriptorIsDisplayed(2);
  242. }
  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() {
  266. return FileDescriptorHasColors(1);
  267. }
  268. bool Process::StandardErrHasColors() {
  269. return FileDescriptorHasColors(2);
  270. }
  271. static bool UseANSI = false;
  272. void Process::UseANSIEscapeCodes(bool enable) {
  273. UseANSI = enable;
  274. }
  275. namespace {
  276. class DefaultColors
  277. {
  278. private:
  279. WORD defaultColor;
  280. public:
  281. DefaultColors()
  282. :defaultColor(GetCurrentColor()) {}
  283. static unsigned GetCurrentColor() {
  284. CONSOLE_SCREEN_BUFFER_INFO csbi;
  285. if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
  286. return csbi.wAttributes;
  287. return 0;
  288. }
  289. WORD operator()() const { return defaultColor; }
  290. };
  291. // DefaultColors defaultColors; // HLSL Change - remove global initialized at DLL load time
  292. WORD fg_color(WORD color) {
  293. return color & (FOREGROUND_BLUE | FOREGROUND_GREEN |
  294. FOREGROUND_INTENSITY | FOREGROUND_RED);
  295. }
  296. WORD bg_color(WORD color) {
  297. return color & (BACKGROUND_BLUE | BACKGROUND_GREEN |
  298. BACKGROUND_INTENSITY | BACKGROUND_RED);
  299. }
  300. }
  301. bool Process::ColorNeedsFlush() {
  302. #ifdef MSFT_SUPPORTS_ANSI_ESCAPE_CODES
  303. return !UseANSI;
  304. #else
  305. return true;
  306. #endif
  307. }
  308. const char *Process::OutputBold(bool bg) {
  309. #ifdef MSFT_SUPPORTS_ANSI_ESCAPE_CODES
  310. if (UseANSI) return "\033[1m";
  311. #endif
  312. WORD colors = DefaultColors::GetCurrentColor();
  313. if (bg)
  314. colors |= BACKGROUND_INTENSITY;
  315. else
  316. colors |= FOREGROUND_INTENSITY;
  317. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
  318. return 0;
  319. }
  320. const char *Process::OutputColor(char code, bool bold, bool bg) {
  321. #ifdef MSFT_SUPPORTS_ANSI_ESCAPE_CODES
  322. if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
  323. #endif
  324. WORD current = DefaultColors::GetCurrentColor();
  325. WORD colors;
  326. if (bg) {
  327. colors = ((code&1) ? BACKGROUND_RED : 0) |
  328. ((code&2) ? BACKGROUND_GREEN : 0 ) |
  329. ((code&4) ? BACKGROUND_BLUE : 0);
  330. if (bold)
  331. colors |= BACKGROUND_INTENSITY;
  332. colors |= fg_color(current);
  333. } else {
  334. colors = ((code&1) ? FOREGROUND_RED : 0) |
  335. ((code&2) ? FOREGROUND_GREEN : 0 ) |
  336. ((code&4) ? FOREGROUND_BLUE : 0);
  337. if (bold)
  338. colors |= FOREGROUND_INTENSITY;
  339. colors |= bg_color(current);
  340. }
  341. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
  342. return 0;
  343. }
  344. static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
  345. CONSOLE_SCREEN_BUFFER_INFO info;
  346. GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
  347. return info.wAttributes;
  348. }
  349. const char *Process::OutputReverse() {
  350. #ifdef MSFT_SUPPORTS_ANSI_ESCAPE_CODES
  351. if (UseANSI) return "\033[7m";
  352. #endif
  353. const WORD attributes
  354. = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
  355. const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
  356. FOREGROUND_RED | FOREGROUND_INTENSITY;
  357. const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
  358. BACKGROUND_RED | BACKGROUND_INTENSITY;
  359. const WORD color_mask = foreground_mask | background_mask;
  360. WORD new_attributes =
  361. ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
  362. ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
  363. ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
  364. ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
  365. ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
  366. ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
  367. ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
  368. ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
  369. 0;
  370. new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
  371. SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
  372. return 0;
  373. }
  374. const char *Process::ResetColor() {
  375. #ifdef MSFT_SUPPORTS_ANSI_ESCAPE_CODES
  376. if (UseANSI) return "\033[0m";
  377. #endif
  378. ::llvm::sys::fs::GetCurrentThreadFileSystem()->ResetConsoleOutputTextAttributes();
  379. return 0;
  380. }
  381. unsigned Process::GetRandomNumber() {
  382. #if 0 // HLSL Change Starts
  383. HCRYPTPROV HCPC;
  384. if (!::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
  385. CRYPT_VERIFYCONTEXT))
  386. report_fatal_error("Could not acquire a cryptographic context");
  387. ScopedCryptContext CryptoProvider(HCPC);
  388. unsigned Ret;
  389. if (!::CryptGenRandom(CryptoProvider, sizeof(Ret),
  390. reinterpret_cast<BYTE *>(&Ret)))
  391. report_fatal_error("Could not generate a random number");
  392. return Ret;
  393. #else
  394. return rand();
  395. #endif // HLSL Change Ends
  396. }