1 //===- Win32/Process.cpp - Win32 Process Implementation ------- -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides the Win32 specific implementation of the Process class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Support/Allocator.h"
15 #include "llvm/Support/ErrorHandling.h"
16 #include "llvm/Support/WindowsError.h"
19 // The Windows.h header must be after LLVM and standard headers.
20 #include "WindowsSupport.h"
28 #if (HAVE_LIBPSAPI != 1)
29 #error "libpsapi.a should be present"
31 #if (HAVE_LIBSHELL32 != 1)
32 #error "libshell32.a should be present"
35 #pragma comment(lib, "psapi.lib")
36 #pragma comment(lib, "shell32.lib")
39 //===----------------------------------------------------------------------===//
40 //=== WARNING: Implementation here must contain only Win32 specific code
41 //=== and must not be UNIX code
42 //===----------------------------------------------------------------------===//
45 // This ban should be lifted when MinGW 1.0+ has defined this value.
52 static TimeValue getTimeValueFromFILETIME(FILETIME Time) {
53 ULARGE_INTEGER TimeInteger;
54 TimeInteger.LowPart = Time.dwLowDateTime;
55 TimeInteger.HighPart = Time.dwHighDateTime;
57 // FILETIME's are # of 100 nanosecond ticks (1/10th of a microsecond)
59 static_cast<TimeValue::SecondsType>(TimeInteger.QuadPart / 10000000),
60 static_cast<TimeValue::NanoSecondsType>(
61 (TimeInteger.QuadPart % 10000000) * 100));
64 // This function retrieves the page size using GetNativeSystemInfo() and is
65 // present solely so it can be called once to initialize the self_process member
67 static unsigned computePageSize() {
68 // GetNativeSystemInfo() provides the physical page size which may differ
69 // from GetSystemInfo() in 32-bit applications running under WOW64.
71 GetNativeSystemInfo(&info);
72 // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
73 // but dwAllocationGranularity.
74 return static_cast<unsigned>(info.dwPageSize);
77 unsigned Process::getPageSize() {
78 static unsigned Ret = computePageSize();
83 Process::GetMallocUsage()
90 while (_heapwalk(&hinfo) == _HEAPOK)
96 void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
97 TimeValue &sys_time) {
98 elapsed = TimeValue::now();
100 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
101 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
105 user_time = getTimeValueFromFILETIME(UserTime);
106 sys_time = getTimeValueFromFILETIME(KernelTime);
109 // Some LLVM programs such as bugpoint produce core files as a normal part of
110 // their operation. To prevent the disk from filling up, this configuration
111 // item does what's necessary to prevent their generation.
112 void Process::PreventCoreFiles() {
113 // Windows does have the concept of core files, called minidumps. However,
114 // disabling minidumps for a particular application extends past the lifetime
115 // of that application, which is the incorrect behavior for this API.
116 // Additionally, the APIs require elevated privileges to disable and re-
117 // enable minidumps, which makes this untenable. For more information, see
118 // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
121 // Windows also has modal pop-up message boxes. As this method is used by
122 // bugpoint, preventing these pop-ups is additionally important.
123 SetErrorMode(SEM_FAILCRITICALERRORS |
124 SEM_NOGPFAULTERRORBOX |
125 SEM_NOOPENFILEERRORBOX);
128 /// Returns the environment variable \arg Name's value as a string encoded in
129 /// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
130 Optional<std::string> Process::GetEnv(StringRef Name) {
131 // Convert the argument to UTF-16 to pass it to _wgetenv().
132 SmallVector<wchar_t, 128> NameUTF16;
133 if (windows::UTF8ToUTF16(Name, NameUTF16))
136 // Environment variable can be encoded in non-UTF8 encoding, and there's no
137 // way to know what the encoding is. The only reliable way to look up
138 // multibyte environment variable is to use GetEnvironmentVariableW().
139 SmallVector<wchar_t, MAX_PATH> Buf;
140 size_t Size = MAX_PATH;
144 GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
148 // Try again with larger buffer.
149 } while (Size > Buf.capacity());
152 // Convert the result from UTF-16 to UTF-8.
153 SmallVector<char, MAX_PATH> Res;
154 if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
156 return std::string(Res.data());
159 static std::error_code windows_error(DWORD E) {
160 return mapWindowsError(E);
163 static void AllocateAndPush(const SmallVectorImpl<char> &S,
164 SmallVectorImpl<const char *> &Vector,
165 SpecificBumpPtrAllocator<char> &Allocator) {
166 char *Buffer = Allocator.Allocate(S.size() + 1);
167 ::memcpy(Buffer, S.data(), S.size());
168 Buffer[S.size()] = '\0';
169 Vector.push_back(Buffer);
172 /// Convert Arg from UTF-16 to UTF-8 and push it onto Args.
173 static std::error_code
174 ConvertAndPushArg(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
175 SpecificBumpPtrAllocator<char> &Allocator) {
176 SmallVector<char, MAX_PATH> ArgString;
177 if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), ArgString))
179 AllocateAndPush(ArgString, Args, Allocator);
180 return std::error_code();
183 /// \brief Perform wildcard expansion of Arg, or just push it into Args if it
184 /// doesn't have wildcards or doesn't match any files.
185 static std::error_code
186 WildcardExpand(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
187 SpecificBumpPtrAllocator<char> &Allocator) {
188 if (!wcspbrk(Arg, L"*?")) {
189 // Arg does not contain any wildcard characters. This is the common case.
190 return ConvertAndPushArg(Arg, Args, Allocator);
193 if (wcscmp(Arg, L"/?") == 0 || wcscmp(Arg, L"-?") == 0) {
194 // Don't wildcard expand /?. Always treat it as an option.
195 return ConvertAndPushArg(Arg, Args, Allocator);
198 // Extract any directory part of the argument.
199 SmallVector<char, MAX_PATH> Dir;
200 if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), Dir))
202 sys::path::remove_filename(Dir);
203 const int DirSize = Dir.size();
205 // Search for matching files.
206 WIN32_FIND_DATAW FileData;
207 HANDLE FindHandle = FindFirstFileW(Arg, &FileData);
208 if (FindHandle == INVALID_HANDLE_VALUE) {
209 return ConvertAndPushArg(Arg, Args, Allocator);
214 SmallVector<char, MAX_PATH> FileName;
215 ec = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
220 // Push the filename onto Dir, and remove it afterwards.
221 llvm::sys::path::append(Dir, StringRef(FileName.data(), FileName.size()));
222 AllocateAndPush(Dir, Args, Allocator);
224 } while (FindNextFileW(FindHandle, &FileData));
226 FindClose(FindHandle);
231 Process::GetArgumentVector(SmallVectorImpl<const char *> &Args,
232 ArrayRef<const char *>,
233 SpecificBumpPtrAllocator<char> &ArgAllocator) {
235 wchar_t **UnicodeCommandLine =
236 CommandLineToArgvW(GetCommandLineW(), &ArgCount);
237 if (!UnicodeCommandLine)
238 return windows_error(::GetLastError());
240 Args.reserve(ArgCount);
243 for (int i = 0; i < ArgCount; ++i) {
244 ec = WildcardExpand(UnicodeCommandLine[i], Args, ArgAllocator);
249 LocalFree(UnicodeCommandLine);
253 std::error_code Process::FixupStandardFileDescriptors() {
254 return std::error_code();
257 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
259 return std::error_code(errno, std::generic_category());
260 return std::error_code();
263 bool Process::StandardInIsUserInput() {
264 return FileDescriptorIsDisplayed(0);
267 bool Process::StandardOutIsDisplayed() {
268 return FileDescriptorIsDisplayed(1);
271 bool Process::StandardErrIsDisplayed() {
272 return FileDescriptorIsDisplayed(2);
275 bool Process::FileDescriptorIsDisplayed(int fd) {
276 DWORD Mode; // Unused
277 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
280 unsigned Process::StandardOutColumns() {
281 unsigned Columns = 0;
282 CONSOLE_SCREEN_BUFFER_INFO csbi;
283 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
284 Columns = csbi.dwSize.X;
288 unsigned Process::StandardErrColumns() {
289 unsigned Columns = 0;
290 CONSOLE_SCREEN_BUFFER_INFO csbi;
291 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
292 Columns = csbi.dwSize.X;
296 // The terminal always has colors.
297 bool Process::FileDescriptorHasColors(int fd) {
298 return FileDescriptorIsDisplayed(fd);
301 bool Process::StandardOutHasColors() {
302 return FileDescriptorHasColors(1);
305 bool Process::StandardErrHasColors() {
306 return FileDescriptorHasColors(2);
309 static bool UseANSI = false;
310 void Process::UseANSIEscapeCodes(bool enable) {
321 :defaultColor(GetCurrentColor()) {}
322 static unsigned GetCurrentColor() {
323 CONSOLE_SCREEN_BUFFER_INFO csbi;
324 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
325 return csbi.wAttributes;
328 WORD operator()() const { return defaultColor; }
331 DefaultColors defaultColors;
333 WORD fg_color(WORD color) {
334 return color & (FOREGROUND_BLUE | FOREGROUND_GREEN |
335 FOREGROUND_INTENSITY | FOREGROUND_RED);
338 WORD bg_color(WORD color) {
339 return color & (BACKGROUND_BLUE | BACKGROUND_GREEN |
340 BACKGROUND_INTENSITY | BACKGROUND_RED);
344 bool Process::ColorNeedsFlush() {
348 const char *Process::OutputBold(bool bg) {
349 if (UseANSI) return "\033[1m";
351 WORD colors = DefaultColors::GetCurrentColor();
353 colors |= BACKGROUND_INTENSITY;
355 colors |= FOREGROUND_INTENSITY;
356 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
360 const char *Process::OutputColor(char code, bool bold, bool bg) {
361 if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
363 WORD current = DefaultColors::GetCurrentColor();
366 colors = ((code&1) ? BACKGROUND_RED : 0) |
367 ((code&2) ? BACKGROUND_GREEN : 0 ) |
368 ((code&4) ? BACKGROUND_BLUE : 0);
370 colors |= BACKGROUND_INTENSITY;
371 colors |= fg_color(current);
373 colors = ((code&1) ? FOREGROUND_RED : 0) |
374 ((code&2) ? FOREGROUND_GREEN : 0 ) |
375 ((code&4) ? FOREGROUND_BLUE : 0);
377 colors |= FOREGROUND_INTENSITY;
378 colors |= bg_color(current);
380 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
384 static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
385 CONSOLE_SCREEN_BUFFER_INFO info;
386 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
387 return info.wAttributes;
390 const char *Process::OutputReverse() {
391 if (UseANSI) return "\033[7m";
393 const WORD attributes
394 = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
396 const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
397 FOREGROUND_RED | FOREGROUND_INTENSITY;
398 const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
399 BACKGROUND_RED | BACKGROUND_INTENSITY;
400 const WORD color_mask = foreground_mask | background_mask;
402 WORD new_attributes =
403 ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
404 ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
405 ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
406 ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
407 ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
408 ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
409 ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
410 ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
412 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
414 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
418 const char *Process::ResetColor() {
419 if (UseANSI) return "\033[0m";
420 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
424 unsigned Process::GetRandomNumber() {
426 if (!::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
427 CRYPT_VERIFYCONTEXT))
428 report_fatal_error("Could not acquire a cryptographic context");
430 ScopedCryptContext CryptoProvider(HCPC);
432 if (!::CryptGenRandom(CryptoProvider, sizeof(Ret),
433 reinterpret_cast<BYTE *>(&Ret)))
434 report_fatal_error("Could not generate a random number");