blob: b1dbc5e3b0e916da34606f6f9d22b8d68e71b0ba [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"
Zachary Turnerb44d7a02018-06-01 22:23:46 +000015#include "llvm/Support/ConvertUTF.h"
Alp Toker552f2f72014-06-03 03:01:03 +000016#include "llvm/Support/ErrorHandling.h"
Rafael Espindola5c4f8292014-06-11 19:05:50 +000017#include "llvm/Support/WindowsError.h"
Chandler Carruth10b09152014-01-07 12:37:13 +000018#include <malloc.h>
19
20// The Windows.h header must be after LLVM and standard headers.
Reid Klecknerd59e2fa2014-02-12 21:26:20 +000021#include "WindowsSupport.h"
Chandler Carruth10b09152014-01-07 12:37:13 +000022
Daniel Dunbar9b92e2b2011-09-23 23:23:36 +000023#include <direct.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include <io.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include <psapi.h>
David Majnemer61eae2e2013-10-07 01:00:07 +000026#include <shellapi.h>
Jeff Cohen7ae0bc72004-12-20 03:24:56 +000027
Nico Weber86811212018-04-02 17:32:48 +000028#if !defined(__MINGW32__)
David Majnemerf636cf42013-10-06 20:44:34 +000029 #pragma comment(lib, "psapi.lib")
David Majnemer61eae2e2013-10-07 01:00:07 +000030 #pragma comment(lib, "shell32.lib")
Reid Spencer187b4ad2006-06-01 19:03:21 +000031#endif
Reid Spencer91886b72004-09-15 05:47:40 +000032
33//===----------------------------------------------------------------------===//
Michael J. Spencer447762d2010-11-29 18:16:10 +000034//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer91886b72004-09-15 05:47:40 +000035//=== and must not be UNIX code
36//===----------------------------------------------------------------------===//
37
Jeff Cohen07e22ba2005-02-19 03:01:13 +000038#ifdef __MINGW32__
Jeff Cohen53fbecc2004-12-23 03:44:40 +000039// This ban should be lifted when MinGW 1.0+ has defined this value.
40# define _HEAPOK (-2)
41#endif
42
Chandler Carruth5473dfb2012-12-31 11:45:20 +000043using namespace llvm;
Chandler Carruth97683aa2012-12-31 11:17:50 +000044
Alp Tokerd71b6df2014-05-19 16:13:28 +000045// This function retrieves the page size using GetNativeSystemInfo() and is
46// present solely so it can be called once to initialize the self_process member
47// below.
Rafael Espindolac0610bf2014-12-04 16:59:36 +000048static unsigned computePageSize() {
Alp Tokerd71b6df2014-05-19 16:13:28 +000049 // GetNativeSystemInfo() provides the physical page size which may differ
50 // from GetSystemInfo() in 32-bit applications running under WOW64.
Reid Spencer91886b72004-09-15 05:47:40 +000051 SYSTEM_INFO info;
Alp Tokerd71b6df2014-05-19 16:13:28 +000052 GetNativeSystemInfo(&info);
NAKAMURA Takumi7a042342013-09-04 14:12:26 +000053 // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
54 // but dwAllocationGranularity.
Reid Spencer91886b72004-09-15 05:47:40 +000055 return static_cast<unsigned>(info.dwPageSize);
56}
57
Rafael Espindolac0610bf2014-12-04 16:59:36 +000058unsigned Process::getPageSize() {
59 static unsigned Ret = computePageSize();
60 return Ret;
Reid Spencer91886b72004-09-15 05:47:40 +000061}
62
Michael J. Spencer447762d2010-11-29 18:16:10 +000063size_t
Reid Spencerac38f3a2004-12-20 00:59:28 +000064Process::GetMallocUsage()
65{
Jeff Cohen7ae0bc72004-12-20 03:24:56 +000066 _HEAPINFO hinfo;
67 hinfo._pentry = NULL;
68
69 size_t size = 0;
70
71 while (_heapwalk(&hinfo) == _HEAPOK)
72 size += hinfo._size;
73
74 return size;
Reid Spencerac38f3a2004-12-20 00:59:28 +000075}
76
Pavel Labath757ca882016-10-24 10:59:17 +000077void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
78 std::chrono::nanoseconds &sys_time) {
79 elapsed = std::chrono::system_clock::now();;
Reid Spencerac38f3a2004-12-20 00:59:28 +000080
Chandler Carruthef7f9682013-01-04 23:19:55 +000081 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
82 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
83 &UserTime) == 0)
84 return;
Reid Spencerac38f3a2004-12-20 00:59:28 +000085
Pavel Labath757ca882016-10-24 10:59:17 +000086 user_time = toDuration(UserTime);
87 sys_time = toDuration(KernelTime);
Reid Spencerac38f3a2004-12-20 00:59:28 +000088}
89
Reid Spencercf15b872004-12-27 06:17:27 +000090// Some LLVM programs such as bugpoint produce core files as a normal part of
Aaron Ballmandcd57572013-08-16 14:33:07 +000091// their operation. To prevent the disk from filling up, this configuration
92// item does what's necessary to prevent their generation.
Reid Spencercf15b872004-12-27 06:17:27 +000093void Process::PreventCoreFiles() {
Aaron Ballmandcd57572013-08-16 14:33:07 +000094 // 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.
Jeff Cohen81549a52005-02-18 07:05:18 +0000104 SetErrorMode(SEM_FAILCRITICALERRORS |
105 SEM_NOGPFAULTERRORBOX |
106 SEM_NOOPENFILEERRORBOX);
Leny Kholodov1b73e662016-05-04 16:56:51 +0000107
108 coreFilesPrevented = true;
Reid Spencercf15b872004-12-27 06:17:27 +0000109}
110
Rui Ueyama471d0c52013-09-10 19:45:51 +0000111/// Returns the environment variable \arg Name's value as a string encoded in
112/// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
113Optional<std::string> Process::GetEnv(StringRef Name) {
114 // Convert the argument to UTF-16 to pass it to _wgetenv().
115 SmallVector<wchar_t, 128> NameUTF16;
Ahmed Charlesce30de92014-03-05 05:04:00 +0000116 if (windows::UTF8ToUTF16(Name, NameUTF16))
Rui Ueyama471d0c52013-09-10 19:45:51 +0000117 return None;
118
119 // Environment variable can be encoded in non-UTF8 encoding, and there's no
120 // way to know what the encoding is. The only reliable way to look up
121 // multibyte environment variable is to use GetEnvironmentVariableW().
David Majnemer61eae2e2013-10-07 01:00:07 +0000122 SmallVector<wchar_t, MAX_PATH> Buf;
123 size_t Size = MAX_PATH;
124 do {
David Majnemerf07777c2013-10-07 21:57:07 +0000125 Buf.reserve(Size);
Ben Dunbobbinac6a5aa2017-08-18 16:55:44 +0000126 SetLastError(NO_ERROR);
David Majnemerf07777c2013-10-07 21:57:07 +0000127 Size =
Ben Dunbobbinac6a5aa2017-08-18 16:55:44 +0000128 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
129 if (Size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
David Majnemer61eae2e2013-10-07 01:00:07 +0000130 return None;
131
Rui Ueyama471d0c52013-09-10 19:45:51 +0000132 // Try again with larger buffer.
David Majnemer61eae2e2013-10-07 01:00:07 +0000133 } while (Size > Buf.capacity());
134 Buf.set_size(Size);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000135
136 // Convert the result from UTF-16 to UTF-8.
David Majnemer61eae2e2013-10-07 01:00:07 +0000137 SmallVector<char, MAX_PATH> Res;
Ahmed Charlesce30de92014-03-05 05:04:00 +0000138 if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
Rui Ueyama471d0c52013-09-10 19:45:51 +0000139 return None;
David Majnemerf07777c2013-10-07 21:57:07 +0000140 return std::string(Res.data());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000141}
142
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000143static const char *AllocateString(const SmallVectorImpl<char> &S,
144 BumpPtrAllocator &Alloc) {
145 char *Buf = reinterpret_cast<char *>(Alloc.Allocate(S.size() + 1, 1));
146 ::memcpy(Buf, S.data(), S.size());
147 Buf[S.size()] = '\0';
148 return Buf;
Hans Wennborg21f0f132014-07-16 00:52:11 +0000149}
150
151/// Convert Arg from UTF-16 to UTF-8 and push it onto Args.
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000152static std::error_code ConvertAndPushArg(const wchar_t *Arg,
153 SmallVectorImpl<const char *> &Args,
154 BumpPtrAllocator &Alloc) {
Hans Wennborg21f0f132014-07-16 00:52:11 +0000155 SmallVector<char, MAX_PATH> ArgString;
156 if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), ArgString))
157 return ec;
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000158 Args.push_back(AllocateString(ArgString, Alloc));
Hans Wennborg21f0f132014-07-16 00:52:11 +0000159 return std::error_code();
160}
161
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000162/// Perform wildcard expansion of Arg, or just push it into Args if it
Hans Wennborg21f0f132014-07-16 00:52:11 +0000163/// doesn't have wildcards or doesn't match any files.
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000164static std::error_code WildcardExpand(const wchar_t *Arg,
165 SmallVectorImpl<const char *> &Args,
166 BumpPtrAllocator &Alloc) {
Hans Wennborg21f0f132014-07-16 00:52:11 +0000167 if (!wcspbrk(Arg, L"*?")) {
168 // Arg does not contain any wildcard characters. This is the common case.
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000169 return ConvertAndPushArg(Arg, Args, Alloc);
Hans Wennborg21f0f132014-07-16 00:52:11 +0000170 }
171
Hans Wennborge34a71a2014-07-24 21:09:45 +0000172 if (wcscmp(Arg, L"/?") == 0 || wcscmp(Arg, L"-?") == 0) {
173 // Don't wildcard expand /?. Always treat it as an option.
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000174 return ConvertAndPushArg(Arg, Args, Alloc);
Hans Wennborge34a71a2014-07-24 21:09:45 +0000175 }
176
Hans Wennborg21f0f132014-07-16 00:52:11 +0000177 // Extract any directory part of the argument.
178 SmallVector<char, MAX_PATH> Dir;
179 if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), Dir))
180 return ec;
181 sys::path::remove_filename(Dir);
182 const int DirSize = Dir.size();
183
184 // Search for matching files.
Adrian McCarthyf8331412016-06-20 17:51:27 +0000185 // FIXME: This assumes the wildcard is only in the file name and not in the
186 // directory portion of the file path. For example, it doesn't handle
187 // "*\foo.c" nor "s?c\bar.cpp".
Hans Wennborg21f0f132014-07-16 00:52:11 +0000188 WIN32_FIND_DATAW FileData;
189 HANDLE FindHandle = FindFirstFileW(Arg, &FileData);
190 if (FindHandle == INVALID_HANDLE_VALUE) {
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000191 return ConvertAndPushArg(Arg, Args, Alloc);
Hans Wennborg21f0f132014-07-16 00:52:11 +0000192 }
193
194 std::error_code ec;
195 do {
196 SmallVector<char, MAX_PATH> FileName;
197 ec = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
198 FileName);
199 if (ec)
200 break;
201
Adrian McCarthyf8331412016-06-20 17:51:27 +0000202 // Append FileName to Dir, and remove it afterwards.
Hans Wennborg21f0f132014-07-16 00:52:11 +0000203 llvm::sys::path::append(Dir, StringRef(FileName.data(), FileName.size()));
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000204 Args.push_back(AllocateString(Dir, Alloc));
Hans Wennborg21f0f132014-07-16 00:52:11 +0000205 Dir.resize(DirSize);
206 } while (FindNextFileW(FindHandle, &FileData));
207
208 FindClose(FindHandle);
209 return ec;
210}
211
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000212static std::error_code ExpandShortFileName(const wchar_t *Arg,
213 SmallVectorImpl<const char *> &Args,
214 BumpPtrAllocator &Alloc) {
Adrian McCarthyf8331412016-06-20 17:51:27 +0000215 SmallVector<wchar_t, MAX_PATH> LongPath;
216 DWORD Length = GetLongPathNameW(Arg, LongPath.data(), LongPath.capacity());
217 if (Length == 0)
218 return mapWindowsError(GetLastError());
219 if (Length > LongPath.capacity()) {
220 // We're not going to try to deal with paths longer than MAX_PATH, so we'll
221 // treat this as an error. GetLastError() returns ERROR_SUCCESS, which
222 // isn't useful, so we'll hardcode an appropriate error value.
223 return mapWindowsError(ERROR_INSUFFICIENT_BUFFER);
224 }
225 LongPath.set_size(Length);
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000226 return ConvertAndPushArg(LongPath.data(), Args, Alloc);
Adrian McCarthyf8331412016-06-20 17:51:27 +0000227}
228
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000229std::error_code
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000230windows::GetCommandLineArguments(SmallVectorImpl<const char *> &Args,
231 BumpPtrAllocator &Alloc) {
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 McCarthyf8331412016-06-20 17:51:27 +0000241 // The first argument may contain just the name of the executable (e.g.,
242 // "clang") rather than the full path, so swap it with the full path.
243 wchar_t ModuleName[MAX_PATH];
244 int Length = ::GetModuleFileNameW(NULL, ModuleName, MAX_PATH);
245 if (0 < Length && Length < MAX_PATH)
246 UnicodeCommandLine[0] = ModuleName;
247
248 // If the first argument is a shortened (8.3) name (which is possible even
249 // if we got the module name), the driver will have trouble distinguishing it
250 // (e.g., clang.exe v. clang++.exe), so expand it now.
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000251 ec = ExpandShortFileName(UnicodeCommandLine[0], Args, Alloc);
Adrian McCarthyf8331412016-06-20 17:51:27 +0000252
253 for (int i = 1; i < ArgCount && !ec; ++i) {
Rui Ueyamae6ac9f52018-04-17 21:09:16 +0000254 ec = WildcardExpand(UnicodeCommandLine[i], Args, Alloc);
David Majnemer61eae2e2013-10-07 01:00:07 +0000255 if (ec)
256 break;
David Majnemer61eae2e2013-10-07 01:00:07 +0000257 }
David Majnemer61eae2e2013-10-07 01:00:07 +0000258
Hans Wennborg21f0f132014-07-16 00:52:11 +0000259 LocalFree(UnicodeCommandLine);
260 return ec;
David Majnemer61eae2e2013-10-07 01:00:07 +0000261}
262
David Majnemer121a1742014-10-06 23:16:18 +0000263std::error_code Process::FixupStandardFileDescriptors() {
264 return std::error_code();
265}
266
David Majnemer51c2afc2014-10-07 05:48:40 +0000267std::error_code Process::SafelyCloseFileDescriptor(int FD) {
268 if (::close(FD) < 0)
269 return std::error_code(errno, std::generic_category());
270 return std::error_code();
271}
272
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000273bool Process::StandardInIsUserInput() {
Dan Gohmane5929232009-09-11 20:46:33 +0000274 return FileDescriptorIsDisplayed(0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000275}
276
277bool Process::StandardOutIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000278 return FileDescriptorIsDisplayed(1);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000279}
280
281bool Process::StandardErrIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000282 return FileDescriptorIsDisplayed(2);
283}
284
285bool Process::FileDescriptorIsDisplayed(int fd) {
Bill Wendling2b079652012-07-19 00:06:06 +0000286 DWORD Mode; // Unused
NAKAMURA Takumi23ebef12010-11-10 08:37:47 +0000287 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000288}
289
Douglas Gregor15436612009-05-11 18:05:52 +0000290unsigned Process::StandardOutColumns() {
291 unsigned Columns = 0;
292 CONSOLE_SCREEN_BUFFER_INFO csbi;
293 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
294 Columns = csbi.dwSize.X;
295 return Columns;
296}
297
298unsigned Process::StandardErrColumns() {
299 unsigned Columns = 0;
300 CONSOLE_SCREEN_BUFFER_INFO csbi;
301 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
302 Columns = csbi.dwSize.X;
303 return Columns;
304}
305
Daniel Dunbar712de822012-07-20 18:29:38 +0000306// The terminal always has colors.
Benjamin Kramerdfaa0f32012-07-20 19:49:33 +0000307bool Process::FileDescriptorHasColors(int fd) {
Daniel Dunbar712de822012-07-20 18:29:38 +0000308 return FileDescriptorIsDisplayed(fd);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000309}
310
311bool Process::StandardOutHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000312 return FileDescriptorHasColors(1);
313}
314
315bool Process::StandardErrHasColors() {
316 return FileDescriptorHasColors(2);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000317}
Torok Edwin63e44bb2009-06-04 08:18:25 +0000318
Nico Rieck92d649a2013-09-11 00:36:48 +0000319static bool UseANSI = false;
320void Process::UseANSIEscapeCodes(bool enable) {
321 UseANSI = enable;
322}
323
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000324namespace {
325class DefaultColors
326{
327 private:
328 WORD defaultColor;
329 public:
330 DefaultColors()
331 :defaultColor(GetCurrentColor()) {}
332 static unsigned GetCurrentColor() {
333 CONSOLE_SCREEN_BUFFER_INFO csbi;
334 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
335 return csbi.wAttributes;
336 return 0;
337 }
338 WORD operator()() const { return defaultColor; }
339};
340
341DefaultColors defaultColors;
Zachary Turner9e1ce992015-02-28 19:08:27 +0000342
343WORD fg_color(WORD color) {
344 return color & (FOREGROUND_BLUE | FOREGROUND_GREEN |
345 FOREGROUND_INTENSITY | FOREGROUND_RED);
346}
347
348WORD bg_color(WORD color) {
349 return color & (BACKGROUND_BLUE | BACKGROUND_GREEN |
350 BACKGROUND_INTENSITY | BACKGROUND_RED);
351}
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000352}
353
354bool Process::ColorNeedsFlush() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000355 return !UseANSI;
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000356}
357
358const char *Process::OutputBold(bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000359 if (UseANSI) return "\033[1m";
360
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000361 WORD colors = DefaultColors::GetCurrentColor();
362 if (bg)
363 colors |= BACKGROUND_INTENSITY;
364 else
365 colors |= FOREGROUND_INTENSITY;
366 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
367 return 0;
368}
369
370const char *Process::OutputColor(char code, bool bold, bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000371 if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
372
Zachary Turner9e1ce992015-02-28 19:08:27 +0000373 WORD current = DefaultColors::GetCurrentColor();
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000374 WORD colors;
375 if (bg) {
376 colors = ((code&1) ? BACKGROUND_RED : 0) |
377 ((code&2) ? BACKGROUND_GREEN : 0 ) |
378 ((code&4) ? BACKGROUND_BLUE : 0);
379 if (bold)
380 colors |= BACKGROUND_INTENSITY;
Zachary Turner9e1ce992015-02-28 19:08:27 +0000381 colors |= fg_color(current);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000382 } else {
383 colors = ((code&1) ? FOREGROUND_RED : 0) |
384 ((code&2) ? FOREGROUND_GREEN : 0 ) |
385 ((code&4) ? FOREGROUND_BLUE : 0);
386 if (bold)
387 colors |= FOREGROUND_INTENSITY;
Zachary Turner9e1ce992015-02-28 19:08:27 +0000388 colors |= bg_color(current);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000389 }
390 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
391 return 0;
392}
393
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000394static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
395 CONSOLE_SCREEN_BUFFER_INFO info;
396 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
397 return info.wAttributes;
398}
399
400const char *Process::OutputReverse() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000401 if (UseANSI) return "\033[7m";
402
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000403 const WORD attributes
404 = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
405
406 const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
407 FOREGROUND_RED | FOREGROUND_INTENSITY;
408 const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
409 BACKGROUND_RED | BACKGROUND_INTENSITY;
410 const WORD color_mask = foreground_mask | background_mask;
411
412 WORD new_attributes =
413 ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
414 ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
415 ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
416 ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
417 ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
418 ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
419 ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
420 ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
421 0;
422 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
423
424 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
425 return 0;
426}
427
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000428const char *Process::ResetColor() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000429 if (UseANSI) return "\033[0m";
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000430 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
431 return 0;
432}
Aaron Ballman78440732014-02-04 14:49:21 +0000433
Paul Robinson8ab79a12015-11-11 20:49:32 +0000434// Include GetLastError() in a fatal error message.
435static void ReportLastErrorFatal(const char *Msg) {
436 std::string ErrMsg;
437 MakeErrMsg(&ErrMsg, Msg);
438 report_fatal_error(ErrMsg);
439}
440
Aaron Ballman78440732014-02-04 14:49:21 +0000441unsigned Process::GetRandomNumber() {
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000442 HCRYPTPROV HCPC;
443 if (!::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
444 CRYPT_VERIFYCONTEXT))
Paul Robinson8ab79a12015-11-11 20:49:32 +0000445 ReportLastErrorFatal("Could not acquire a cryptographic context");
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000446
447 ScopedCryptContext CryptoProvider(HCPC);
448 unsigned Ret;
449 if (!::CryptGenRandom(CryptoProvider, sizeof(Ret),
450 reinterpret_cast<BYTE *>(&Ret)))
Paul Robinson8ab79a12015-11-11 20:49:32 +0000451 ReportLastErrorFatal("Could not generate a random number");
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000452 return Ret;
Aaron Ballman78440732014-02-04 14:49:21 +0000453}