1//===- Win32/Process.cpp - Win32 Process Implementation ------- -*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides the Win32 specific implementation of the Process class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Support/Allocator.h"
15#include "llvm/Support/ErrorHandling.h"
16#include "llvm/Support/WindowsError.h"
17#include <malloc.h>
18
19// The Windows.h header must be after LLVM and standard headers.
20#include "WindowsSupport.h"
21
22#include <direct.h>
23#include <io.h>
24#include <psapi.h>
25#include <shellapi.h>
26
27#ifdef __MINGW32__
28 #if (HAVE_LIBPSAPI != 1)
29  #error "libpsapi.a should be present"
30 #endif
31 #if (HAVE_LIBSHELL32 != 1)
32  #error "libshell32.a should be present"
33 #endif
34#else
35 #pragma comment(lib, "psapi.lib")
36 #pragma comment(lib, "shell32.lib")
37#endif
38
39//===----------------------------------------------------------------------===//
40//=== WARNING: Implementation here must contain only Win32 specific code
41//===          and must not be UNIX code
42//===----------------------------------------------------------------------===//
43
44#ifdef __MINGW32__
45// This ban should be lifted when MinGW 1.0+ has defined this value.
46#  define _HEAPOK (-2)
47#endif
48
49using namespace llvm;
50using namespace sys;
51
52process::id_type self_process::get_id() {
53  return GetCurrentProcessId();
54}
55
56static 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
86// 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.
89static unsigned getPageSize() {
90  // GetNativeSystemInfo() provides the physical page size which may differ
91  // from GetSystemInfo() in 32-bit applications running under WOW64.
92  SYSTEM_INFO info;
93  GetNativeSystemInfo(&info);
94  // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
95  // but dwAllocationGranularity.
96  return static_cast<unsigned>(info.dwPageSize);
97}
98
99// 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()) {
102}
103
104
105size_t
106Process::GetMallocUsage()
107{
108  _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;
117}
118
119void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
120                           TimeValue &sys_time) {
121  elapsed = TimeValue::now();
122
123  FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
124  if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
125                      &UserTime) == 0)
126    return;
127
128  user_time = getTimeValueFromFILETIME(UserTime);
129  sys_time = getTimeValueFromFILETIME(KernelTime);
130}
131
132// Some LLVM programs such as bugpoint produce core files as a normal part of
133// their operation. To prevent the disk from filling up, this configuration
134// item does what's necessary to prevent their generation.
135void Process::PreventCoreFiles() {
136  // 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.
146  SetErrorMode(SEM_FAILCRITICALERRORS |
147               SEM_NOGPFAULTERRORBOX |
148               SEM_NOOPENFILEERRORBOX);
149}
150
151/// 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;
156  if (windows::UTF8ToUTF16(Name, NameUTF16))
157    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().
162  SmallVector<wchar_t, MAX_PATH> Buf;
163  size_t Size = MAX_PATH;
164  do {
165    Buf.reserve(Size);
166    Size =
167        GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
168    if (Size == 0)
169      return None;
170
171    // Try again with larger buffer.
172  } while (Size > Buf.capacity());
173  Buf.set_size(Size);
174
175  // Convert the result from UTF-16 to UTF-8.
176  SmallVector<char, MAX_PATH> Res;
177  if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
178    return None;
179  return std::string(Res.data());
180}
181
182static std::error_code windows_error(DWORD E) {
183  return mapWindowsError(E);
184}
185
186static void AllocateAndPush(const SmallVectorImpl<char> &S,
187                            SmallVectorImpl<const char *> &Vector,
188                            SpecificBumpPtrAllocator<char> &Allocator) {
189  char *Buffer = Allocator.Allocate(S.size() + 1);
190  ::memcpy(Buffer, S.data(), S.size());
191  Buffer[S.size()] = '\0';
192  Vector.push_back(Buffer);
193}
194
195/// Convert Arg from UTF-16 to UTF-8 and push it onto Args.
196static std::error_code
197ConvertAndPushArg(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
198                  SpecificBumpPtrAllocator<char> &Allocator) {
199  SmallVector<char, MAX_PATH> ArgString;
200  if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), ArgString))
201    return ec;
202  AllocateAndPush(ArgString, Args, Allocator);
203  return std::error_code();
204}
205
206/// \brief Perform wildcard expansion of Arg, or just push it into Args if it
207/// doesn't have wildcards or doesn't match any files.
208static std::error_code
209WildcardExpand(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
210               SpecificBumpPtrAllocator<char> &Allocator) {
211  if (!wcspbrk(Arg, L"*?")) {
212    // Arg does not contain any wildcard characters. This is the common case.
213    return ConvertAndPushArg(Arg, Args, Allocator);
214  }
215
216  if (wcscmp(Arg, L"/?") == 0 || wcscmp(Arg, L"-?") == 0) {
217    // Don't wildcard expand /?. Always treat it as an option.
218    return ConvertAndPushArg(Arg, Args, Allocator);
219  }
220
221  // Extract any directory part of the argument.
222  SmallVector<char, MAX_PATH> Dir;
223  if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), Dir))
224    return ec;
225  sys::path::remove_filename(Dir);
226  const int DirSize = Dir.size();
227
228  // Search for matching files.
229  WIN32_FIND_DATAW FileData;
230  HANDLE FindHandle = FindFirstFileW(Arg, &FileData);
231  if (FindHandle == INVALID_HANDLE_VALUE) {
232    return ConvertAndPushArg(Arg, Args, Allocator);
233  }
234
235  std::error_code ec;
236  do {
237    SmallVector<char, MAX_PATH> FileName;
238    ec = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
239                              FileName);
240    if (ec)
241      break;
242
243    // Push the filename onto Dir, and remove it afterwards.
244    llvm::sys::path::append(Dir, StringRef(FileName.data(), FileName.size()));
245    AllocateAndPush(Dir, Args, Allocator);
246    Dir.resize(DirSize);
247  } while (FindNextFileW(FindHandle, &FileData));
248
249  FindClose(FindHandle);
250  return ec;
251}
252
253std::error_code
254Process::GetArgumentVector(SmallVectorImpl<const char *> &Args,
255                           ArrayRef<const char *>,
256                           SpecificBumpPtrAllocator<char> &ArgAllocator) {
257  int ArgCount;
258  wchar_t **UnicodeCommandLine =
259      CommandLineToArgvW(GetCommandLineW(), &ArgCount);
260  if (!UnicodeCommandLine)
261    return windows_error(::GetLastError());
262
263  Args.reserve(ArgCount);
264  std::error_code ec;
265
266  for (int i = 0; i < ArgCount; ++i) {
267    ec = WildcardExpand(UnicodeCommandLine[i], Args, ArgAllocator);
268    if (ec)
269      break;
270  }
271
272  LocalFree(UnicodeCommandLine);
273  return ec;
274}
275
276std::error_code Process::FixupStandardFileDescriptors() {
277  return std::error_code();
278}
279
280std::error_code Process::SafelyCloseFileDescriptor(int FD) {
281  if (::close(FD) < 0)
282    return std::error_code(errno, std::generic_category());
283  return std::error_code();
284}
285
286bool Process::StandardInIsUserInput() {
287  return FileDescriptorIsDisplayed(0);
288}
289
290bool Process::StandardOutIsDisplayed() {
291  return FileDescriptorIsDisplayed(1);
292}
293
294bool Process::StandardErrIsDisplayed() {
295  return FileDescriptorIsDisplayed(2);
296}
297
298bool Process::FileDescriptorIsDisplayed(int fd) {
299  DWORD Mode;  // Unused
300  return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
301}
302
303unsigned Process::StandardOutColumns() {
304  unsigned Columns = 0;
305  CONSOLE_SCREEN_BUFFER_INFO csbi;
306  if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
307    Columns = csbi.dwSize.X;
308  return Columns;
309}
310
311unsigned Process::StandardErrColumns() {
312  unsigned Columns = 0;
313  CONSOLE_SCREEN_BUFFER_INFO csbi;
314  if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
315    Columns = csbi.dwSize.X;
316  return Columns;
317}
318
319// The terminal always has colors.
320bool Process::FileDescriptorHasColors(int fd) {
321  return FileDescriptorIsDisplayed(fd);
322}
323
324bool Process::StandardOutHasColors() {
325  return FileDescriptorHasColors(1);
326}
327
328bool Process::StandardErrHasColors() {
329  return FileDescriptorHasColors(2);
330}
331
332static bool UseANSI = false;
333void Process::UseANSIEscapeCodes(bool enable) {
334  UseANSI = enable;
335}
336
337namespace {
338class DefaultColors
339{
340  private:
341    WORD defaultColor;
342  public:
343    DefaultColors()
344     :defaultColor(GetCurrentColor()) {}
345    static unsigned GetCurrentColor() {
346      CONSOLE_SCREEN_BUFFER_INFO csbi;
347      if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
348        return csbi.wAttributes;
349      return 0;
350    }
351    WORD operator()() const { return defaultColor; }
352};
353
354DefaultColors defaultColors;
355}
356
357bool Process::ColorNeedsFlush() {
358  return !UseANSI;
359}
360
361const char *Process::OutputBold(bool bg) {
362  if (UseANSI) return "\033[1m";
363
364  WORD colors = DefaultColors::GetCurrentColor();
365  if (bg)
366    colors |= BACKGROUND_INTENSITY;
367  else
368    colors |= FOREGROUND_INTENSITY;
369  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
370  return 0;
371}
372
373const char *Process::OutputColor(char code, bool bold, bool bg) {
374  if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
375
376  WORD colors;
377  if (bg) {
378    colors = ((code&1) ? BACKGROUND_RED : 0) |
379      ((code&2) ? BACKGROUND_GREEN : 0 ) |
380      ((code&4) ? BACKGROUND_BLUE : 0);
381    if (bold)
382      colors |= BACKGROUND_INTENSITY;
383  } else {
384    colors = ((code&1) ? FOREGROUND_RED : 0) |
385      ((code&2) ? FOREGROUND_GREEN : 0 ) |
386      ((code&4) ? FOREGROUND_BLUE : 0);
387    if (bold)
388      colors |= FOREGROUND_INTENSITY;
389  }
390  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
391  return 0;
392}
393
394static 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() {
401  if (UseANSI) return "\033[7m";
402
403  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
428const char *Process::ResetColor() {
429  if (UseANSI) return "\033[0m";
430  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
431  return 0;
432}
433
434unsigned Process::GetRandomNumber() {
435  HCRYPTPROV HCPC;
436  if (!::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
437                              CRYPT_VERIFYCONTEXT))
438    report_fatal_error("Could not acquire a cryptographic context");
439
440  ScopedCryptContext CryptoProvider(HCPC);
441  unsigned Ret;
442  if (!::CryptGenRandom(CryptoProvider, sizeof(Ret),
443                        reinterpret_cast<BYTE *>(&Ret)))
444    report_fatal_error("Could not generate a random number");
445  return Ret;
446}
447