30#if !defined(__MINGW32__)
31#pragma comment(lib, "psapi.lib")
32#pragma comment(lib, "shell32.lib")
48 static_assert(
sizeof(Pid) >=
sizeof(DWORD),
49 "Process::Pid should be big enough to store DWORD");
50 return Pid(::GetCurrentProcessId());
56static unsigned computePageSize() {
60 GetNativeSystemInfo(&
info);
63 return static_cast<unsigned>(
info.dwPageSize);
67 static unsigned Ret = computePageSize();
71size_t Process::GetMallocUsage() {
77 while (_heapwalk(&hinfo) == _HEAPOK)
84 std::chrono::nanoseconds &user_time,
85 std::chrono::nanoseconds &sys_time) {
86 elapsed = std::chrono::system_clock::now();
89 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
90 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
101void Process::PreventCoreFiles() {
112 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
113 SEM_NOOPENFILEERRORBOX);
123 if (windows::UTF8ToUTF16(
Name, NameUTF16))
130 size_t Size = MAX_PATH;
133 SetLastError(NO_ERROR);
135 if (
Size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
144 if (windows::UTF16ToUTF8(Buf.
data(),
Size, Res))
146 return std::string(Res.
data());
151static std::error_code WildcardExpand(
StringRef Arg,
160 if (Arg.
find_first_of(
"*?") == StringRef::npos || Arg ==
"/?" ||
168 EC = windows::UTF8ToUTF16(Arg, ArgW);
176 WIN32_FIND_DATAW FileData;
177 HANDLE FindHandle = FindFirstFileW(ArgW.
data(), &FileData);
178 if (FindHandle == INVALID_HANDLE_VALUE) {
185 sys::path::remove_filename(Dir);
186 const int DirSize = Dir.
size();
190 EC = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
199 }
while (FindNextFileW(FindHandle, &FileData));
201 FindClose(FindHandle);
210 if (Length == 0 || Length == MAX_PATH) {
220 if (Length > MAX_PATH) {
227 std::error_code
EC = windows::UTF16ToUTF8(
ModuleName, Length, Filename);
232 std::string
Base = sys::path::filename(
Filename.data()).str();
234 return std::error_code();
240 const wchar_t *CmdW = GetCommandLineW();
244 EC = windows::UTF16ToUTF8(CmdW, wcslen(CmdW), Cmd);
250 cl::TokenizeWindowsCommandLineFull(Cmd, Saver, TmpArgs,
false);
252 for (
const char *Arg : TmpArgs) {
253 EC = WildcardExpand(Arg, Args, Saver);
258 if (
Args.size() == 0)
259 return std::make_error_code(std::errc::invalid_argument);
263 sys::path::remove_filename(Arg0);
264 EC = GetExecutableName(Filename);
267 sys::path::make_preferred(Arg0);
268 sys::path::append(Arg0, Filename);
270 return std::error_code();
273std::error_code Process::FixupStandardFileDescriptors() {
274 return std::error_code();
277std::error_code Process::SafelyCloseFileDescriptor(
int FD) {
280 return std::error_code();
283bool Process::StandardInIsUserInput() {
return FileDescriptorIsDisplayed(0); }
285bool Process::StandardOutIsDisplayed() {
return FileDescriptorIsDisplayed(1); }
287bool Process::StandardErrIsDisplayed() {
return FileDescriptorIsDisplayed(2); }
289bool Process::FileDescriptorIsDisplayed(
int fd) {
291 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &
Mode) != 0);
294unsigned Process::StandardOutColumns() {
295 unsigned Columns = 0;
296 CONSOLE_SCREEN_BUFFER_INFO csbi;
297 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
298 Columns = csbi.dwSize.X;
302unsigned Process::StandardErrColumns() {
303 unsigned Columns = 0;
304 CONSOLE_SCREEN_BUFFER_INFO csbi;
305 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
306 Columns = csbi.dwSize.X;
311bool Process::FileDescriptorHasColors(
int fd) {
312 return FileDescriptorIsDisplayed(fd);
315bool Process::StandardOutHasColors() {
return FileDescriptorHasColors(1); }
317bool Process::StandardErrHasColors() {
return FileDescriptorHasColors(2); }
319static bool UseANSI =
false;
320void Process::UseANSIEscapeCodes(
bool enable) {
321#if defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
323 HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE);
325 GetConsoleMode(Console, &
Mode);
326 Mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
327 SetConsoleMode(Console,
Mode);
339 DefaultColors() : defaultColor(GetCurrentColor()) {}
340 static unsigned GetCurrentColor() {
341 CONSOLE_SCREEN_BUFFER_INFO csbi;
342 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
343 return csbi.wAttributes;
346 WORD operator()()
const {
return defaultColor; }
349DefaultColors defaultColors;
351WORD fg_color(WORD color) {
352 return color & (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY |
356WORD bg_color(WORD color) {
357 return color & (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_INTENSITY |
362bool Process::ColorNeedsFlush() {
return !UseANSI; }
364const char *Process::OutputBold(
bool bg) {
368 WORD colors = DefaultColors::GetCurrentColor();
370 colors |= BACKGROUND_INTENSITY;
372 colors |= FOREGROUND_INTENSITY;
373 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
377const char *Process::OutputColor(
char code,
bool bold,
bool bg) {
379 return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 15];
381 WORD current = DefaultColors::GetCurrentColor();
384 colors = ((code & 1) ? BACKGROUND_RED : 0) |
385 ((code & 2) ? BACKGROUND_GREEN : 0) |
386 ((code & 4) ? BACKGROUND_BLUE : 0);
388 colors |= BACKGROUND_INTENSITY;
389 colors |= fg_color(current);
391 colors = ((code & 1) ? FOREGROUND_RED : 0) |
392 ((code & 2) ? FOREGROUND_GREEN : 0) |
393 ((code & 4) ? FOREGROUND_BLUE : 0);
395 colors |= FOREGROUND_INTENSITY;
396 colors |= bg_color(current);
398 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
402static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
403 CONSOLE_SCREEN_BUFFER_INFO
info;
404 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &
info);
405 return info.wAttributes;
408const char *Process::OutputReverse() {
412 const WORD attributes =
413 GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
415 const WORD foreground_mask = FOREGROUND_BLUE | FOREGROUND_GREEN |
416 FOREGROUND_RED | FOREGROUND_INTENSITY;
417 const WORD background_mask = BACKGROUND_BLUE | BACKGROUND_GREEN |
418 BACKGROUND_RED | BACKGROUND_INTENSITY;
419 const WORD color_mask = foreground_mask | background_mask;
421 WORD new_attributes =
422 ((attributes & FOREGROUND_BLUE) ? BACKGROUND_BLUE : 0) |
423 ((attributes & FOREGROUND_GREEN) ? BACKGROUND_GREEN : 0) |
424 ((attributes & FOREGROUND_RED) ? BACKGROUND_RED : 0) |
425 ((attributes & FOREGROUND_INTENSITY) ? BACKGROUND_INTENSITY : 0) |
426 ((attributes & BACKGROUND_BLUE) ? FOREGROUND_BLUE : 0) |
427 ((attributes & BACKGROUND_GREEN) ? FOREGROUND_GREEN : 0) |
428 ((attributes & BACKGROUND_RED) ? FOREGROUND_RED : 0) |
429 ((attributes & BACKGROUND_INTENSITY) ? FOREGROUND_INTENSITY : 0) | 0;
430 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
432 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
436const char *Process::ResetColor() {
439 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
443static unsigned GetRandomNumberSeed() {
447 GetSystemTimeAsFileTime(&Time);
448 DWORD Pid = GetCurrentProcessId();
449 return hash_combine(Time.dwHighDateTime, Time.dwLowDateTime, Pid);
452static unsigned GetPseudoRandomNumber() {
456 static int x = (
static_cast<void>(::srand(GetRandomNumberSeed())), 0);
461unsigned Process::GetRandomNumber() {
464 if (::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
465 CRYPT_VERIFYCONTEXT)) {
468 if (::CryptGenRandom(CryptoProvider,
sizeof(Ret),
469 reinterpret_cast<BYTE *
>(&Ret)))
474 return GetPseudoRandomNumber();
477typedef NTSTATUS(WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
478#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
480static RTL_OSVERSIONINFOEXW GetWindowsVer() {
481 auto getVer = []() -> RTL_OSVERSIONINFOEXW {
482 HMODULE hMod = ::GetModuleHandleW(L
"ntdll.dll");
486 (RtlGetVersionPtr)(
void *)::GetProcAddress(hMod,
"RtlGetVersion");
489 RTL_OSVERSIONINFOEXW
info{};
490 info.dwOSVersionInfoSize =
sizeof(
info);
491 NTSTATUS r = getVer((PRTL_OSVERSIONINFOW)&
info);
493 assert(r == STATUS_SUCCESS);
497 static RTL_OSVERSIONINFOEXW
info = getVer();
502 RTL_OSVERSIONINFOEXW
info = GetWindowsVer();
513 RTL_OSVERSIONINFOEXW
info = GetWindowsVer();
518 if (
info.wProductType == VER_NT_SERVER)
525[[noreturn]]
void Process::ExitNoCleanup(
int RetCode) {
526 TerminateProcess(GetCurrentProcess(), RetCode);
This file defines the BumpPtrAllocator interface.
static bool coreFilesPrevented
static const char colorcodes[2][2][16][11]
static cl::opt< RegAllocEvictionAdvisorAnalysis::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysis::AdvisorMode::Development, "development", "for training")))
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Allocate memory in an ever growing pool, as if by bump-pointer.
Tagged union holding either a T or a Error.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
StringRef str() const
Explicit conversion to StringRef.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void resize_for_overwrite(size_type N)
Like resize, but T is POD, the new values won't be initialized.
void truncate(size_type N)
Like resize, but requires that N is less than size().
pointer data()
Return a pointer to the vector's buffer, even if empty().
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
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.
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
StringRef save(const char *S)
Represents a version number in the form major[.minor[.subminor[.build]]].
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
std::chrono::nanoseconds toDuration(FILETIME Time)
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
llvm::VersionTuple GetWindowsOSVersion()
Returns the Windows version as Major.Minor.0.BuildNumber.
bool RunningWindows8OrGreater()
Determines if the program is running on Windows 8 or newer.
bool RunningWindows11OrGreater()
Determines if the program is running on Windows 11 or Windows Server 2022.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
std::error_code mapWindowsError(unsigned EV)