blob: 16e4092e9faf5b3ab2d5ac9921ba26f780b01dc4 [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"
Chandler Carruth10b09152014-01-07 12:37:13 +000015#include <malloc.h>
16
17// The Windows.h header must be after LLVM and standard headers.
18#include "Windows.h"
19
Daniel Dunbar9b92e2b2011-09-23 23:23:36 +000020#include <direct.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include <io.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include <psapi.h>
David Majnemer61eae2e2013-10-07 01:00:07 +000023#include <shellapi.h>
Jeff Cohen7ae0bc72004-12-20 03:24:56 +000024
Reid Spencer187b4ad2006-06-01 19:03:21 +000025#ifdef __MINGW32__
26 #if (HAVE_LIBPSAPI != 1)
27 #error "libpsapi.a should be present"
28 #endif
David Majnemer61eae2e2013-10-07 01:00:07 +000029 #if (HAVE_LIBSHELL32 != 1)
30 #error "libshell32.a should be present"
31 #endif
Reid Spencer187b4ad2006-06-01 19:03:21 +000032#else
David Majnemerf636cf42013-10-06 20:44:34 +000033 #pragma comment(lib, "psapi.lib")
David Majnemer61eae2e2013-10-07 01:00:07 +000034 #pragma comment(lib, "shell32.lib")
Reid Spencer187b4ad2006-06-01 19:03:21 +000035#endif
Reid Spencer91886b72004-09-15 05:47:40 +000036
37//===----------------------------------------------------------------------===//
Michael J. Spencer447762d2010-11-29 18:16:10 +000038//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer91886b72004-09-15 05:47:40 +000039//=== and must not be UNIX code
40//===----------------------------------------------------------------------===//
41
Jeff Cohen07e22ba2005-02-19 03:01:13 +000042#ifdef __MINGW32__
Jeff Cohen53fbecc2004-12-23 03:44:40 +000043// This ban should be lifted when MinGW 1.0+ has defined this value.
44# define _HEAPOK (-2)
45#endif
46
Chandler Carruth5473dfb2012-12-31 11:45:20 +000047using namespace llvm;
Reid Spencer91886b72004-09-15 05:47:40 +000048using namespace sys;
49
Chandler Carruth97683aa2012-12-31 11:17:50 +000050
51process::id_type self_process::get_id() {
Aaron Ballmanf0b53842013-06-08 20:29:03 +000052 return GetCurrentProcessId();
Chandler Carruth97683aa2012-12-31 11:17:50 +000053}
54
Chandler Carruthef7f9682013-01-04 23:19:55 +000055static TimeValue getTimeValueFromFILETIME(FILETIME Time) {
56 ULARGE_INTEGER TimeInteger;
57 TimeInteger.LowPart = Time.dwLowDateTime;
58 TimeInteger.HighPart = Time.dwHighDateTime;
59
60 // FILETIME's are # of 100 nanosecond ticks (1/10th of a microsecond)
61 return TimeValue(
62 static_cast<TimeValue::SecondsType>(TimeInteger.QuadPart / 10000000),
63 static_cast<TimeValue::NanoSecondsType>(
64 (TimeInteger.QuadPart % 10000000) * 100));
65}
66
67TimeValue self_process::get_user_time() const {
68 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
69 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
70 &UserTime) == 0)
71 return TimeValue();
72
73 return getTimeValueFromFILETIME(UserTime);
74}
75
76TimeValue self_process::get_system_time() const {
77 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
78 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
79 &UserTime) == 0)
80 return TimeValue();
81
82 return getTimeValueFromFILETIME(KernelTime);
83}
84
Reid Spencer91886b72004-09-15 05:47:40 +000085// This function retrieves the page size using GetSystemInfo and is present
Chandler Carruth15dcad92012-12-31 23:23:35 +000086// solely so it can be called once to initialize the self_process member below.
87static unsigned getPageSize() {
Reid Spencer91886b72004-09-15 05:47:40 +000088 // NOTE: A 32-bit application running under WOW64 is supposed to use
89 // GetNativeSystemInfo. However, this interface is not present prior
90 // to Windows XP so to use it requires dynamic linking. It is not clear
91 // how this affects the reported page size, if at all. One could argue
92 // that LLVM ought to run as 64-bits on a 64-bit system, anyway.
93 SYSTEM_INFO info;
94 GetSystemInfo(&info);
NAKAMURA Takumi7a042342013-09-04 14:12:26 +000095 // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
96 // but dwAllocationGranularity.
Reid Spencer91886b72004-09-15 05:47:40 +000097 return static_cast<unsigned>(info.dwPageSize);
98}
99
Chandler Carruth15dcad92012-12-31 23:23:35 +0000100// This constructor guaranteed to be run exactly once on a single thread, and
101// sets up various process invariants that can be queried cheaply from then on.
102self_process::self_process() : PageSize(getPageSize()) {
Reid Spencer91886b72004-09-15 05:47:40 +0000103}
104
Chandler Carruth15dcad92012-12-31 23:23:35 +0000105
Michael J. Spencer447762d2010-11-29 18:16:10 +0000106size_t
Reid Spencerac38f3a2004-12-20 00:59:28 +0000107Process::GetMallocUsage()
108{
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000109 _HEAPINFO hinfo;
110 hinfo._pentry = NULL;
111
112 size_t size = 0;
113
114 while (_heapwalk(&hinfo) == _HEAPOK)
115 size += hinfo._size;
116
117 return size;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000118}
119
Chandler Carruthef7f9682013-01-04 23:19:55 +0000120void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
121 TimeValue &sys_time) {
Reid Spencerac38f3a2004-12-20 00:59:28 +0000122 elapsed = TimeValue::now();
123
Chandler Carruthef7f9682013-01-04 23:19:55 +0000124 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
125 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
126 &UserTime) == 0)
127 return;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000128
Chandler Carruthef7f9682013-01-04 23:19:55 +0000129 user_time = getTimeValueFromFILETIME(UserTime);
Chandler Carruthb79a7aa2013-01-04 23:46:04 +0000130 sys_time = getTimeValueFromFILETIME(KernelTime);
Reid Spencerac38f3a2004-12-20 00:59:28 +0000131}
132
Reid Spencercf15b872004-12-27 06:17:27 +0000133// Some LLVM programs such as bugpoint produce core files as a normal part of
Aaron Ballmandcd57572013-08-16 14:33:07 +0000134// their operation. To prevent the disk from filling up, this configuration
135// item does what's necessary to prevent their generation.
Reid Spencercf15b872004-12-27 06:17:27 +0000136void Process::PreventCoreFiles() {
Aaron Ballmandcd57572013-08-16 14:33:07 +0000137 // Windows does have the concept of core files, called minidumps. However,
138 // disabling minidumps for a particular application extends past the lifetime
139 // of that application, which is the incorrect behavior for this API.
140 // Additionally, the APIs require elevated privileges to disable and re-
141 // enable minidumps, which makes this untenable. For more information, see
142 // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
143 // later).
144 //
145 // Windows also has modal pop-up message boxes. As this method is used by
146 // bugpoint, preventing these pop-ups is additionally important.
Jeff Cohen81549a52005-02-18 07:05:18 +0000147 SetErrorMode(SEM_FAILCRITICALERRORS |
148 SEM_NOGPFAULTERRORBOX |
149 SEM_NOOPENFILEERRORBOX);
Reid Spencercf15b872004-12-27 06:17:27 +0000150}
151
Rui Ueyama471d0c52013-09-10 19:45:51 +0000152/// Returns the environment variable \arg Name's value as a string encoded in
153/// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
154Optional<std::string> Process::GetEnv(StringRef Name) {
155 // Convert the argument to UTF-16 to pass it to _wgetenv().
156 SmallVector<wchar_t, 128> NameUTF16;
157 if (error_code ec = windows::UTF8ToUTF16(Name, NameUTF16))
158 return None;
159
160 // Environment variable can be encoded in non-UTF8 encoding, and there's no
161 // way to know what the encoding is. The only reliable way to look up
162 // multibyte environment variable is to use GetEnvironmentVariableW().
David Majnemer61eae2e2013-10-07 01:00:07 +0000163 SmallVector<wchar_t, MAX_PATH> Buf;
164 size_t Size = MAX_PATH;
165 do {
David Majnemerf07777c2013-10-07 21:57:07 +0000166 Buf.reserve(Size);
167 Size =
168 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
David Majnemer61eae2e2013-10-07 01:00:07 +0000169 if (Size == 0)
170 return None;
171
Rui Ueyama471d0c52013-09-10 19:45:51 +0000172 // Try again with larger buffer.
David Majnemer61eae2e2013-10-07 01:00:07 +0000173 } while (Size > Buf.capacity());
174 Buf.set_size(Size);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000175
176 // Convert the result from UTF-16 to UTF-8.
David Majnemer61eae2e2013-10-07 01:00:07 +0000177 SmallVector<char, MAX_PATH> Res;
David Majnemerf07777c2013-10-07 21:57:07 +0000178 if (error_code ec = windows::UTF16ToUTF8(Buf.data(), Size, Res))
Rui Ueyama471d0c52013-09-10 19:45:51 +0000179 return None;
David Majnemerf07777c2013-10-07 21:57:07 +0000180 return std::string(Res.data());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000181}
182
David Majnemer61eae2e2013-10-07 01:00:07 +0000183error_code
184Process::GetArgumentVector(SmallVectorImpl<const char *> &Args,
185 ArrayRef<const char *>,
186 SpecificBumpPtrAllocator<char> &ArgAllocator) {
187 int NewArgCount;
188 error_code ec;
189
190 wchar_t **UnicodeCommandLine = CommandLineToArgvW(GetCommandLineW(),
191 &NewArgCount);
192 if (!UnicodeCommandLine)
193 return windows_error(::GetLastError());
194
195 Args.reserve(NewArgCount);
196
197 for (int i = 0; i < NewArgCount; ++i) {
198 SmallVector<char, MAX_PATH> NewArgString;
199 ec = windows::UTF16ToUTF8(UnicodeCommandLine[i],
200 wcslen(UnicodeCommandLine[i]),
201 NewArgString);
202 if (ec)
203 break;
204
205 char *Buffer = ArgAllocator.Allocate(NewArgString.size() + 1);
206 ::memcpy(Buffer, NewArgString.data(), NewArgString.size() + 1);
207 Args.push_back(Buffer);
208 }
209 LocalFree(UnicodeCommandLine);
210 if (ec)
211 return ec;
212
213 return error_code::success();
214}
215
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000216bool Process::StandardInIsUserInput() {
Dan Gohmane5929232009-09-11 20:46:33 +0000217 return FileDescriptorIsDisplayed(0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000218}
219
220bool Process::StandardOutIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000221 return FileDescriptorIsDisplayed(1);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000222}
223
224bool Process::StandardErrIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000225 return FileDescriptorIsDisplayed(2);
226}
227
228bool Process::FileDescriptorIsDisplayed(int fd) {
Bill Wendling2b079652012-07-19 00:06:06 +0000229 DWORD Mode; // Unused
NAKAMURA Takumi23ebef12010-11-10 08:37:47 +0000230 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000231}
232
Douglas Gregor15436612009-05-11 18:05:52 +0000233unsigned Process::StandardOutColumns() {
234 unsigned Columns = 0;
235 CONSOLE_SCREEN_BUFFER_INFO csbi;
236 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
237 Columns = csbi.dwSize.X;
238 return Columns;
239}
240
241unsigned Process::StandardErrColumns() {
242 unsigned Columns = 0;
243 CONSOLE_SCREEN_BUFFER_INFO csbi;
244 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
245 Columns = csbi.dwSize.X;
246 return Columns;
247}
248
Daniel Dunbar712de822012-07-20 18:29:38 +0000249// The terminal always has colors.
Benjamin Kramerdfaa0f32012-07-20 19:49:33 +0000250bool Process::FileDescriptorHasColors(int fd) {
Daniel Dunbar712de822012-07-20 18:29:38 +0000251 return FileDescriptorIsDisplayed(fd);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000252}
253
254bool Process::StandardOutHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000255 return FileDescriptorHasColors(1);
256}
257
258bool Process::StandardErrHasColors() {
259 return FileDescriptorHasColors(2);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000260}
Torok Edwin63e44bb2009-06-04 08:18:25 +0000261
Nico Rieck92d649a2013-09-11 00:36:48 +0000262static bool UseANSI = false;
263void Process::UseANSIEscapeCodes(bool enable) {
264 UseANSI = enable;
265}
266
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000267namespace {
268class DefaultColors
269{
270 private:
271 WORD defaultColor;
272 public:
273 DefaultColors()
274 :defaultColor(GetCurrentColor()) {}
275 static unsigned GetCurrentColor() {
276 CONSOLE_SCREEN_BUFFER_INFO csbi;
277 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
278 return csbi.wAttributes;
279 return 0;
280 }
281 WORD operator()() const { return defaultColor; }
282};
283
284DefaultColors defaultColors;
285}
286
287bool Process::ColorNeedsFlush() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000288 return !UseANSI;
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000289}
290
291const char *Process::OutputBold(bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000292 if (UseANSI) return "\033[1m";
293
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000294 WORD colors = DefaultColors::GetCurrentColor();
295 if (bg)
296 colors |= BACKGROUND_INTENSITY;
297 else
298 colors |= FOREGROUND_INTENSITY;
299 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
300 return 0;
301}
302
303const char *Process::OutputColor(char code, bool bold, bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000304 if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
305
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000306 WORD colors;
307 if (bg) {
308 colors = ((code&1) ? BACKGROUND_RED : 0) |
309 ((code&2) ? BACKGROUND_GREEN : 0 ) |
310 ((code&4) ? BACKGROUND_BLUE : 0);
311 if (bold)
312 colors |= BACKGROUND_INTENSITY;
313 } else {
314 colors = ((code&1) ? FOREGROUND_RED : 0) |
315 ((code&2) ? FOREGROUND_GREEN : 0 ) |
316 ((code&4) ? FOREGROUND_BLUE : 0);
317 if (bold)
318 colors |= FOREGROUND_INTENSITY;
319 }
320 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
321 return 0;
322}
323
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000324static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
325 CONSOLE_SCREEN_BUFFER_INFO info;
326 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
327 return info.wAttributes;
328}
329
330const char *Process::OutputReverse() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000331 if (UseANSI) return "\033[7m";
332
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000333 const WORD attributes
334 = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
335
336 const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
337 FOREGROUND_RED | FOREGROUND_INTENSITY;
338 const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
339 BACKGROUND_RED | BACKGROUND_INTENSITY;
340 const WORD color_mask = foreground_mask | background_mask;
341
342 WORD new_attributes =
343 ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
344 ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
345 ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
346 ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
347 ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
348 ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
349 ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
350 ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
351 0;
352 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
353
354 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
355 return 0;
356}
357
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000358const char *Process::ResetColor() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000359 if (UseANSI) return "\033[0m";
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000360 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
361 return 0;
362}
Aaron Ballman78440732014-02-04 14:49:21 +0000363
364unsigned Process::GetRandomNumber() {
365 unsigned int result;
366 const errno_t ec = rand_s(&result);
367 assert(ec == 0 && "rand_s failed");
368 return result;
369}