LLVM  10.0.0
Process.inc
Go to the documentation of this file.
1 //===- Win32/Process.cpp - Win32 Process Implementation ------- -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file provides the Win32 specific implementation of the Process class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Support/Allocator.h"
19 #include <malloc.h>
20 
21 // The Windows.h header must be after LLVM and standard headers.
23 
24 #include <direct.h>
25 #include <io.h>
26 #include <psapi.h>
27 #include <shellapi.h>
28 
29 #if !defined(__MINGW32__)
30  #pragma comment(lib, "psapi.lib")
31  #pragma comment(lib, "shell32.lib")
32 #endif
33 
34 //===----------------------------------------------------------------------===//
35 //=== WARNING: Implementation here must contain only Win32 specific code
36 //=== and must not be UNIX code
37 //===----------------------------------------------------------------------===//
38 
39 #ifdef __MINGW32__
40 // This ban should be lifted when MinGW 1.0+ has defined this value.
41 # define _HEAPOK (-2)
42 #endif
43 
44 using namespace llvm;
45 
46 // This function retrieves the page size using GetNativeSystemInfo() and is
47 // present solely so it can be called once to initialize the self_process member
48 // below.
49 static unsigned computePageSize() {
50  // GetNativeSystemInfo() provides the physical page size which may differ
51  // from GetSystemInfo() in 32-bit applications running under WOW64.
52  SYSTEM_INFO info;
53  GetNativeSystemInfo(&info);
54  // FIXME: FileOffset in MapViewOfFile() should be aligned to not dwPageSize,
55  // but dwAllocationGranularity.
56  return static_cast<unsigned>(info.dwPageSize);
57 }
58 
60  static unsigned Ret = computePageSize();
61  return Ret;
62 }
63 
64 size_t
66 {
67  _HEAPINFO hinfo;
68  hinfo._pentry = NULL;
69 
70  size_t size = 0;
71 
72  while (_heapwalk(&hinfo) == _HEAPOK)
73  size += hinfo._size;
74 
75  return size;
76 }
77 
78 void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
79  std::chrono::nanoseconds &sys_time) {
80  elapsed = std::chrono::system_clock::now();;
81 
82  FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
83  if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
84  &UserTime) == 0)
85  return;
86 
87  user_time = toDuration(UserTime);
88  sys_time = toDuration(KernelTime);
89 }
90 
91 // Some LLVM programs such as bugpoint produce core files as a normal part of
92 // their operation. To prevent the disk from filling up, this configuration
93 // item does what's necessary to prevent their generation.
95  // Windows does have the concept of core files, called minidumps. However,
96  // disabling minidumps for a particular application extends past the lifetime
97  // of that application, which is the incorrect behavior for this API.
98  // Additionally, the APIs require elevated privileges to disable and re-
99  // enable minidumps, which makes this untenable. For more information, see
100  // WerAddExcludedApplication and WerRemoveExcludedApplication (Vista and
101  // later).
102  //
103  // Windows also has modal pop-up message boxes. As this method is used by
104  // bugpoint, preventing these pop-ups is additionally important.
105  SetErrorMode(SEM_FAILCRITICALERRORS |
106  SEM_NOGPFAULTERRORBOX |
107  SEM_NOOPENFILEERRORBOX);
108 
109  coreFilesPrevented = true;
110 }
111 
112 /// Returns the environment variable \arg Name's value as a string encoded in
113 /// UTF-8. \arg Name is assumed to be in UTF-8 encoding.
115  // Convert the argument to UTF-16 to pass it to _wgetenv().
116  SmallVector<wchar_t, 128> NameUTF16;
117  if (windows::UTF8ToUTF16(Name, NameUTF16))
118  return None;
119 
120  // Environment variable can be encoded in non-UTF8 encoding, and there's no
121  // way to know what the encoding is. The only reliable way to look up
122  // multibyte environment variable is to use GetEnvironmentVariableW().
124  size_t Size = MAX_PATH;
125  do {
126  Buf.reserve(Size);
127  SetLastError(NO_ERROR);
128  Size =
129  GetEnvironmentVariableW(NameUTF16.data(), Buf.data(), Buf.capacity());
130  if (Size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
131  return None;
132 
133  // Try again with larger buffer.
134  } while (Size > Buf.capacity());
135  Buf.set_size(Size);
136 
137  // Convert the result from UTF-16 to UTF-8.
139  if (windows::UTF16ToUTF8(Buf.data(), Size, Res))
140  return None;
141  return std::string(Res.data());
142 }
143 
144 /// Perform wildcard expansion of Arg, or just push it into Args if it doesn't
145 /// have wildcards or doesn't match any files.
146 static std::error_code WildcardExpand(StringRef Arg,
148  StringSaver &Saver) {
149  std::error_code EC;
150 
151  // Don't expand Arg if it does not contain any wildcard characters. This is
152  // the common case. Also don't wildcard expand /?. Always treat it as an
153  // option.
154  if (Arg.find_first_of("*?") == StringRef::npos || Arg == "/?" ||
155  Arg == "-?") {
156  Args.push_back(Arg.data());
157  return EC;
158  }
159 
160  // Convert back to UTF-16 so we can call FindFirstFileW.
162  EC = windows::UTF8ToUTF16(Arg, ArgW);
163  if (EC)
164  return EC;
165 
166  // Search for matching files.
167  // FIXME: This assumes the wildcard is only in the file name and not in the
168  // directory portion of the file path. For example, it doesn't handle
169  // "*\foo.c" nor "s?c\bar.cpp".
170  WIN32_FIND_DATAW FileData;
171  HANDLE FindHandle = FindFirstFileW(ArgW.data(), &FileData);
172  if (FindHandle == INVALID_HANDLE_VALUE) {
173  Args.push_back(Arg.data());
174  return EC;
175  }
176 
177  // Extract any directory part of the argument.
180  const int DirSize = Dir.size();
181 
182  do {
183  SmallString<MAX_PATH> FileName;
184  EC = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
185  FileName);
186  if (EC)
187  break;
188 
189  // Append FileName to Dir, and remove it afterwards.
190  llvm::sys::path::append(Dir, FileName);
191  Args.push_back(Saver.save(StringRef(Dir)).data());
192  Dir.resize(DirSize);
193  } while (FindNextFileW(FindHandle, &FileData));
194 
195  FindClose(FindHandle);
196  return EC;
197 }
198 
199 static std::error_code GetExecutableName(SmallVectorImpl<char> &Filename) {
200  // The first argument may contain just the name of the executable (e.g.,
201  // "clang") rather than the full path, so swap it with the full path.
202  wchar_t ModuleName[MAX_PATH];
203  size_t Length = ::GetModuleFileNameW(NULL, ModuleName, MAX_PATH);
204  if (Length == 0 || Length == MAX_PATH) {
205  return mapWindowsError(GetLastError());
206  }
207 
208  // If the first argument is a shortened (8.3) name (which is possible even
209  // if we got the module name), the driver will have trouble distinguishing it
210  // (e.g., clang.exe v. clang++.exe), so expand it now.
211  Length = GetLongPathNameW(ModuleName, ModuleName, MAX_PATH);
212  if (Length == 0)
213  return mapWindowsError(GetLastError());
214  if (Length > MAX_PATH) {
215  // We're not going to try to deal with paths longer than MAX_PATH, so we'll
216  // treat this as an error. GetLastError() returns ERROR_SUCCESS, which
217  // isn't useful, so we'll hardcode an appropriate error value.
218  return mapWindowsError(ERROR_INSUFFICIENT_BUFFER);
219  }
220 
221  std::error_code EC = windows::UTF16ToUTF8(ModuleName, Length, Filename);
222  if (EC)
223  return EC;
224 
225  StringRef Base = sys::path::filename(Filename.data());
226  Filename.assign(Base.begin(), Base.end());
227  return std::error_code();
228 }
229 
230 std::error_code
232  BumpPtrAllocator &Alloc) {
233  const wchar_t *CmdW = GetCommandLineW();
234  assert(CmdW);
235  std::error_code EC;
237  EC = windows::UTF16ToUTF8(CmdW, wcslen(CmdW), Cmd);
238  if (EC)
239  return EC;
240 
242  StringSaver Saver(Alloc);
243  cl::TokenizeWindowsCommandLine(Cmd, Saver, TmpArgs, /*MarkEOLs=*/false);
244 
245  for (const char *Arg : TmpArgs) {
246  EC = WildcardExpand(Arg, Args, Saver);
247  if (EC)
248  return EC;
249  }
250 
251  SmallVector<char, MAX_PATH> Arg0(Args[0], Args[0] + strlen(Args[0]));
254  EC = GetExecutableName(Filename);
255  if (EC)
256  return EC;
257  sys::path::append(Arg0, Filename);
258  Args[0] = Saver.save(Arg0).data();
259  return std::error_code();
260 }
261 
262 std::error_code Process::FixupStandardFileDescriptors() {
263  return std::error_code();
264 }
265 
266 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
267  if (::close(FD) < 0)
268  return std::error_code(errno, std::generic_category());
269  return std::error_code();
270 }
271 
273  return FileDescriptorIsDisplayed(0);
274 }
275 
277  return FileDescriptorIsDisplayed(1);
278 }
279 
281  return FileDescriptorIsDisplayed(2);
282 }
283 
285  DWORD Mode; // Unused
286  return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &Mode) != 0);
287 }
288 
289 unsigned Process::StandardOutColumns() {
290  unsigned Columns = 0;
291  CONSOLE_SCREEN_BUFFER_INFO csbi;
292  if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
293  Columns = csbi.dwSize.X;
294  return Columns;
295 }
296 
297 unsigned Process::StandardErrColumns() {
298  unsigned Columns = 0;
299  CONSOLE_SCREEN_BUFFER_INFO csbi;
300  if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
301  Columns = csbi.dwSize.X;
302  return Columns;
303 }
304 
305 // The terminal always has colors.
307  return FileDescriptorIsDisplayed(fd);
308 }
309 
311  return FileDescriptorHasColors(1);
312 }
313 
315  return FileDescriptorHasColors(2);
316 }
317 
318 static bool UseANSI = false;
319 void Process::UseANSIEscapeCodes(bool enable) {
320 #if defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
321  if (enable) {
322  HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE);
323  DWORD Mode;
324  GetConsoleMode(Console, &Mode);
325  Mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
326  SetConsoleMode(Console, Mode);
327  }
328 #endif
329  UseANSI = enable;
330 }
331 
332 namespace {
333 class DefaultColors
334 {
335  private:
336  WORD defaultColor;
337  public:
338  DefaultColors()
339  :defaultColor(GetCurrentColor()) {}
340  static unsigned GetCurrentColor() {
341  CONSOLE_SCREEN_BUFFER_INFO csbi;
342  if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
343  return csbi.wAttributes;
344  return 0;
345  }
346  WORD operator()() const { return defaultColor; }
347 };
348 
349 DefaultColors defaultColors;
350 
351 WORD fg_color(WORD color) {
352  return color & (FOREGROUND_BLUE | FOREGROUND_GREEN |
353  FOREGROUND_INTENSITY | FOREGROUND_RED);
354 }
355 
356 WORD bg_color(WORD color) {
357  return color & (BACKGROUND_BLUE | BACKGROUND_GREEN |
358  BACKGROUND_INTENSITY | BACKGROUND_RED);
359 }
360 }
361 
363  return !UseANSI;
364 }
365 
366 const char *Process::OutputBold(bool bg) {
367  if (UseANSI) return "\033[1m";
368 
369  WORD colors = DefaultColors::GetCurrentColor();
370  if (bg)
371  colors |= BACKGROUND_INTENSITY;
372  else
373  colors |= FOREGROUND_INTENSITY;
374  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
375  return 0;
376 }
377 
378 const char *Process::OutputColor(char code, bool bold, bool bg) {
379  if (UseANSI) return colorcodes[bg?1:0][bold?1:0][code&7];
380 
381  WORD current = DefaultColors::GetCurrentColor();
382  WORD colors;
383  if (bg) {
384  colors = ((code&1) ? BACKGROUND_RED : 0) |
385  ((code&2) ? BACKGROUND_GREEN : 0 ) |
386  ((code&4) ? BACKGROUND_BLUE : 0);
387  if (bold)
388  colors |= BACKGROUND_INTENSITY;
389  colors |= fg_color(current);
390  } else {
391  colors = ((code&1) ? FOREGROUND_RED : 0) |
392  ((code&2) ? FOREGROUND_GREEN : 0 ) |
393  ((code&4) ? FOREGROUND_BLUE : 0);
394  if (bold)
395  colors |= FOREGROUND_INTENSITY;
396  colors |= bg_color(current);
397  }
398  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
399  return 0;
400 }
401 
402 static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
403  CONSOLE_SCREEN_BUFFER_INFO info;
404  GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info);
405  return info.wAttributes;
406 }
407 
408 const char *Process::OutputReverse() {
409  if (UseANSI) return "\033[7m";
410 
411  const WORD attributes
412  = GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
413 
414  const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
415  FOREGROUND_RED | FOREGROUND_INTENSITY;
416  const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
417  BACKGROUND_RED | BACKGROUND_INTENSITY;
418  const WORD color_mask = foreground_mask | background_mask;
419 
420  WORD new_attributes =
421  ((attributes & FOREGROUND_BLUE )?BACKGROUND_BLUE :0) |
422  ((attributes & FOREGROUND_GREEN )?BACKGROUND_GREEN :0) |
423  ((attributes & FOREGROUND_RED )?BACKGROUND_RED :0) |
424  ((attributes & FOREGROUND_INTENSITY)?BACKGROUND_INTENSITY:0) |
425  ((attributes & BACKGROUND_BLUE )?FOREGROUND_BLUE :0) |
426  ((attributes & BACKGROUND_GREEN )?FOREGROUND_GREEN :0) |
427  ((attributes & BACKGROUND_RED )?FOREGROUND_RED :0) |
428  ((attributes & BACKGROUND_INTENSITY)?FOREGROUND_INTENSITY:0) |
429  0;
430  new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
431 
432  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
433  return 0;
434 }
435 
436 const char *Process::ResetColor() {
437  if (UseANSI) return "\033[0m";
438  SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
439  return 0;
440 }
441 
442 unsigned Process::GetRandomNumber() {
443  HCRYPTPROV HCPC;
444  if (!::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
445  CRYPT_VERIFYCONTEXT))
446  ReportLastErrorFatal("Could not acquire a cryptographic context");
447 
448  ScopedCryptContext CryptoProvider(HCPC);
449  unsigned Ret;
450  if (!::CryptGenRandom(CryptoProvider, sizeof(Ret),
451  reinterpret_cast<BYTE *>(&Ret)))
452  ReportLastErrorFatal("Could not generate a random number");
453  return Ret;
454 }
455 
456 typedef NTSTATUS(WINAPI* RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
457 #define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
458 
460  HMODULE hMod = ::GetModuleHandleW(L"ntdll.dll");
461  if (hMod) {
462  auto getVer = (RtlGetVersionPtr)::GetProcAddress(hMod, "RtlGetVersion");
463  if (getVer) {
464  RTL_OSVERSIONINFOEXW info{};
465  info.dwOSVersionInfoSize = sizeof(info);
466  if (getVer((PRTL_OSVERSIONINFOW)&info) == STATUS_SUCCESS) {
467  return llvm::VersionTuple(info.dwMajorVersion, info.dwMinorVersion, 0,
468  info.dwBuildNumber);
469  }
470  }
471  }
472  return llvm::VersionTuple(0, 0, 0, 0);
473 }
474 
476  // Windows 8 is version 6.2, service pack 0.
477  return GetWindowsOSVersion() >= llvm::VersionTuple(6, 2, 0, 0);
478 }
std::error_code GetCommandLineArguments(SmallVectorImpl< const char *> &Args, BumpPtrAllocator &Alloc)
void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
Definition: Path.cpp:474
SI Whole Quad Mode
This class represents lattice values for constants.
Definition: AllocatorList.h:23
static const char * ResetColor()
Resets the terminals colors, or returns an escape sequence to do so.
static const char * OutputColor(char c, bool bold, bool bg)
This function returns the colorcode escape sequences.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
void push_back(const T &Elt)
Definition: SmallVector.h:211
static bool StandardErrHasColors()
This function determines whether the terminal connected to standard error supports colors...
static bool FileDescriptorHasColors(int fd)
This function determines if the given file descriptor is displayd and supports colors.
static bool FileDescriptorIsDisplayed(int fd)
This function determines if the given file descriptor is connected to a "tty" or "console" window...
void reserve(size_type N)
Definition: SmallVector.h:369
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
static std::error_code FixupStandardFileDescriptors()
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:455
static bool ColorNeedsFlush()
Whether changing colors requires the output to be flushed.
static const char * OutputReverse()
This function returns the escape sequence to reverse forground and background colors.
static const char colorcodes[2][2][8][10]
Definition: Process.cpp:81
Tagged union holding either a T or a Error.
Definition: APFloat.h:41
void TokenizeWindowsCommandLine(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char *> &NewArgv, bool MarkEOLs=false)
Tokenizes a Windows command line which may contain quotes and escaped quotes.
void assign(size_type NumElts, const T &Elt)
Definition: SmallVector.h:412
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:25
static bool StandardInIsUserInput()
This function determines if the standard input is connected directly to a user&#39;s input (keyboard prob...
static bool StandardOutIsDisplayed()
This function determines if the standard output is connected to a "tty" or "console" window...
static void UseANSIEscapeCodes(bool enable)
Enables or disables whether ANSI escape sequences are used to output colors.
static unsigned StandardOutColumns()
This function determines the number of columns in the window if standard output is connected to a "tt...
Allocate memory in an ever growing pool, as if by bump-pointer.
Definition: Allocator.h:141
void set_size(size_t N)
Set the array size to N, which the current array must have enough capacity for.
Definition: SmallVector.h:66
static sys::TimePoint< std::chrono::seconds > now(bool Deterministic)
static bool coreFilesPrevented
Definition: Process.cpp:88
std::error_code mapWindowsError(unsigned EV)
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
size_t capacity() const
Definition: SmallVector.h:53
lazy value info
bool RunningWindows8OrGreater()
Determines if the program is running on Windows 8 or newer.
size_t size() const
Definition: SmallVector.h:52
static size_t GetMallocUsage()
Return process memory usage.
llvm::VersionTuple GetWindowsOSVersion()
Returns the Windows version as Major.Minor.0.BuildNumber.
static bool StandardErrIsDisplayed()
This function determines if the standard error is connected to a "tty" or "console" window...
static void PreventCoreFiles()
This function makes the necessary calls to the operating system to prevent core files or any other ki...
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
Definition: STLExtras.h:1163
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
static unsigned StandardErrColumns()
This function determines the number of columns in the window if standard error is connected to a "tty...
static bool StandardOutHasColors()
This function determines whether the terminal connected to standard output supports colors...
StringRef save(const char *S)
Definition: StringSaver.h:28
iterator begin() const
Definition: StringRef.h:122
static unsigned GetRandomNumber()
Get the result of a process wide random number generator.
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer...
Definition: StringSaver.h:21
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:144
static const size_t npos
Definition: StringRef.h:56
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:588
LLVM_NODISCARD size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:401
uint32_t Size
Definition: Profile.cpp:46
static void GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time, std::chrono::nanoseconds &sys_time)
This static function will set user_time to the amount of CPU time spent in user (non-kernel) mode and...
LLVM_ATTRIBUTE_NORETURN void ReportLastErrorFatal(const char *Msg)
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:143
Deduce and propagate attributes
static const char * OutputBold(bool bg)
Same as OutputColor, but only enables the bold attribute.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static Expected< unsigned > getPageSize()
Get the process&#39;s page size.
static std::error_code SafelyCloseFileDescriptor(int FD)
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:54
std::chrono::nanoseconds toDuration(FILETIME Time)
iterator end() const
Definition: StringRef.h:124
static Optional< std::string > GetEnv(StringRef name)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
void resize(size_type N)
Definition: SmallVector.h:344