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;
50
51// This function retrieves the page size using GetNativeSystemInfo() and is
52// present solely so it can be called once to initialize the self_process member
53// below.
54static unsigned computePageSize() {
55  // GetNativeSystemInfo() provides the physical page size which may differ
56  // from GetSystemInfo() in 32-bit applications running under WOW64.
57  SYSTEM_INFO info;
58  GetNativeSystemInfo(&info);
59  // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
60  // but dwAllocationGranularity.
61  return static_cast<unsigned>(info.dwPageSize);
62}
63
64unsigned Process::getPageSize() {
65  static unsigned Ret = computePageSize();
66  return Ret;
67}
68
69size_t
70Process::GetMallocUsage()
71{
72  _HEAPINFO hinfo;
73  hinfo._pentry = NULL;
74
75  size_t size = 0;
76
77  while (_heapwalk(&hinfo) == _HEAPOK)
78    size += hinfo._size;
79
80  return size;
81}
82
83void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
84                           std::chrono::nanoseconds &sys_time) {
85  elapsed = std::chrono::system_clock::now();;
86
87  FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
88  if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
89                      &UserTime) == 0)
90    return;
91
92  user_time = toDuration(UserTime);
93  sys_time = toDuration(KernelTime);
94}
95
96// Some LLVM programs such as bugpoint produce core files as a normal part of
97// their operation. To prevent the disk from filling up, this configuration
98// item does what's necessary to prevent their generation.
99void Process::PreventCoreFiles() {
100  // Windows does have the concept of core files, called minidumps.  However,
101  // disabling minidumps for a particular application extends past the lifetime
102  // of that application, which is the incorrect behavior for this API.
103  // Additionally, the APIs require elevated privileges to disable and re-
104  // enable minidumps, which makes this untenable. For more information, see
105  // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
106  // later).
107  //
108  // Windows also has modal pop-up message boxes.  As this method is used by
109  // bugpoint, preventing these pop-ups is additionally important.
110  SetErrorMode(SEM_FAILCRITICALERRORS |
111               SEM_NOGPFAULTERRORBOX |
112               SEM_NOOPENFILEERRORBOX);
113
114  coreFilesPrevented = true;
115}
116
117/// Returns the environment variable \arg Name's value as a string encoded in
118/// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
119Optional<std::string> Process::GetEnv(StringRef Name) {
120  // Convert the argument to UTF-16 to pass it to _wgetenv().
121  SmallVector<wchar_t, 128> NameUTF16;
122  if (windows::UTF8ToUTF16(Name, NameUTF16))
123    return None;
124
125  // Environment variable can be encoded in non-UTF8 encoding, and there's no
126  // way to know what the encoding is. The only reliable way to look up
127  // multibyte environment variable is to use GetEnvironmentVariableW().
128  SmallVector<wchar_t, MAX_PATH> Buf;
129  size_t Size = MAX_PATH;
130  do {
131    Buf.reserve(Size);
132    Size =
133        GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
134    if (Size == 0)
135      return None;
136
137    // Try again with larger buffer.
138  } while (Size > Buf.capacity());
139  Buf.set_size(Size);
140
141  // Convert the result from UTF-16 to UTF-8.
142  SmallVector<char, MAX_PATH> Res;
143  if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
144    return None;
145  return std::string(Res.data());
146}
147
148static void AllocateAndPush(const SmallVectorImpl<char> &S,
149                            SmallVectorImpl<const char *> &Vector,
150                            SpecificBumpPtrAllocator<char> &Allocator) {
151  char *Buffer = Allocator.Allocate(S.size() + 1);
152  ::memcpy(Buffer, S.data(), S.size());
153  Buffer[S.size()] = '\0';
154  Vector.push_back(Buffer);
155}
156
157/// Convert Arg from UTF-16 to UTF-8 and push it onto Args.
158static std::error_code
159ConvertAndPushArg(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
160                  SpecificBumpPtrAllocator<char> &Allocator) {
161  SmallVector<char, MAX_PATH> ArgString;
162  if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), ArgString))
163    return ec;
164  AllocateAndPush(ArgString, Args, Allocator);
165  return std::error_code();
166}
167
168/// \brief Perform wildcard expansion of Arg, or just push it into Args if it
169/// doesn't have wildcards or doesn't match any files.
170static std::error_code
171WildcardExpand(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
172               SpecificBumpPtrAllocator<char> &Allocator) {
173  if (!wcspbrk(Arg, L"*?")) {
174    // Arg does not contain any wildcard characters. This is the common case.
175    return ConvertAndPushArg(Arg, Args, Allocator);
176  }
177
178  if (wcscmp(Arg, L"/?") == 0 || wcscmp(Arg, L"-?") == 0) {
179    // Don't wildcard expand /?. Always treat it as an option.
180    return ConvertAndPushArg(Arg, Args, Allocator);
181  }
182
183  // Extract any directory part of the argument.
184  SmallVector<char, MAX_PATH> Dir;
185  if (std::error_code ec = windows::UTF16ToUTF8(Arg, wcslen(Arg), Dir))
186    return ec;
187  sys::path::remove_filename(Dir);
188  const int DirSize = Dir.size();
189
190  // Search for matching files.
191  // FIXME:  This assumes the wildcard is only in the file name and not in the
192  // directory portion of the file path.  For example, it doesn't handle
193  // "*\foo.c" nor "s?c\bar.cpp".
194  WIN32_FIND_DATAW FileData;
195  HANDLE FindHandle = FindFirstFileW(Arg, &FileData);
196  if (FindHandle == INVALID_HANDLE_VALUE) {
197    return ConvertAndPushArg(Arg, Args, Allocator);
198  }
199
200  std::error_code ec;
201  do {
202    SmallVector<char, MAX_PATH> FileName;
203    ec = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
204                              FileName);
205    if (ec)
206      break;
207
208    // Append FileName to Dir, and remove it afterwards.
209    llvm::sys::path::append(Dir, StringRef(FileName.data(), FileName.size()));
210    AllocateAndPush(Dir, Args, Allocator);
211    Dir.resize(DirSize);
212  } while (FindNextFileW(FindHandle, &FileData));
213
214  FindClose(FindHandle);
215  return ec;
216}
217
218static std::error_code
219ExpandShortFileName(const wchar_t *Arg, SmallVectorImpl<const char *> &Args,
220                    SpecificBumpPtrAllocator<char> &Allocator) {
221  SmallVector<wchar_t, MAX_PATH> LongPath;
222  DWORD Length = GetLongPathNameW(Arg, LongPath.data(), LongPath.capacity());
223  if (Length == 0)
224    return mapWindowsError(GetLastError());
225  if (Length > LongPath.capacity()) {
226    // We're not going to try to deal with paths longer than MAX_PATH, so we'll
227    // treat this as an error.  GetLastError() returns ERROR_SUCCESS, which
228    // isn't useful, so we'll hardcode an appropriate error value.
229    return mapWindowsError(ERROR_INSUFFICIENT_BUFFER);
230  }
231  LongPath.set_size(Length);
232  return ConvertAndPushArg(LongPath.data(), Args, Allocator);
233}
234
235std::error_code
236Process::GetArgumentVector(SmallVectorImpl<const char *> &Args,
237                           ArrayRef<const char *>,
238                           SpecificBumpPtrAllocator<char> &ArgAllocator) {
239  int ArgCount;
240  wchar_t **UnicodeCommandLine =
241      CommandLineToArgvW(GetCommandLineW(), &ArgCount);
242  if (!UnicodeCommandLine)
243    return mapWindowsError(::GetLastError());
244
245  Args.reserve(ArgCount);
246  std::error_code ec;
247
248  // The first argument may contain just the name of the executable (e.g.,
249  // "clang") rather than the full path, so swap it with the full path.
250  wchar_t ModuleName[MAX_PATH];
251  int Length = ::GetModuleFileNameW(NULL, ModuleName, MAX_PATH);
252  if (0 < Length && Length < MAX_PATH)
253    UnicodeCommandLine[0] = ModuleName;
254
255  // If the first argument is a shortened (8.3) name (which is possible even
256  // if we got the module name), the driver will have trouble distinguishing it
257  // (e.g., clang.exe v. clang++.exe), so expand it now.
258  ec = ExpandShortFileName(UnicodeCommandLine[0], Args, ArgAllocator);
259
260  for (int i = 1; i < ArgCount && !ec; ++i) {
261    ec = WildcardExpand(UnicodeCommandLine[i], Args, ArgAllocator);
262    if (ec)
263      break;
264  }
265
266  LocalFree(UnicodeCommandLine);
267  return ec;
268}
269
270std::error_code Process::FixupStandardFileDescriptors() {
271  return std::error_code();
272}
273
274std::error_code Process::SafelyCloseFileDescriptor(int FD) {
275  if (::close(FD) < 0)
276    return std::error_code(errno, std::generic_category());
277  return std::error_code();
278}
279
280bool Process::StandardInIsUserInput() {
281  return FileDescriptorIsDisplayed(0);
282}
283
284bool Process::StandardOutIsDisplayed() {
285  return FileDescriptorIsDisplayed(1);
286}
287
288bool Process::StandardErrIsDisplayed() {
289  return FileDescriptorIsDisplayed(2);
290}
291
292bool Process::FileDescriptorIsDisplayed(int fd) {
293  DWORD Mode;  // Unused
294  return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
295}
296
297unsigned Process::StandardOutColumns() {
298  unsigned Columns = 0;
299  CONSOLE_SCREEN_BUFFER_INFO csbi;
300  if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
301    Columns = csbi.dwSize.X;
302  return Columns;
303}
304
305unsigned Process::StandardErrColumns() {
306  unsigned Columns = 0;
307  CONSOLE_SCREEN_BUFFER_INFO csbi;
308  if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
309    Columns = csbi.dwSize.X;
310  return Columns;
311}
312
313// The terminal always has colors.
314bool Process::FileDescriptorHasColors(int fd) {
315  return FileDescriptorIsDisplayed(fd);
316}
317
318bool Process::StandardOutHasColors() {
319  return FileDescriptorHasColors(1);
320}
321
322bool Process::StandardErrHasColors() {
323  return FileDescriptorHasColors(2);
324}
325
326static bool UseANSI = false;
327void Process::UseANSIEscapeCodes(bool enable) {
328  UseANSI = enable;
329}
330
331namespace {
332class DefaultColors
333{
334  private:
335    WORD defaultColor;
336  public:
337    DefaultColors()
338     :defaultColor(GetCurrentColor()) {}
339    static unsigned GetCurrentColor() {
340      CONSOLE_SCREEN_BUFFER_INFO csbi;
341      if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
342        return csbi.wAttributes;
343      return 0;
344    }
345    WORD operator()() const { return defaultColor; }
346};
347
348DefaultColors defaultColors;
349
350WORD fg_color(WORD color) {
351  return color & (FOREGROUND_BLUE | FOREGROUND_GREEN |
352                  FOREGROUND_INTENSITY | FOREGROUND_RED);
353}
354
355WORD bg_color(WORD color) {
356  return color & (BACKGROUND_BLUE | BACKGROUND_GREEN |
357                  BACKGROUND_INTENSITY | BACKGROUND_RED);
358}
359}
360
361bool Process::ColorNeedsFlush() {
362  return !UseANSI;
363}
364
365const char *Process::OutputBold(bool bg) {
366  if (UseANSI) return "\033[1m";
367
368  WORD colors = DefaultColors::GetCurrentColor();
369  if (bg)
370    colors |= BACKGROUND_INTENSITY;
371  else
372    colors |= FOREGROUND_INTENSITY;
373  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
374  return 0;
375}
376
377const char *Process::OutputColor(char code, bool bold, bool bg) {
378  if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
379
380  WORD current = DefaultColors::GetCurrentColor();
381  WORD colors;
382  if (bg) {
383    colors = ((code&1) ? BACKGROUND_RED : 0) |
384      ((code&2) ? BACKGROUND_GREEN : 0 ) |
385      ((code&4) ? BACKGROUND_BLUE : 0);
386    if (bold)
387      colors |= BACKGROUND_INTENSITY;
388    colors |= fg_color(current);
389  } else {
390    colors = ((code&1) ? FOREGROUND_RED : 0) |
391      ((code&2) ? FOREGROUND_GREEN : 0 ) |
392      ((code&4) ? FOREGROUND_BLUE : 0);
393    if (bold)
394      colors |= FOREGROUND_INTENSITY;
395    colors |= bg_color(current);
396  }
397  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
398  return 0;
399}
400
401static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
402  CONSOLE_SCREEN_BUFFER_INFO info;
403  GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
404  return info.wAttributes;
405}
406
407const char *Process::OutputReverse() {
408  if (UseANSI) return "\033[7m";
409
410  const WORD attributes
411   = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
412
413  const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
414    FOREGROUND_RED | FOREGROUND_INTENSITY;
415  const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
416    BACKGROUND_RED | BACKGROUND_INTENSITY;
417  const WORD color_mask = foreground_mask | background_mask;
418
419  WORD new_attributes =
420    ((attributes & FOREGROUND_BLUE     )?BACKGROUND_BLUE     :0) |
421    ((attributes & FOREGROUND_GREEN    )?BACKGROUND_GREEN    :0) |
422    ((attributes & FOREGROUND_RED      )?BACKGROUND_RED      :0) |
423    ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
424    ((attributes & BACKGROUND_BLUE     )?FOREGROUND_BLUE     :0) |
425    ((attributes & BACKGROUND_GREEN    )?FOREGROUND_GREEN    :0) |
426    ((attributes & BACKGROUND_RED      )?FOREGROUND_RED      :0) |
427    ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
428    0;
429  new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
430
431  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
432  return 0;
433}
434
435const char *Process::ResetColor() {
436  if (UseANSI) return "\033[0m";
437  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
438  return 0;
439}
440
441// Include GetLastError() in a fatal error message.
442static void ReportLastErrorFatal(const char *Msg) {
443  std::string ErrMsg;
444  MakeErrMsg(&ErrMsg, Msg);
445  report_fatal_error(ErrMsg);
446}
447
448unsigned Process::GetRandomNumber() {
449  HCRYPTPROV HCPC;
450  if (!::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
451                              CRYPT_VERIFYCONTEXT))
452    ReportLastErrorFatal("Could not acquire a cryptographic context");
453
454  ScopedCryptContext CryptoProvider(HCPC);
455  unsigned Ret;
456  if (!::CryptGenRandom(CryptoProvider, sizeof(Ret),
457                        reinterpret_cast<BYTE *>(&Ret)))
458    ReportLastErrorFatal("Could not generate a random number");
459  return Ret;
460}
461