blob: f9a3db9d918d30710beb2b111760816d938a0189 [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"
15
Michael J. Spencer447762d2010-11-29 18:16:10 +000016#include "Windows.h"
Daniel Dunbar9b92e2b2011-09-23 23:23:36 +000017#include <direct.h>
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include <io.h>
19#include <malloc.h>
20#include <psapi.h>
David Majnemer61eae2e2013-10-07 01:00:07 +000021#include <shellapi.h>
Jeff Cohen7ae0bc72004-12-20 03:24:56 +000022
Reid Spencer187b4ad2006-06-01 19:03:21 +000023#ifdef __MINGW32__
24 #if (HAVE_LIBPSAPI != 1)
25 #error "libpsapi.a should be present"
26 #endif
David Majnemer61eae2e2013-10-07 01:00:07 +000027 #if (HAVE_LIBSHELL32 != 1)
28 #error "libshell32.a should be present"
29 #endif
Reid Spencer187b4ad2006-06-01 19:03:21 +000030#else
David Majnemerf636cf42013-10-06 20:44:34 +000031 #pragma comment(lib, "psapi.lib")
David Majnemer61eae2e2013-10-07 01:00:07 +000032 #pragma comment(lib, "shell32.lib")
Reid Spencer187b4ad2006-06-01 19:03:21 +000033#endif
Reid Spencer91886b72004-09-15 05:47:40 +000034
35//===----------------------------------------------------------------------===//
Michael J. Spencer447762d2010-11-29 18:16:10 +000036//=== WARNING: Implementation here must contain only Win32 specific code
Reid Spencer91886b72004-09-15 05:47:40 +000037//=== and must not be UNIX code
38//===----------------------------------------------------------------------===//
39
Jeff Cohen07e22ba2005-02-19 03:01:13 +000040#ifdef __MINGW32__
Jeff Cohen53fbecc2004-12-23 03:44:40 +000041// This ban should be lifted when MinGW 1.0+ has defined this value.
42# define _HEAPOK (-2)
43#endif
44
Chandler Carruth5473dfb2012-12-31 11:45:20 +000045using namespace llvm;
Reid Spencer91886b72004-09-15 05:47:40 +000046using namespace sys;
47
Chandler Carruth97683aa2012-12-31 11:17:50 +000048
49process::id_type self_process::get_id() {
Aaron Ballmanf0b53842013-06-08 20:29:03 +000050 return GetCurrentProcessId();
Chandler Carruth97683aa2012-12-31 11:17:50 +000051}
52
Chandler Carruthef7f9682013-01-04 23:19:55 +000053static TimeValue getTimeValueFromFILETIME(FILETIME Time) {
54 ULARGE_INTEGER TimeInteger;
55 TimeInteger.LowPart = Time.dwLowDateTime;
56 TimeInteger.HighPart = Time.dwHighDateTime;
57
58 // FILETIME's are # of 100 nanosecond ticks (1/10th of a microsecond)
59 return TimeValue(
60 static_cast<TimeValue::SecondsType>(TimeInteger.QuadPart / 10000000),
61 static_cast<TimeValue::NanoSecondsType>(
62 (TimeInteger.QuadPart % 10000000) * 100));
63}
64
65TimeValue self_process::get_user_time() const {
66 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
67 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
68 &UserTime) == 0)
69 return TimeValue();
70
71 return getTimeValueFromFILETIME(UserTime);
72}
73
74TimeValue self_process::get_system_time() const {
75 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
76 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
77 &UserTime) == 0)
78 return TimeValue();
79
80 return getTimeValueFromFILETIME(KernelTime);
81}
82
Reid Spencer91886b72004-09-15 05:47:40 +000083// This function retrieves the page size using GetSystemInfo and is present
Chandler Carruth15dcad92012-12-31 23:23:35 +000084// solely so it can be called once to initialize the self_process member below.
85static unsigned getPageSize() {
Reid Spencer91886b72004-09-15 05:47:40 +000086 // NOTE: A 32-bit application running under WOW64 is supposed to use
87 // GetNativeSystemInfo. However, this interface is not present prior
88 // to Windows XP so to use it requires dynamic linking. It is not clear
89 // how this affects the reported page size, if at all. One could argue
90 // that LLVM ought to run as 64-bits on a 64-bit system, anyway.
91 SYSTEM_INFO info;
92 GetSystemInfo(&info);
NAKAMURA Takumi7a042342013-09-04 14:12:26 +000093 // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
94 // but dwAllocationGranularity.
Reid Spencer91886b72004-09-15 05:47:40 +000095 return static_cast<unsigned>(info.dwPageSize);
96}
97
Chandler Carruth15dcad92012-12-31 23:23:35 +000098// This constructor guaranteed to be run exactly once on a single thread, and
99// sets up various process invariants that can be queried cheaply from then on.
100self_process::self_process() : PageSize(getPageSize()) {
Reid Spencer91886b72004-09-15 05:47:40 +0000101}
102
Chandler Carruth15dcad92012-12-31 23:23:35 +0000103
Michael J. Spencer447762d2010-11-29 18:16:10 +0000104size_t
Reid Spencerac38f3a2004-12-20 00:59:28 +0000105Process::GetMallocUsage()
106{
Jeff Cohen7ae0bc72004-12-20 03:24:56 +0000107 _HEAPINFO hinfo;
108 hinfo._pentry = NULL;
109
110 size_t size = 0;
111
112 while (_heapwalk(&hinfo) == _HEAPOK)
113 size += hinfo._size;
114
115 return size;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000116}
117
Chandler Carruthef7f9682013-01-04 23:19:55 +0000118void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
119 TimeValue &sys_time) {
Reid Spencerac38f3a2004-12-20 00:59:28 +0000120 elapsed = TimeValue::now();
121
Chandler Carruthef7f9682013-01-04 23:19:55 +0000122 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
123 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
124 &UserTime) == 0)
125 return;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000126
Chandler Carruthef7f9682013-01-04 23:19:55 +0000127 user_time = getTimeValueFromFILETIME(UserTime);
Chandler Carruthb79a7aa2013-01-04 23:46:04 +0000128 sys_time = getTimeValueFromFILETIME(KernelTime);
Reid Spencerac38f3a2004-12-20 00:59:28 +0000129}
130
Reid Spencercf15b872004-12-27 06:17:27 +0000131// Some LLVM programs such as bugpoint produce core files as a normal part of
Aaron Ballmandcd57572013-08-16 14:33:07 +0000132// their operation. To prevent the disk from filling up, this configuration
133// item does what's necessary to prevent their generation.
Reid Spencercf15b872004-12-27 06:17:27 +0000134void Process::PreventCoreFiles() {
Aaron Ballmandcd57572013-08-16 14:33:07 +0000135 // Windows does have the concept of core files, called minidumps. However,
136 // disabling minidumps for a particular application extends past the lifetime
137 // of that application, which is the incorrect behavior for this API.
138 // Additionally, the APIs require elevated privileges to disable and re-
139 // enable minidumps, which makes this untenable. For more information, see
140 // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
141 // later).
142 //
143 // Windows also has modal pop-up message boxes. As this method is used by
144 // bugpoint, preventing these pop-ups is additionally important.
Jeff Cohen81549a52005-02-18 07:05:18 +0000145 SetErrorMode(SEM_FAILCRITICALERRORS |
146 SEM_NOGPFAULTERRORBOX |
147 SEM_NOOPENFILEERRORBOX);
Reid Spencercf15b872004-12-27 06:17:27 +0000148}
149
Rui Ueyama471d0c52013-09-10 19:45:51 +0000150/// Returns the environment variable \arg Name's value as a string encoded in
151/// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
152Optional<std::string> Process::GetEnv(StringRef Name) {
153 // Convert the argument to UTF-16 to pass it to _wgetenv().
154 SmallVector<wchar_t, 128> NameUTF16;
155 if (error_code ec = windows::UTF8ToUTF16(Name, NameUTF16))
156 return None;
157
158 // Environment variable can be encoded in non-UTF8 encoding, and there's no
159 // way to know what the encoding is. The only reliable way to look up
160 // multibyte environment variable is to use GetEnvironmentVariableW().
David Majnemer61eae2e2013-10-07 01:00:07 +0000161 SmallVector<wchar_t, MAX_PATH> Buf;
162 size_t Size = MAX_PATH;
163 do {
David Majnemerf07777c2013-10-07 21:57:07 +0000164 Buf.reserve(Size);
165 Size =
166 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
David Majnemer61eae2e2013-10-07 01:00:07 +0000167 if (Size == 0)
168 return None;
169
Rui Ueyama471d0c52013-09-10 19:45:51 +0000170 // Try again with larger buffer.
David Majnemer61eae2e2013-10-07 01:00:07 +0000171 } while (Size > Buf.capacity());
172 Buf.set_size(Size);
Rui Ueyama471d0c52013-09-10 19:45:51 +0000173
174 // Convert the result from UTF-16 to UTF-8.
David Majnemer61eae2e2013-10-07 01:00:07 +0000175 SmallVector<char, MAX_PATH> Res;
David Majnemerf07777c2013-10-07 21:57:07 +0000176 if (error_code ec = windows::UTF16ToUTF8(Buf.data(), Size, Res))
Rui Ueyama471d0c52013-09-10 19:45:51 +0000177 return None;
David Majnemerf07777c2013-10-07 21:57:07 +0000178 return std::string(Res.data());
Rui Ueyama471d0c52013-09-10 19:45:51 +0000179}
180
David Majnemer61eae2e2013-10-07 01:00:07 +0000181error_code
182Process::GetArgumentVector(SmallVectorImpl<const char *> &Args,
183 ArrayRef<const char *>,
184 SpecificBumpPtrAllocator<char> &ArgAllocator) {
185 int NewArgCount;
186 error_code ec;
187
188 wchar_t **UnicodeCommandLine = CommandLineToArgvW(GetCommandLineW(),
189 &NewArgCount);
190 if (!UnicodeCommandLine)
191 return windows_error(::GetLastError());
192
193 Args.reserve(NewArgCount);
194
195 for (int i = 0; i < NewArgCount; ++i) {
196 SmallVector<char, MAX_PATH> NewArgString;
197 ec = windows::UTF16ToUTF8(UnicodeCommandLine[i],
198 wcslen(UnicodeCommandLine[i]),
199 NewArgString);
200 if (ec)
201 break;
202
203 char *Buffer = ArgAllocator.Allocate(NewArgString.size() + 1);
204 ::memcpy(Buffer, NewArgString.data(), NewArgString.size() + 1);
205 Args.push_back(Buffer);
206 }
207 LocalFree(UnicodeCommandLine);
208 if (ec)
209 return ec;
210
211 return error_code::success();
212}
213
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000214bool Process::StandardInIsUserInput() {
Dan Gohmane5929232009-09-11 20:46:33 +0000215 return FileDescriptorIsDisplayed(0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000216}
217
218bool Process::StandardOutIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000219 return FileDescriptorIsDisplayed(1);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000220}
221
222bool Process::StandardErrIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000223 return FileDescriptorIsDisplayed(2);
224}
225
226bool Process::FileDescriptorIsDisplayed(int fd) {
Bill Wendling2b079652012-07-19 00:06:06 +0000227 DWORD Mode; // Unused
NAKAMURA Takumi23ebef12010-11-10 08:37:47 +0000228 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
Jeff Cohenb90c31f2005-01-01 22:54:05 +0000229}
230
Douglas Gregor15436612009-05-11 18:05:52 +0000231unsigned Process::StandardOutColumns() {
232 unsigned Columns = 0;
233 CONSOLE_SCREEN_BUFFER_INFO csbi;
234 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
235 Columns = csbi.dwSize.X;
236 return Columns;
237}
238
239unsigned Process::StandardErrColumns() {
240 unsigned Columns = 0;
241 CONSOLE_SCREEN_BUFFER_INFO csbi;
242 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
243 Columns = csbi.dwSize.X;
244 return Columns;
245}
246
Daniel Dunbar712de822012-07-20 18:29:38 +0000247// The terminal always has colors.
Benjamin Kramerdfaa0f32012-07-20 19:49:33 +0000248bool Process::FileDescriptorHasColors(int fd) {
Daniel Dunbar712de822012-07-20 18:29:38 +0000249 return FileDescriptorIsDisplayed(fd);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000250}
251
252bool Process::StandardOutHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000253 return FileDescriptorHasColors(1);
254}
255
256bool Process::StandardErrHasColors() {
257 return FileDescriptorHasColors(2);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000258}
Torok Edwin63e44bb2009-06-04 08:18:25 +0000259
Nico Rieck92d649a2013-09-11 00:36:48 +0000260static bool UseANSI = false;
261void Process::UseANSIEscapeCodes(bool enable) {
262 UseANSI = enable;
263}
264
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000265namespace {
266class DefaultColors
267{
268 private:
269 WORD defaultColor;
270 public:
271 DefaultColors()
272 :defaultColor(GetCurrentColor()) {}
273 static unsigned GetCurrentColor() {
274 CONSOLE_SCREEN_BUFFER_INFO csbi;
275 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
276 return csbi.wAttributes;
277 return 0;
278 }
279 WORD operator()() const { return defaultColor; }
280};
281
282DefaultColors defaultColors;
283}
284
285bool Process::ColorNeedsFlush() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000286 return !UseANSI;
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000287}
288
289const char *Process::OutputBold(bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000290 if (UseANSI) return "\033[1m";
291
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000292 WORD colors = DefaultColors::GetCurrentColor();
293 if (bg)
294 colors |= BACKGROUND_INTENSITY;
295 else
296 colors |= FOREGROUND_INTENSITY;
297 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
298 return 0;
299}
300
301const char *Process::OutputColor(char code, bool bold, bool bg) {
Nico Rieck92d649a2013-09-11 00:36:48 +0000302 if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
303
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000304 WORD colors;
305 if (bg) {
306 colors = ((code&1) ? BACKGROUND_RED : 0) |
307 ((code&2) ? BACKGROUND_GREEN : 0 ) |
308 ((code&4) ? BACKGROUND_BLUE : 0);
309 if (bold)
310 colors |= BACKGROUND_INTENSITY;
311 } else {
312 colors = ((code&1) ? FOREGROUND_RED : 0) |
313 ((code&2) ? FOREGROUND_GREEN : 0 ) |
314 ((code&4) ? FOREGROUND_BLUE : 0);
315 if (bold)
316 colors |= FOREGROUND_INTENSITY;
317 }
318 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
319 return 0;
320}
321
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000322static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
323 CONSOLE_SCREEN_BUFFER_INFO info;
324 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
325 return info.wAttributes;
326}
327
328const char *Process::OutputReverse() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000329 if (UseANSI) return "\033[7m";
330
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000331 const WORD attributes
332 = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
333
334 const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
335 FOREGROUND_RED | FOREGROUND_INTENSITY;
336 const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
337 BACKGROUND_RED | BACKGROUND_INTENSITY;
338 const WORD color_mask = foreground_mask | background_mask;
339
340 WORD new_attributes =
341 ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
342 ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
343 ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
344 ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
345 ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
346 ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
347 ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
348 ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
349 0;
350 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
351
352 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
353 return 0;
354}
355
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000356const char *Process::ResetColor() {
Nico Rieck92d649a2013-09-11 00:36:48 +0000357 if (UseANSI) return "\033[0m";
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000358 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
359 return 0;
360}