blob: 3fe9f89f1ef537bbf1c78bd7c495338fe50faeb9 [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;
Chandler Carruth97683aa2012-12-31 11:17:50 +000050
Alp Tokerd71b6df2014-05-19 16:13:28 +000051// This function retrieves the page size using GetNativeSystemInfo() and is
52// present solely so it can be called once to initialize the self_process member
53// below.
Rafael Espindolac0610bf2014-12-04 16:59:36 +000054static unsigned computePageSize() {
Alp Tokerd71b6df2014-05-19 16:13:28 +000055 // GetNativeSystemInfo() provides the physical page size which may differ
56 // from GetSystemInfo() in 32-bit applications running under WOW64.
Reid Spencer91886b72004-09-15 05:47:40 +000057 SYSTEM_INFO info;
Alp Tokerd71b6df2014-05-19 16:13:28 +000058 GetNativeSystemInfo(&info);
NAKAMURA Takumi7a042342013-09-04 14:12:26 +000059 // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
60 // but dwAllocationGranularity.
Reid Spencer91886b72004-09-15 05:47:40 +000061 return static_cast<unsigned>(info.dwPageSize);
62}
63
Rafael Espindolac0610bf2014-12-04 16:59:36 +000064unsigned Process::getPageSize() {
65 static unsigned Ret = computePageSize();
66 return Ret;
Reid Spencer91886b72004-09-15 05:47:40 +000067}
68
Michael J. Spencer447762d2010-11-29 18:16:10 +000069size_t
Reid Spencerac38f3a2004-12-20 00:59:28 +000070Process::GetMallocUsage()
71{
Jeff Cohen7ae0bc72004-12-20 03:24:56 +000072 _HEAPINFO hinfo;
73 hinfo._pentry = NULL;
74
75 size_t size = 0;
76
77 while (_heapwalk(&hinfo) == _HEAPOK)
78 size += hinfo._size;
79
80 return size;
Reid Spencerac38f3a2004-12-20 00:59:28 +000081}
82
Pavel Labath757ca882016-10-24 10:59:17 +000083void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
84 std::chrono::nanoseconds &sys_time) {
85 elapsed = std::chrono::system_clock::now();;
Reid Spencerac38f3a2004-12-20 00:59:28 +000086
Chandler Carruthef7f9682013-01-04 23:19:55 +000087 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
88 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
89 &UserTime) == 0)
90 return;
Reid Spencerac38f3a2004-12-20 00:59:28 +000091
Pavel Labath757ca882016-10-24 10:59:17 +000092 user_time = toDuration(UserTime);
93 sys_time = toDuration(KernelTime);
Reid Spencerac38f3a2004-12-20 00:59:28 +000094}
95
Reid Spencercf15b872004-12-27 06:17:27 +000096// Some LLVM programs such as bugpoint produce core files as a normal part of
Aaron Ballmandcd57572013-08-16 14:33:07 +000097// their operation. To prevent the disk from filling up, this configuration
98// item does what's necessary to prevent their generation.
Reid Spencercf15b872004-12-27 06:17:27 +000099void Process::PreventCoreFiles() {
Aaron Ballmandcd57572013-08-16 14:33:07 +0000100 // Windows does have the concept of core files, called minidumps. However,
101 // disabling minidumps for a particular application extends past the lifetime
102 // of that application, which is the incorrect behavior for this API.
103 // Additionally, the APIs require elevated privileges to disable and re-
104 // enable minidumps, which makes this untenable. For more information, see
105 // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
106 // later).
107 //
108 // Windows also has modal pop-up message boxes. As this method is used by
109 // bugpoint, preventing these pop-ups is additionally important.
Jeff Cohen81549a52005-02-18 07:05:18 +0000110 SetErrorMode(SEM_FAILCRITICALERRORS |
111 SEM_NOGPFAULTERRORBOX |
112 SEM_NOOPENFILEERRORBOX);
Leny Kholodov1b73e662016-05-04 16:56:51 +0000113
114 coreFilesPrevented = true;
Reid Spencercf15b872004-12-27 06:17:27 +0000115}
116
Rui Ueyama471d0c52013-09-10 19:45:51 +0000117/// Returns the environment variable \arg Name's value as a string encoded in
118/// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
119Optional<std::string> Process::GetEnv(StringRef Name) {
120 // Convert the argument to UTF-16 to pass it to _wgetenv().
121 SmallVector<wchar_t, 128> NameUTF16;
Ahmed Charlesce30de92014-03-05 05:04:00 +0000122 if (windows::UTF8ToUTF16(Name, NameUTF16))
Rui Ueyama471d0c52013-09-10 19:45:51 +0000123 return None;
124
125 // Environment variable can be encoded in non-UTF8 encoding, and there's no
126 // way to know what the encoding is. The only reliable way to look up
127 // multibyte environment variable is to use GetEnvironmentVariableW().
David Majnemer61eae2e2013-10-07 01:00:07 +0000128 SmallVector<wchar_t, MAX_PATH> Buf;
129 size_t Size = MAX_PATH;
130 do {
David Majnemerf07777c2013-10-07 21:57:07 +0000131 Buf.reserve(Size);
Ben Dunbobbinac6a5aa2017-08-18 16:55:44 +0000132 SetLastError(NO_ERROR);
David Majnemerf07777c2013-10-07 21:57:07 +0000133 Size =
Ben Dunbobbinac6a5aa2017-08-18 16:55:44 +0000134 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
135 if (Size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
David Majnemer61eae2e2013-10-07 01:00:07 +0000136 return None;
137
Rui Ueyama471d0c52013-09-10 19:45:51 +0000138 // Try again with larger buffer.
David Majnemer61eae2e2013-10-07 01:00:07 +0000139 } while (Size > Buf.capacity());
140 Buf.set_size(Size);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000141
142 // Convert the result from UTF-16 to UTF-8.
David Majnemer61eae2e2013-10-07 01:00:07 +0000143 SmallVector<char, MAX_PATH> Res;
Ahmed Charlesce30de92014-03-05 05:04:00 +0000144 if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
Rui Ueyama471d0c52013-09-10 19:45:51 +0000145 return None;
David Majnemerf07777c2013-10-07 21:57:07 +0000146 return std::string(Res.data());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000147}
148
Hans Wennborg21f0f132014-07-16 00:52:11 +0000149static void AllocateAndPush(const SmallVectorImpl<char> &S,
150 SmallVectorImpl<const char *> &Vector,
151 SpecificBumpPtrAllocator<char> &Allocator) {
152 char *Buffer = Allocator.Allocate(S.size() + 1);
153 ::memcpy(Buffer, S.data(), S.size());
154 Buffer[S.size()] = '\0';
155 Vector.push_back(Buffer);
156}
157
158/// Convert Arg from UTF-16 to UTF-8 and push it onto Args.
159static std::error_code
160ConvertAndPushArg(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
161 SpecificBumpPtrAllocator<char> &Allocator) {
162 SmallVector<char, MAX_PATH> ArgString;
163 if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), ArgString))
164 return ec;
165 AllocateAndPush(ArgString, Args, Allocator);
166 return std::error_code();
167}
168
169/// \brief Perform wildcard expansion of Arg, or just push it into Args if it
170/// doesn't have wildcards or doesn't match any files.
171static std::error_code
172WildcardExpand(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
173 SpecificBumpPtrAllocator<char> &Allocator) {
174 if (!wcspbrk(Arg, L"*?")) {
175 // Arg does not contain any wildcard characters. This is the common case.
176 return ConvertAndPushArg(Arg, Args, Allocator);
177 }
178
Hans Wennborge34a71a2014-07-24 21:09:45 +0000179 if (wcscmp(Arg, L"/?") == 0 || wcscmp(Arg, L"-?") == 0) {
180 // Don't wildcard expand /?. Always treat it as an option.
181 return ConvertAndPushArg(Arg, Args, Allocator);
182 }
183
Hans Wennborg21f0f132014-07-16 00:52:11 +0000184 // Extract any directory part of the argument.
185 SmallVector<char, MAX_PATH> Dir;
186 if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), Dir))
187 return ec;
188 sys::path::remove_filename(Dir);
189 const int DirSize = Dir.size();
190
191 // Search for matching files.
Adrian McCarthyf8331412016-06-20 17:51:27 +0000192 // FIXME: This assumes the wildcard is only in the file name and not in the
193 // directory portion of the file path. For example, it doesn't handle
194 // "*\foo.c" nor "s?c\bar.cpp".
Hans Wennborg21f0f132014-07-16 00:52:11 +0000195 WIN32_FIND_DATAW FileData;
196 HANDLE FindHandle = FindFirstFileW(Arg, &FileData);
197 if (FindHandle == INVALID_HANDLE_VALUE) {
198 return ConvertAndPushArg(Arg, Args, Allocator);
199 }
200
201 std::error_code ec;
202 do {
203 SmallVector<char, MAX_PATH> FileName;
204 ec = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
205 FileName);
206 if (ec)
207 break;
208
Adrian McCarthyf8331412016-06-20 17:51:27 +0000209 // Append FileName to Dir, and remove it afterwards.
Hans Wennborg21f0f132014-07-16 00:52:11 +0000210 llvm::sys::path::append(Dir, StringRef(FileName.data(), FileName.size()));
211 AllocateAndPush(Dir, Args, Allocator);
212 Dir.resize(DirSize);
213 } while (FindNextFileW(FindHandle, &FileData));
214
215 FindClose(FindHandle);
216 return ec;
217}
218
Adrian McCarthyf8331412016-06-20 17:51:27 +0000219static std::error_code
220ExpandShortFileName(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
221 SpecificBumpPtrAllocator<char> &Allocator) {
222 SmallVector<wchar_t, MAX_PATH> LongPath;
223 DWORD Length = GetLongPathNameW(Arg, LongPath.data(), LongPath.capacity());
224 if (Length == 0)
225 return mapWindowsError(GetLastError());
226 if (Length > LongPath.capacity()) {
227 // We're not going to try to deal with paths longer than MAX_PATH, so we'll
228 // treat this as an error. GetLastError() returns ERROR_SUCCESS, which
229 // isn't useful, so we'll hardcode an appropriate error value.
230 return mapWindowsError(ERROR_INSUFFICIENT_BUFFER);
231 }
232 LongPath.set_size(Length);
233 return ConvertAndPushArg(LongPath.data(), Args, Allocator);
234}
235
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000236std::error_code
David Majnemer61eae2e2013-10-07 01:00:07 +0000237Process::GetArgumentVector(SmallVectorImpl<const char *> &Args,
238 ArrayRef<const char *>,
239 SpecificBumpPtrAllocator<char> &ArgAllocator) {
Hans Wennborg21f0f132014-07-16 00:52:11 +0000240 int ArgCount;
241 wchar_t **UnicodeCommandLine =
242 CommandLineToArgvW(GetCommandLineW(), &ArgCount);
David Majnemer61eae2e2013-10-07 01:00:07 +0000243 if (!UnicodeCommandLine)
Yaron Kerenf8e65172015-05-04 04:48:10 +0000244 return mapWindowsError(::GetLastError());
David Majnemer61eae2e2013-10-07 01:00:07 +0000245
Hans Wennborg21f0f132014-07-16 00:52:11 +0000246 Args.reserve(ArgCount);
247 std::error_code ec;
David Majnemer61eae2e2013-10-07 01:00:07 +0000248
Adrian McCarthyf8331412016-06-20 17:51:27 +0000249 // The first argument may contain just the name of the executable (e.g.,
250 // "clang") rather than the full path, so swap it with the full path.
251 wchar_t ModuleName[MAX_PATH];
252 int Length = ::GetModuleFileNameW(NULL, ModuleName, MAX_PATH);
253 if (0 < Length && Length < MAX_PATH)
254 UnicodeCommandLine[0] = ModuleName;
255
256 // If the first argument is a shortened (8.3) name (which is possible even
257 // if we got the module name), the driver will have trouble distinguishing it
258 // (e.g., clang.exe v. clang++.exe), so expand it now.
259 ec = ExpandShortFileName(UnicodeCommandLine[0], Args, ArgAllocator);
260
261 for (int i = 1; i < ArgCount && !ec; ++i) {
Hans Wennborg21f0f132014-07-16 00:52:11 +0000262 ec = WildcardExpand(UnicodeCommandLine[i], Args, ArgAllocator);
David Majnemer61eae2e2013-10-07 01:00:07 +0000263 if (ec)
264 break;
David Majnemer61eae2e2013-10-07 01:00:07 +0000265 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000266
Hans Wennborg21f0f132014-07-16 00:52:11 +0000267 LocalFree(UnicodeCommandLine);
268 return ec;
David Majnemer61eae2e2013-10-07 01:00:07 +0000269}
270
David Majnemer121a1742014-10-06 23:16:18 +0000271std::error_code Process::FixupStandardFileDescriptors() {
272 return std::error_code();
273}
274
David Majnemer51c2afc2014-10-07 05:48:40 +0000275std::error_code Process::SafelyCloseFileDescriptor(int FD) {
276 if (::close(FD) < 0)
277 return std::error_code(errno, std::generic_category());
278 return std::error_code();
279}
280
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000281bool Process::StandardInIsUserInput() {
Dan Gohmane5929232009-09-11 20:46:33 +0000282 return FileDescriptorIsDisplayed(0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000283}
284
285bool Process::StandardOutIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000286 return FileDescriptorIsDisplayed(1);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000287}
288
289bool Process::StandardErrIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000290 return FileDescriptorIsDisplayed(2);
291}
292
293bool Process::FileDescriptorIsDisplayed(int fd) {
Bill Wendling2b079652012-07-19 00:06:06 +0000294 DWORD Mode; // Unused
NAKAMURA Takumi23ebef12010-11-10 08:37:47 +0000295 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000296}
297
Douglas Gregor15436612009-05-11 18:05:52 +0000298unsigned Process::StandardOutColumns() {
299 unsigned Columns = 0;
300 CONSOLE_SCREEN_BUFFER_INFO csbi;
301 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
302 Columns = csbi.dwSize.X;
303 return Columns;
304}
305
306unsigned Process::StandardErrColumns() {
307 unsigned Columns = 0;
308 CONSOLE_SCREEN_BUFFER_INFO csbi;
309 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
310 Columns = csbi.dwSize.X;
311 return Columns;
312}
313
Daniel Dunbar712de822012-07-20 18:29:38 +0000314// The terminal always has colors.
Benjamin Kramerdfaa0f32012-07-20 19:49:33 +0000315bool Process::FileDescriptorHasColors(int fd) {
Daniel Dunbar712de822012-07-20 18:29:38 +0000316 return FileDescriptorIsDisplayed(fd);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000317}
318
319bool Process::StandardOutHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000320 return FileDescriptorHasColors(1);
321}
322
323bool Process::StandardErrHasColors() {
324 return FileDescriptorHasColors(2);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000325}
Torok Edwin63e44bb2009-06-04 08:18:25 +0000326
Nico Rieck92d649a2013-09-11 00:36:48 +0000327static bool UseANSI = false;
328void Process::UseANSIEscapeCodes(bool enable) {
329 UseANSI = enable;
330}
331
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000332namespace {
333class DefaultColors
334{
335 private:
336 WORD defaultColor;
337 public:
338 DefaultColors()
339 :defaultColor(GetCurrentColor()) {}
340 static unsigned GetCurrentColor() {
341 CONSOLE_SCREEN_BUFFER_INFO csbi;
342 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
343 return csbi.wAttributes;
344 return 0;
345 }
346 WORD operator()() const { return defaultColor; }
347};
348
349DefaultColors defaultColors;
Zachary Turner9e1ce992015-02-28 19:08:27 +0000350
351WORD fg_color(WORD color) {
352 return color & (FOREGROUND_BLUE | FOREGROUND_GREEN |
353 FOREGROUND_INTENSITY | FOREGROUND_RED);
354}
355
356WORD bg_color(WORD color) {
357 return color & (BACKGROUND_BLUE | BACKGROUND_GREEN |
358 BACKGROUND_INTENSITY | BACKGROUND_RED);
359}
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000360}
361
362bool Process::ColorNeedsFlush() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000363 return !UseANSI;
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000364}
365
366const char *Process::OutputBold(bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000367 if (UseANSI) return "\033[1m";
368
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000369 WORD colors = DefaultColors::GetCurrentColor();
370 if (bg)
371 colors |= BACKGROUND_INTENSITY;
372 else
373 colors |= FOREGROUND_INTENSITY;
374 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
375 return 0;
376}
377
378const char *Process::OutputColor(char code, bool bold, bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000379 if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
380
Zachary Turner9e1ce992015-02-28 19:08:27 +0000381 WORD current = DefaultColors::GetCurrentColor();
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000382 WORD colors;
383 if (bg) {
384 colors = ((code&1) ? BACKGROUND_RED : 0) |
385 ((code&2) ? BACKGROUND_GREEN : 0 ) |
386 ((code&4) ? BACKGROUND_BLUE : 0);
387 if (bold)
388 colors |= BACKGROUND_INTENSITY;
Zachary Turner9e1ce992015-02-28 19:08:27 +0000389 colors |= fg_color(current);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000390 } else {
391 colors = ((code&1) ? FOREGROUND_RED : 0) |
392 ((code&2) ? FOREGROUND_GREEN : 0 ) |
393 ((code&4) ? FOREGROUND_BLUE : 0);
394 if (bold)
395 colors |= FOREGROUND_INTENSITY;
Zachary Turner9e1ce992015-02-28 19:08:27 +0000396 colors |= bg_color(current);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000397 }
398 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
399 return 0;
400}
401
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000402static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
403 CONSOLE_SCREEN_BUFFER_INFO info;
404 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
405 return info.wAttributes;
406}
407
408const char *Process::OutputReverse() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000409 if (UseANSI) return "\033[7m";
410
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000411 const WORD attributes
412 = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
413
414 const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
415 FOREGROUND_RED | FOREGROUND_INTENSITY;
416 const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
417 BACKGROUND_RED | BACKGROUND_INTENSITY;
418 const WORD color_mask = foreground_mask | background_mask;
419
420 WORD new_attributes =
421 ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
422 ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
423 ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
424 ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
425 ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
426 ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
427 ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
428 ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
429 0;
430 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
431
432 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
433 return 0;
434}
435
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000436const char *Process::ResetColor() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000437 if (UseANSI) return "\033[0m";
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000438 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
439 return 0;
440}
Aaron Ballman78440732014-02-04 14:49:21 +0000441
Paul Robinson8ab79a12015-11-11 20:49:32 +0000442// Include GetLastError() in a fatal error message.
443static void ReportLastErrorFatal(const char *Msg) {
444 std::string ErrMsg;
445 MakeErrMsg(&ErrMsg, Msg);
446 report_fatal_error(ErrMsg);
447}
448
Aaron Ballman78440732014-02-04 14:49:21 +0000449unsigned Process::GetRandomNumber() {
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000450 HCRYPTPROV HCPC;
451 if (!::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
452 CRYPT_VERIFYCONTEXT))
Paul Robinson8ab79a12015-11-11 20:49:32 +0000453 ReportLastErrorFatal("Could not acquire a cryptographic context");
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000454
455 ScopedCryptContext CryptoProvider(HCPC);
456 unsigned Ret;
457 if (!::CryptGenRandom(CryptoProvider, sizeof(Ret),
458 reinterpret_cast<BYTE *>(&Ret)))
Paul Robinson8ab79a12015-11-11 20:49:32 +0000459 ReportLastErrorFatal("Could not generate a random number");
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000460 return Ret;
Aaron Ballman78440732014-02-04 14:49:21 +0000461}