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