blob: 3aef79fee849c4809077489a791cb2a8d2157c46 [file] [log] [blame]
Reid Spencer91886b72004-09-15 05:47:40 +00001//===- Win32/Process.cpp - Win32 Process Implementation ------- -*- C++ -*-===//
Michael J. Spencer447762d2010-11-29 18:16:10 +00002//
Reid Spencer91886b72004-09-15 05:47:40 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Michael J. Spencer447762d2010-11-29 18:16:10 +00007//
Reid Spencer91886b72004-09-15 05:47:40 +00008//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Process class.
11//
12//===----------------------------------------------------------------------===//
13
David Majnemer61eae2e2013-10-07 01:00:07 +000014#include "llvm/Support/Allocator.h"
Alp Toker552f2f72014-06-03 03:01:03 +000015#include "llvm/Support/ErrorHandling.h"
Rafael Espindola5c4f8292014-06-11 19:05:50 +000016#include "llvm/Support/WindowsError.h"
Chandler Carruth10b09152014-01-07 12:37:13 +000017#include <malloc.h>
18
19// The Windows.h header must be after LLVM and standard headers.
Reid Klecknerd59e2fa2014-02-12 21:26:20 +000020#include "WindowsSupport.h"
Chandler Carruth10b09152014-01-07 12:37:13 +000021
Daniel Dunbar9b92e2b2011-09-23 23:23:36 +000022#include <direct.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000023#include <io.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include <psapi.h>
David Majnemer61eae2e2013-10-07 01:00:07 +000025#include <shellapi.h>
Jeff Cohen7ae0bc72004-12-20 03:24:56 +000026
Reid Spencer187b4ad2006-06-01 19:03:21 +000027#ifdef __MINGW32__
28 #if (HAVE_LIBPSAPI != 1)
29 #error "libpsapi.a should be present"
30 #endif
David Majnemer61eae2e2013-10-07 01:00:07 +000031 #if (HAVE_LIBSHELL32 != 1)
32 #error "libshell32.a should be present"
33 #endif
Reid Spencer187b4ad2006-06-01 19:03:21 +000034#else
David Majnemerf636cf42013-10-06 20:44:34 +000035 #pragma comment(lib, "psapi.lib")
David Majnemer61eae2e2013-10-07 01:00:07 +000036 #pragma comment(lib, "shell32.lib")
Reid Spencer187b4ad2006-06-01 19:03:21 +000037#endif
Reid Spencer91886b72004-09-15 05:47:40 +000038
39//===----------------------------------------------------------------------===//
Michael J. Spencer447762d2010-11-29 18:16:10 +000040//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer91886b72004-09-15 05:47:40 +000041//=== and must not be UNIX code
42//===----------------------------------------------------------------------===//
43
Jeff Cohen07e22ba2005-02-19 03:01:13 +000044#ifdef __MINGW32__
Jeff Cohen53fbecc2004-12-23 03:44:40 +000045// This ban should be lifted when MinGW 1.0+ has defined this value.
46# define _HEAPOK (-2)
47#endif
48
Chandler Carruth5473dfb2012-12-31 11:45:20 +000049using namespace llvm;
Reid Spencer91886b72004-09-15 05:47:40 +000050using namespace sys;
Chandler Carruth97683aa2012-12-31 11:17:50 +000051
Chandler Carruthef7f9682013-01-04 23:19:55 +000052static TimeValue getTimeValueFromFILETIME(FILETIME Time) {
53 ULARGE_INTEGER TimeInteger;
54 TimeInteger.LowPart = Time.dwLowDateTime;
55 TimeInteger.HighPart = Time.dwHighDateTime;
56
57 // FILETIME's are # of 100 nanosecond ticks (1/10th of a microsecond)
58 return TimeValue(
59 static_cast<TimeValue::SecondsType>(TimeInteger.QuadPart / 10000000),
60 static_cast<TimeValue::NanoSecondsType>(
61 (TimeInteger.QuadPart % 10000000) * 100));
62}
63
Alp Tokerd71b6df2014-05-19 16:13:28 +000064// This function retrieves the page size using GetNativeSystemInfo() and is
65// present solely so it can be called once to initialize the self_process member
66// below.
Rafael Espindolac0610bf2014-12-04 16:59:36 +000067static unsigned computePageSize() {
Alp Tokerd71b6df2014-05-19 16:13:28 +000068 // GetNativeSystemInfo() provides the physical page size which may differ
69 // from GetSystemInfo() in 32-bit applications running under WOW64.
Reid Spencer91886b72004-09-15 05:47:40 +000070 SYSTEM_INFO info;
Alp Tokerd71b6df2014-05-19 16:13:28 +000071 GetNativeSystemInfo(&info);
NAKAMURA Takumi7a042342013-09-04 14:12:26 +000072 // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
73 // but dwAllocationGranularity.
Reid Spencer91886b72004-09-15 05:47:40 +000074 return static_cast<unsigned>(info.dwPageSize);
75}
76
Rafael Espindolac0610bf2014-12-04 16:59:36 +000077unsigned Process::getPageSize() {
78 static unsigned Ret = computePageSize();
79 return Ret;
Reid Spencer91886b72004-09-15 05:47:40 +000080}
81
Michael J. Spencer447762d2010-11-29 18:16:10 +000082size_t
Reid Spencerac38f3a2004-12-20 00:59:28 +000083Process::GetMallocUsage()
84{
Jeff Cohen7ae0bc72004-12-20 03:24:56 +000085 _HEAPINFO hinfo;
86 hinfo._pentry = NULL;
87
88 size_t size = 0;
89
90 while (_heapwalk(&hinfo) == _HEAPOK)
91 size += hinfo._size;
92
93 return size;
Reid Spencerac38f3a2004-12-20 00:59:28 +000094}
95
Chandler Carruthef7f9682013-01-04 23:19:55 +000096void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
97 TimeValue &sys_time) {
Reid Spencerac38f3a2004-12-20 00:59:28 +000098 elapsed = TimeValue::now();
99
Chandler Carruthef7f9682013-01-04 23:19:55 +0000100 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
101 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
102 &UserTime) == 0)
103 return;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000104
Chandler Carruthef7f9682013-01-04 23:19:55 +0000105 user_time = getTimeValueFromFILETIME(UserTime);
Chandler Carruthb79a7aa2013-01-04 23:46:04 +0000106 sys_time = getTimeValueFromFILETIME(KernelTime);
Reid Spencerac38f3a2004-12-20 00:59:28 +0000107}
108
Reid Spencercf15b872004-12-27 06:17:27 +0000109// Some LLVM programs such as bugpoint produce core files as a normal part of
Aaron Ballmandcd57572013-08-16 14:33:07 +0000110// their operation. To prevent the disk from filling up, this configuration
111// item does what's necessary to prevent their generation.
Reid Spencercf15b872004-12-27 06:17:27 +0000112void Process::PreventCoreFiles() {
Aaron Ballmandcd57572013-08-16 14:33:07 +0000113 // Windows does have the concept of core files, called minidumps. However,
114 // disabling minidumps for a particular application extends past the lifetime
115 // of that application, which is the incorrect behavior for this API.
116 // Additionally, the APIs require elevated privileges to disable and re-
117 // enable minidumps, which makes this untenable. For more information, see
118 // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
119 // later).
120 //
121 // Windows also has modal pop-up message boxes. As this method is used by
122 // bugpoint, preventing these pop-ups is additionally important.
Jeff Cohen81549a52005-02-18 07:05:18 +0000123 SetErrorMode(SEM_FAILCRITICALERRORS |
124 SEM_NOGPFAULTERRORBOX |
125 SEM_NOOPENFILEERRORBOX);
Leny Kholodov1b73e662016-05-04 16:56:51 +0000126
127 coreFilesPrevented = true;
Reid Spencercf15b872004-12-27 06:17:27 +0000128}
129
Rui Ueyama471d0c52013-09-10 19:45:51 +0000130/// Returns the environment variable \arg Name's value as a string encoded in
131/// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
132Optional<std::string> Process::GetEnv(StringRef Name) {
133 // Convert the argument to UTF-16 to pass it to _wgetenv().
134 SmallVector<wchar_t, 128> NameUTF16;
Ahmed Charlesce30de92014-03-05 05:04:00 +0000135 if (windows::UTF8ToUTF16(Name, NameUTF16))
Rui Ueyama471d0c52013-09-10 19:45:51 +0000136 return None;
137
138 // Environment variable can be encoded in non-UTF8 encoding, and there's no
139 // way to know what the encoding is. The only reliable way to look up
140 // multibyte environment variable is to use GetEnvironmentVariableW().
David Majnemer61eae2e2013-10-07 01:00:07 +0000141 SmallVector<wchar_t, MAX_PATH> Buf;
142 size_t Size = MAX_PATH;
143 do {
David Majnemerf07777c2013-10-07 21:57:07 +0000144 Buf.reserve(Size);
145 Size =
146 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
David Majnemer61eae2e2013-10-07 01:00:07 +0000147 if (Size == 0)
148 return None;
149
Rui Ueyama471d0c52013-09-10 19:45:51 +0000150 // Try again with larger buffer.
David Majnemer61eae2e2013-10-07 01:00:07 +0000151 } while (Size > Buf.capacity());
152 Buf.set_size(Size);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000153
154 // Convert the result from UTF-16 to UTF-8.
David Majnemer61eae2e2013-10-07 01:00:07 +0000155 SmallVector<char, MAX_PATH> Res;
Ahmed Charlesce30de92014-03-05 05:04:00 +0000156 if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
Rui Ueyama471d0c52013-09-10 19:45:51 +0000157 return None;
David Majnemerf07777c2013-10-07 21:57:07 +0000158 return std::string(Res.data());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000159}
160
Hans Wennborg21f0f132014-07-16 00:52:11 +0000161static void AllocateAndPush(const SmallVectorImpl<char> &S,
162 SmallVectorImpl<const char *> &Vector,
163 SpecificBumpPtrAllocator<char> &Allocator) {
164 char *Buffer = Allocator.Allocate(S.size() + 1);
165 ::memcpy(Buffer, S.data(), S.size());
166 Buffer[S.size()] = '\0';
167 Vector.push_back(Buffer);
168}
169
170/// Convert Arg from UTF-16 to UTF-8 and push it onto Args.
171static std::error_code
172ConvertAndPushArg(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
173 SpecificBumpPtrAllocator<char> &Allocator) {
174 SmallVector<char, MAX_PATH> ArgString;
175 if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), ArgString))
176 return ec;
177 AllocateAndPush(ArgString, Args, Allocator);
178 return std::error_code();
179}
180
181/// \brief Perform wildcard expansion of Arg, or just push it into Args if it
182/// doesn't have wildcards or doesn't match any files.
183static std::error_code
184WildcardExpand(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
185 SpecificBumpPtrAllocator<char> &Allocator) {
186 if (!wcspbrk(Arg, L"*?")) {
187 // Arg does not contain any wildcard characters. This is the common case.
188 return ConvertAndPushArg(Arg, Args, Allocator);
189 }
190
Hans Wennborge34a71a2014-07-24 21:09:45 +0000191 if (wcscmp(Arg, L"/?") == 0 || wcscmp(Arg, L"-?") == 0) {
192 // Don't wildcard expand /?. Always treat it as an option.
193 return ConvertAndPushArg(Arg, Args, Allocator);
194 }
195
Hans Wennborg21f0f132014-07-16 00:52:11 +0000196 // Extract any directory part of the argument.
197 SmallVector<char, MAX_PATH> Dir;
198 if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), Dir))
199 return ec;
200 sys::path::remove_filename(Dir);
201 const int DirSize = Dir.size();
202
203 // Search for matching files.
204 WIN32_FIND_DATAW FileData;
205 HANDLE FindHandle = FindFirstFileW(Arg, &FileData);
206 if (FindHandle == INVALID_HANDLE_VALUE) {
207 return ConvertAndPushArg(Arg, Args, Allocator);
208 }
209
210 std::error_code ec;
211 do {
212 SmallVector<char, MAX_PATH> FileName;
213 ec = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
214 FileName);
215 if (ec)
216 break;
217
Adrian McCarthy7a581352016-06-17 19:45:59 +0000218 // Push the filename onto Dir, and remove it afterwards.
Hans Wennborg21f0f132014-07-16 00:52:11 +0000219 llvm::sys::path::append(Dir, StringRef(FileName.data(), FileName.size()));
220 AllocateAndPush(Dir, Args, Allocator);
221 Dir.resize(DirSize);
222 } while (FindNextFileW(FindHandle, &FileData));
223
224 FindClose(FindHandle);
225 return ec;
226}
227
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000228std::error_code
David Majnemer61eae2e2013-10-07 01:00:07 +0000229Process::GetArgumentVector(SmallVectorImpl<const char *> &Args,
230 ArrayRef<const char *>,
231 SpecificBumpPtrAllocator<char> &ArgAllocator) {
Hans Wennborg21f0f132014-07-16 00:52:11 +0000232 int ArgCount;
233 wchar_t **UnicodeCommandLine =
234 CommandLineToArgvW(GetCommandLineW(), &ArgCount);
David Majnemer61eae2e2013-10-07 01:00:07 +0000235 if (!UnicodeCommandLine)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000236 return mapWindowsError(::GetLastError());
David Majnemer61eae2e2013-10-07 01:00:07 +0000237
Hans Wennborg21f0f132014-07-16 00:52:11 +0000238 Args.reserve(ArgCount);
239 std::error_code ec;
David Majnemer61eae2e2013-10-07 01:00:07 +0000240
Adrian McCarthy7a581352016-06-17 19:45:59 +0000241 for (int i = 0; i < ArgCount; ++i) {
Hans Wennborg21f0f132014-07-16 00:52:11 +0000242 ec = WildcardExpand(UnicodeCommandLine[i], Args, ArgAllocator);
David Majnemer61eae2e2013-10-07 01:00:07 +0000243 if (ec)
244 break;
David Majnemer61eae2e2013-10-07 01:00:07 +0000245 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000246
Hans Wennborg21f0f132014-07-16 00:52:11 +0000247 LocalFree(UnicodeCommandLine);
248 return ec;
David Majnemer61eae2e2013-10-07 01:00:07 +0000249}
250
David Majnemer121a1742014-10-06 23:16:18 +0000251std::error_code Process::FixupStandardFileDescriptors() {
252 return std::error_code();
253}
254
David Majnemer51c2afc2014-10-07 05:48:40 +0000255std::error_code Process::SafelyCloseFileDescriptor(int FD) {
256 if (::close(FD) < 0)
257 return std::error_code(errno, std::generic_category());
258 return std::error_code();
259}
260
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000261bool Process::StandardInIsUserInput() {
Dan Gohmane5929232009-09-11 20:46:33 +0000262 return FileDescriptorIsDisplayed(0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000263}
264
265bool Process::StandardOutIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000266 return FileDescriptorIsDisplayed(1);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000267}
268
269bool Process::StandardErrIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000270 return FileDescriptorIsDisplayed(2);
271}
272
273bool Process::FileDescriptorIsDisplayed(int fd) {
Bill Wendling2b079652012-07-19 00:06:06 +0000274 DWORD Mode; // Unused
NAKAMURA Takumi23ebef12010-11-10 08:37:47 +0000275 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000276}
277
Douglas Gregor15436612009-05-11 18:05:52 +0000278unsigned Process::StandardOutColumns() {
279 unsigned Columns = 0;
280 CONSOLE_SCREEN_BUFFER_INFO csbi;
281 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
282 Columns = csbi.dwSize.X;
283 return Columns;
284}
285
286unsigned Process::StandardErrColumns() {
287 unsigned Columns = 0;
288 CONSOLE_SCREEN_BUFFER_INFO csbi;
289 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
290 Columns = csbi.dwSize.X;
291 return Columns;
292}
293
Daniel Dunbar712de822012-07-20 18:29:38 +0000294// The terminal always has colors.
Benjamin Kramerdfaa0f32012-07-20 19:49:33 +0000295bool Process::FileDescriptorHasColors(int fd) {
Daniel Dunbar712de822012-07-20 18:29:38 +0000296 return FileDescriptorIsDisplayed(fd);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000297}
298
299bool Process::StandardOutHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000300 return FileDescriptorHasColors(1);
301}
302
303bool Process::StandardErrHasColors() {
304 return FileDescriptorHasColors(2);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000305}
Torok Edwin63e44bb2009-06-04 08:18:25 +0000306
Nico Rieck92d649a2013-09-11 00:36:48 +0000307static bool UseANSI = false;
308void Process::UseANSIEscapeCodes(bool enable) {
309 UseANSI = enable;
310}
311
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000312namespace {
313class DefaultColors
314{
315 private:
316 WORD defaultColor;
317 public:
318 DefaultColors()
319 :defaultColor(GetCurrentColor()) {}
320 static unsigned GetCurrentColor() {
321 CONSOLE_SCREEN_BUFFER_INFO csbi;
322 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
323 return csbi.wAttributes;
324 return 0;
325 }
326 WORD operator()() const { return defaultColor; }
327};
328
329DefaultColors defaultColors;
Zachary Turner9e1ce992015-02-28 19:08:27 +0000330
331WORD fg_color(WORD color) {
332 return color & (FOREGROUND_BLUE | FOREGROUND_GREEN |
333 FOREGROUND_INTENSITY | FOREGROUND_RED);
334}
335
336WORD bg_color(WORD color) {
337 return color & (BACKGROUND_BLUE | BACKGROUND_GREEN |
338 BACKGROUND_INTENSITY | BACKGROUND_RED);
339}
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000340}
341
342bool Process::ColorNeedsFlush() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000343 return !UseANSI;
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000344}
345
346const char *Process::OutputBold(bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000347 if (UseANSI) return "\033[1m";
348
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000349 WORD colors = DefaultColors::GetCurrentColor();
350 if (bg)
351 colors |= BACKGROUND_INTENSITY;
352 else
353 colors |= FOREGROUND_INTENSITY;
354 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
355 return 0;
356}
357
358const char *Process::OutputColor(char code, bool bold, bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000359 if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
360
Zachary Turner9e1ce992015-02-28 19:08:27 +0000361 WORD current = DefaultColors::GetCurrentColor();
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000362 WORD colors;
363 if (bg) {
364 colors = ((code&1) ? BACKGROUND_RED : 0) |
365 ((code&2) ? BACKGROUND_GREEN : 0 ) |
366 ((code&4) ? BACKGROUND_BLUE : 0);
367 if (bold)
368 colors |= BACKGROUND_INTENSITY;
Zachary Turner9e1ce992015-02-28 19:08:27 +0000369 colors |= fg_color(current);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000370 } else {
371 colors = ((code&1) ? FOREGROUND_RED : 0) |
372 ((code&2) ? FOREGROUND_GREEN : 0 ) |
373 ((code&4) ? FOREGROUND_BLUE : 0);
374 if (bold)
375 colors |= FOREGROUND_INTENSITY;
Zachary Turner9e1ce992015-02-28 19:08:27 +0000376 colors |= bg_color(current);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000377 }
378 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
379 return 0;
380}
381
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000382static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
383 CONSOLE_SCREEN_BUFFER_INFO info;
384 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
385 return info.wAttributes;
386}
387
388const char *Process::OutputReverse() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000389 if (UseANSI) return "\033[7m";
390
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000391 const WORD attributes
392 = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
393
394 const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
395 FOREGROUND_RED | FOREGROUND_INTENSITY;
396 const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
397 BACKGROUND_RED | BACKGROUND_INTENSITY;
398 const WORD color_mask = foreground_mask | background_mask;
399
400 WORD new_attributes =
401 ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
402 ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
403 ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
404 ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
405 ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
406 ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
407 ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
408 ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
409 0;
410 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
411
412 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
413 return 0;
414}
415
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000416const char *Process::ResetColor() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000417 if (UseANSI) return "\033[0m";
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000418 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
419 return 0;
420}
Aaron Ballman78440732014-02-04 14:49:21 +0000421
Paul Robinson8ab79a12015-11-11 20:49:32 +0000422// Include GetLastError() in a fatal error message.
423static void ReportLastErrorFatal(const char *Msg) {
424 std::string ErrMsg;
425 MakeErrMsg(&ErrMsg, Msg);
426 report_fatal_error(ErrMsg);
427}
428
Aaron Ballman78440732014-02-04 14:49:21 +0000429unsigned Process::GetRandomNumber() {
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000430 HCRYPTPROV HCPC;
431 if (!::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
432 CRYPT_VERIFYCONTEXT))
Paul Robinson8ab79a12015-11-11 20:49:32 +0000433 ReportLastErrorFatal("Could not acquire a cryptographic context");
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000434
435 ScopedCryptContext CryptoProvider(HCPC);
436 unsigned Ret;
437 if (!::CryptGenRandom(CryptoProvider, sizeof(Ret),
438 reinterpret_cast<BYTE *>(&Ret)))
Paul Robinson8ab79a12015-11-11 20:49:32 +0000439 ReportLastErrorFatal("Could not generate a random number");
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000440 return Ret;
Aaron Ballman78440732014-02-04 14:49:21 +0000441}