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