blob: 81aee0e1b6aca5a58a750d82b0e7aa72e5be94d5 [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
52process::id_type self_process::get_id() {
Aaron Ballmanf0b53842013-06-08 20:29:03 +000053 return GetCurrentProcessId();
Chandler Carruth97683aa2012-12-31 11:17:50 +000054}
55
Chandler Carruthef7f9682013-01-04 23:19:55 +000056static TimeValue getTimeValueFromFILETIME(FILETIME Time) {
57 ULARGE_INTEGER TimeInteger;
58 TimeInteger.LowPart = Time.dwLowDateTime;
59 TimeInteger.HighPart = Time.dwHighDateTime;
60
61 // FILETIME's are # of 100 nanosecond ticks (1/10th of a microsecond)
62 return TimeValue(
63 static_cast<TimeValue::SecondsType>(TimeInteger.QuadPart / 10000000),
64 static_cast<TimeValue::NanoSecondsType>(
65 (TimeInteger.QuadPart % 10000000) * 100));
66}
67
68TimeValue self_process::get_user_time() const {
69 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
70 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
71 &UserTime) == 0)
72 return TimeValue();
73
74 return getTimeValueFromFILETIME(UserTime);
75}
76
77TimeValue self_process::get_system_time() const {
78 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
79 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
80 &UserTime) == 0)
81 return TimeValue();
82
83 return getTimeValueFromFILETIME(KernelTime);
84}
85
Alp Tokerd71b6df2014-05-19 16:13:28 +000086// This function retrieves the page size using GetNativeSystemInfo() and is
87// present solely so it can be called once to initialize the self_process member
88// below.
Chandler Carruth15dcad92012-12-31 23:23:35 +000089static unsigned getPageSize() {
Alp Tokerd71b6df2014-05-19 16:13:28 +000090 // GetNativeSystemInfo() provides the physical page size which may differ
91 // from GetSystemInfo() in 32-bit applications running under WOW64.
Reid Spencer91886b72004-09-15 05:47:40 +000092 SYSTEM_INFO info;
Alp Tokerd71b6df2014-05-19 16:13:28 +000093 GetNativeSystemInfo(&info);
NAKAMURA Takumi7a042342013-09-04 14:12:26 +000094 // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
95 // but dwAllocationGranularity.
Reid Spencer91886b72004-09-15 05:47:40 +000096 return static_cast<unsigned>(info.dwPageSize);
97}
98
Chandler Carruth15dcad92012-12-31 23:23:35 +000099// This constructor guaranteed to be run exactly once on a single thread, and
100// sets up various process invariants that can be queried cheaply from then on.
101self_process::self_process() : PageSize(getPageSize()) {
Reid Spencer91886b72004-09-15 05:47:40 +0000102}
103
Chandler Carruth15dcad92012-12-31 23:23:35 +0000104
Michael J. Spencer447762d2010-11-29 18:16:10 +0000105size_t
Reid Spencerac38f3a2004-12-20 00:59:28 +0000106Process::GetMallocUsage()
107{
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000108 _HEAPINFO hinfo;
109 hinfo._pentry = NULL;
110
111 size_t size = 0;
112
113 while (_heapwalk(&hinfo) == _HEAPOK)
114 size += hinfo._size;
115
116 return size;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000117}
118
Chandler Carruthef7f9682013-01-04 23:19:55 +0000119void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
120 TimeValue &sys_time) {
Reid Spencerac38f3a2004-12-20 00:59:28 +0000121 elapsed = TimeValue::now();
122
Chandler Carruthef7f9682013-01-04 23:19:55 +0000123 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
124 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
125 &UserTime) == 0)
126 return;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000127
Chandler Carruthef7f9682013-01-04 23:19:55 +0000128 user_time = getTimeValueFromFILETIME(UserTime);
Chandler Carruthb79a7aa2013-01-04 23:46:04 +0000129 sys_time = getTimeValueFromFILETIME(KernelTime);
Reid Spencerac38f3a2004-12-20 00:59:28 +0000130}
131
Reid Spencercf15b872004-12-27 06:17:27 +0000132// Some LLVM programs such as bugpoint produce core files as a normal part of
Aaron Ballmandcd57572013-08-16 14:33:07 +0000133// their operation. To prevent the disk from filling up, this configuration
134// item does what's necessary to prevent their generation.
Reid Spencercf15b872004-12-27 06:17:27 +0000135void Process::PreventCoreFiles() {
Aaron Ballmandcd57572013-08-16 14:33:07 +0000136 // Windows does have the concept of core files, called minidumps. However,
137 // disabling minidumps for a particular application extends past the lifetime
138 // of that application, which is the incorrect behavior for this API.
139 // Additionally, the APIs require elevated privileges to disable and re-
140 // enable minidumps, which makes this untenable. For more information, see
141 // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
142 // later).
143 //
144 // Windows also has modal pop-up message boxes. As this method is used by
145 // bugpoint, preventing these pop-ups is additionally important.
Jeff Cohen81549a52005-02-18 07:05:18 +0000146 SetErrorMode(SEM_FAILCRITICALERRORS |
147 SEM_NOGPFAULTERRORBOX |
148 SEM_NOOPENFILEERRORBOX);
Reid Spencercf15b872004-12-27 06:17:27 +0000149}
150
Rui Ueyama471d0c52013-09-10 19:45:51 +0000151/// Returns the environment variable \arg Name's value as a string encoded in
152/// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
153Optional<std::string> Process::GetEnv(StringRef Name) {
154 // Convert the argument to UTF-16 to pass it to _wgetenv().
155 SmallVector<wchar_t, 128> NameUTF16;
Ahmed Charlesce30de92014-03-05 05:04:00 +0000156 if (windows::UTF8ToUTF16(Name, NameUTF16))
Rui Ueyama471d0c52013-09-10 19:45:51 +0000157 return None;
158
159 // Environment variable can be encoded in non-UTF8 encoding, and there's no
160 // way to know what the encoding is. The only reliable way to look up
161 // multibyte environment variable is to use GetEnvironmentVariableW().
David Majnemer61eae2e2013-10-07 01:00:07 +0000162 SmallVector<wchar_t, MAX_PATH> Buf;
163 size_t Size = MAX_PATH;
164 do {
David Majnemerf07777c2013-10-07 21:57:07 +0000165 Buf.reserve(Size);
166 Size =
167 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
David Majnemer61eae2e2013-10-07 01:00:07 +0000168 if (Size == 0)
169 return None;
170
Rui Ueyama471d0c52013-09-10 19:45:51 +0000171 // Try again with larger buffer.
David Majnemer61eae2e2013-10-07 01:00:07 +0000172 } while (Size > Buf.capacity());
173 Buf.set_size(Size);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000174
175 // Convert the result from UTF-16 to UTF-8.
David Majnemer61eae2e2013-10-07 01:00:07 +0000176 SmallVector<char, MAX_PATH> Res;
Ahmed Charlesce30de92014-03-05 05:04:00 +0000177 if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
Rui Ueyama471d0c52013-09-10 19:45:51 +0000178 return None;
David Majnemerf07777c2013-10-07 21:57:07 +0000179 return std::string(Res.data());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000180}
181
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000182static std::error_code windows_error(DWORD E) {
Rafael Espindola5c4f8292014-06-11 19:05:50 +0000183 return mapWindowsError(E);
Rafael Espindolaa813d602014-06-11 03:58:34 +0000184}
185
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000186std::error_code
David Majnemer61eae2e2013-10-07 01:00:07 +0000187Process::GetArgumentVector(SmallVectorImpl<const char *> &Args,
188 ArrayRef<const char *>,
189 SpecificBumpPtrAllocator<char> &ArgAllocator) {
190 int NewArgCount;
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000191 std::error_code ec;
David Majnemer61eae2e2013-10-07 01:00:07 +0000192
193 wchar_t **UnicodeCommandLine = CommandLineToArgvW(GetCommandLineW(),
194 &NewArgCount);
195 if (!UnicodeCommandLine)
196 return windows_error(::GetLastError());
197
198 Args.reserve(NewArgCount);
199
200 for (int i = 0; i < NewArgCount; ++i) {
201 SmallVector<char, MAX_PATH> NewArgString;
202 ec = windows::UTF16ToUTF8(UnicodeCommandLine[i],
203 wcslen(UnicodeCommandLine[i]),
204 NewArgString);
205 if (ec)
206 break;
207
208 char *Buffer = ArgAllocator.Allocate(NewArgString.size() + 1);
209 ::memcpy(Buffer, NewArgString.data(), NewArgString.size() + 1);
210 Args.push_back(Buffer);
211 }
212 LocalFree(UnicodeCommandLine);
213 if (ec)
214 return ec;
215
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000216 return std::error_code();
David Majnemer61eae2e2013-10-07 01:00:07 +0000217}
218
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000219bool Process::StandardInIsUserInput() {
Dan Gohmane5929232009-09-11 20:46:33 +0000220 return FileDescriptorIsDisplayed(0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000221}
222
223bool Process::StandardOutIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000224 return FileDescriptorIsDisplayed(1);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000225}
226
227bool Process::StandardErrIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000228 return FileDescriptorIsDisplayed(2);
229}
230
231bool Process::FileDescriptorIsDisplayed(int fd) {
Bill Wendling2b079652012-07-19 00:06:06 +0000232 DWORD Mode; // Unused
NAKAMURA Takumi23ebef12010-11-10 08:37:47 +0000233 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000234}
235
Douglas Gregor15436612009-05-11 18:05:52 +0000236unsigned Process::StandardOutColumns() {
237 unsigned Columns = 0;
238 CONSOLE_SCREEN_BUFFER_INFO csbi;
239 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
240 Columns = csbi.dwSize.X;
241 return Columns;
242}
243
244unsigned Process::StandardErrColumns() {
245 unsigned Columns = 0;
246 CONSOLE_SCREEN_BUFFER_INFO csbi;
247 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
248 Columns = csbi.dwSize.X;
249 return Columns;
250}
251
Daniel Dunbar712de822012-07-20 18:29:38 +0000252// The terminal always has colors.
Benjamin Kramerdfaa0f32012-07-20 19:49:33 +0000253bool Process::FileDescriptorHasColors(int fd) {
Daniel Dunbar712de822012-07-20 18:29:38 +0000254 return FileDescriptorIsDisplayed(fd);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000255}
256
257bool Process::StandardOutHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000258 return FileDescriptorHasColors(1);
259}
260
261bool Process::StandardErrHasColors() {
262 return FileDescriptorHasColors(2);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000263}
Torok Edwin63e44bb2009-06-04 08:18:25 +0000264
Nico Rieck92d649a2013-09-11 00:36:48 +0000265static bool UseANSI = false;
266void Process::UseANSIEscapeCodes(bool enable) {
267 UseANSI = enable;
268}
269
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000270namespace {
271class DefaultColors
272{
273 private:
274 WORD defaultColor;
275 public:
276 DefaultColors()
277 :defaultColor(GetCurrentColor()) {}
278 static unsigned GetCurrentColor() {
279 CONSOLE_SCREEN_BUFFER_INFO csbi;
280 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
281 return csbi.wAttributes;
282 return 0;
283 }
284 WORD operator()() const { return defaultColor; }
285};
286
287DefaultColors defaultColors;
288}
289
290bool Process::ColorNeedsFlush() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000291 return !UseANSI;
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000292}
293
294const char *Process::OutputBold(bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000295 if (UseANSI) return "\033[1m";
296
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000297 WORD colors = DefaultColors::GetCurrentColor();
298 if (bg)
299 colors |= BACKGROUND_INTENSITY;
300 else
301 colors |= FOREGROUND_INTENSITY;
302 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
303 return 0;
304}
305
306const char *Process::OutputColor(char code, bool bold, bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000307 if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
308
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000309 WORD colors;
310 if (bg) {
311 colors = ((code&1) ? BACKGROUND_RED : 0) |
312 ((code&2) ? BACKGROUND_GREEN : 0 ) |
313 ((code&4) ? BACKGROUND_BLUE : 0);
314 if (bold)
315 colors |= BACKGROUND_INTENSITY;
316 } else {
317 colors = ((code&1) ? FOREGROUND_RED : 0) |
318 ((code&2) ? FOREGROUND_GREEN : 0 ) |
319 ((code&4) ? FOREGROUND_BLUE : 0);
320 if (bold)
321 colors |= FOREGROUND_INTENSITY;
322 }
323 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
324 return 0;
325}
326
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000327static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
328 CONSOLE_SCREEN_BUFFER_INFO info;
329 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
330 return info.wAttributes;
331}
332
333const char *Process::OutputReverse() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000334 if (UseANSI) return "\033[7m";
335
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000336 const WORD attributes
337 = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
338
339 const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
340 FOREGROUND_RED | FOREGROUND_INTENSITY;
341 const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
342 BACKGROUND_RED | BACKGROUND_INTENSITY;
343 const WORD color_mask = foreground_mask | background_mask;
344
345 WORD new_attributes =
346 ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
347 ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
348 ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
349 ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
350 ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
351 ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
352 ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
353 ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
354 0;
355 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
356
357 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
358 return 0;
359}
360
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000361const char *Process::ResetColor() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000362 if (UseANSI) return "\033[0m";
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000363 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
364 return 0;
365}
Aaron Ballman78440732014-02-04 14:49:21 +0000366
367unsigned Process::GetRandomNumber() {
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000368 HCRYPTPROV HCPC;
369 if (!::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
370 CRYPT_VERIFYCONTEXT))
Alp Toker552f2f72014-06-03 03:01:03 +0000371 report_fatal_error("Could not acquire a cryptographic context");
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000372
373 ScopedCryptContext CryptoProvider(HCPC);
374 unsigned Ret;
375 if (!::CryptGenRandom(CryptoProvider, sizeof(Ret),
376 reinterpret_cast<BYTE *>(&Ret)))
Alp Toker552f2f72014-06-03 03:01:03 +0000377 report_fatal_error("Could not generate a random number");
Aaron Ballman3f5e8b82014-02-11 02:47:33 +0000378 return Ret;
Aaron Ballman78440732014-02-04 14:49:21 +0000379}