30#if !defined(__MINGW32__)
31#pragma comment(lib, "psapi.lib")
32#if !LLVM_WINDOWS_RESTRICTED_APIS
33#pragma comment(lib, "shell32.lib")
45 static_assert(
sizeof(Pid) >=
sizeof(DWORD),
46 "Process::Pid should be big enough to store DWORD");
47 return Pid(::GetCurrentProcessId());
53static unsigned computePageSize() {
57 GetNativeSystemInfo(&
info);
60 return static_cast<unsigned>(
info.dwPageSize);
64 static unsigned Ret = computePageSize();
74 while (_heapwalk(&hinfo) == _HEAPOK)
81 std::chrono::nanoseconds &user_time,
82 std::chrono::nanoseconds &sys_time) {
83 elapsed = std::chrono::system_clock::now();
86 FILETIME ProcCreate, ProcExit, KernelTime, UserTime;
87 if (GetProcessTimes(GetCurrentProcess(), &ProcCreate, &ProcExit, &KernelTime,
109 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
110 SEM_NOOPENFILEERRORBOX);
120 if (windows::UTF8ToUTF16(Name, NameUTF16))
127 size_t Size = MAX_PATH;
130 SetLastError(NO_ERROR);
132 if (
Size == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
141 if (windows::UTF16ToUTF8(Buf.
data(),
Size, Res))
143 return std::string(Res.
data());
148static std::error_code WildcardExpand(
StringRef Arg,
165 EC = windows::UTF8ToUTF16(Arg, ArgW);
173 WIN32_FIND_DATAW FileData;
174 HANDLE FindHandle = ::FindFirstFileExW(ArgW.
data(), FindExInfoBasic,
175 &FileData, FindExSearchNameMatch, NULL,
176 FIND_FIRST_EX_LARGE_FETCH);
177 if (FindHandle == INVALID_HANDLE_VALUE) {
185 const int DirSize = Dir.
size();
189 EC = windows::UTF16ToUTF8(FileData.cFileName, wcslen(FileData.cFileName),
198 }
while (FindNextFileW(FindHandle, &FileData));
200 FindClose(FindHandle);
233 return std::error_code();
239 const wchar_t *CmdW = GetCommandLineW();
243 EC = windows::UTF16ToUTF8(CmdW, wcslen(CmdW), Cmd);
251 for (
const char *Arg : TmpArgs) {
252 EC = WildcardExpand(Arg, Args, Saver);
257 if (
Args.size() == 0)
258 return std::make_error_code(std::errc::invalid_argument);
269 return std::error_code();
273 return std::error_code();
279 return std::error_code();
290 return (GetConsoleMode((HANDLE)_get_osfhandle(fd), &
Mode) != 0);
294 unsigned Columns = 0;
295 CONSOLE_SCREEN_BUFFER_INFO csbi;
296 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
297 Columns = csbi.dwSize.X;
302 unsigned Columns = 0;
303 CONSOLE_SCREEN_BUFFER_INFO csbi;
304 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &csbi))
305 Columns = csbi.dwSize.X;
311 return FileDescriptorIsDisplayed(fd);
318static bool UseANSI =
false;
320#if defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
322 HANDLE Console = GetStdHandle(STD_OUTPUT_HANDLE);
324 GetConsoleMode(Console, &
Mode);
325 Mode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
326 SetConsoleMode(Console,
Mode);
338 DefaultColors() : defaultColor(GetCurrentColor()) {}
339 static unsigned GetCurrentColor() {
340 CONSOLE_SCREEN_BUFFER_INFO csbi;
341 if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi))
342 return csbi.wAttributes;
345 WORD operator()()
const {
return defaultColor; }
348DefaultColors defaultColors;
350WORD fg_color(WORD color) {
351 return color & (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY |
355WORD bg_color(WORD color) {
356 return color & (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_INTENSITY |
367 WORD colors = DefaultColors::GetCurrentColor();
369 colors |= BACKGROUND_INTENSITY;
371 colors |= FOREGROUND_INTENSITY;
372 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
378 return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 15];
380 WORD current = DefaultColors::GetCurrentColor();
383 colors = ((code & 1) ? BACKGROUND_RED : 0) |
384 ((code & 2) ? BACKGROUND_GREEN : 0) |
385 ((code & 4) ? BACKGROUND_BLUE : 0);
387 colors |= BACKGROUND_INTENSITY;
388 colors |= fg_color(current);
390 colors = ((code & 1) ? FOREGROUND_RED : 0) |
391 ((code & 2) ? FOREGROUND_GREEN : 0) |
392 ((code & 4) ? FOREGROUND_BLUE : 0);
394 colors |= FOREGROUND_INTENSITY;
395 colors |= bg_color(current);
397 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), colors);
401static WORD GetConsoleTextAttribute(HANDLE hConsoleOutput) {
402 CONSOLE_SCREEN_BUFFER_INFO
info;
403 GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &
info);
404 return info.wAttributes;
411 const WORD attributes =
412 GetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE));
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;
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) | 0;
429 new_attributes = (attributes & ~color_mask) | (new_attributes & color_mask);
431 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), new_attributes);
438 SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), defaultColors());
442static unsigned GetRandomNumberSeed() {
446 GetSystemTimeAsFileTime(&Time);
447 DWORD Pid = GetCurrentProcessId();
448 return hash_combine(Time.dwHighDateTime, Time.dwLowDateTime, Pid);
451static unsigned GetPseudoRandomNumber() {
455 static int x = (
static_cast<void>(::srand(GetRandomNumberSeed())), 0);
463 if (::CryptAcquireContextW(&HCPC, NULL, NULL, PROV_RSA_FULL,
464 CRYPT_VERIFYCONTEXT)) {
467 if (::CryptGenRandom(CryptoProvider,
sizeof(Ret),
468 reinterpret_cast<BYTE *
>(&Ret)))
473 return GetPseudoRandomNumber();
476typedef NTSTATUS(WINAPI *RtlGetVersionPtr)(PRTL_OSVERSIONINFOW);
477#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
479static RTL_OSVERSIONINFOEXW GetWindowsVer() {
480 auto getVer = []() -> RTL_OSVERSIONINFOEXW {
481 HMODULE hMod = ::GetModuleHandleW(L
"ntdll.dll");
485 (RtlGetVersionPtr)(
void *)::GetProcAddress(hMod,
"RtlGetVersion");
488 RTL_OSVERSIONINFOEXW
info{};
489 info.dwOSVersionInfoSize =
sizeof(
info);
490 NTSTATUS r = getVer((PRTL_OSVERSIONINFOW)&
info);
492 assert(r == STATUS_SUCCESS);
496 static RTL_OSVERSIONINFOEXW
info = getVer();
501 RTL_OSVERSIONINFOEXW
info = GetWindowsVer();
512 RTL_OSVERSIONINFOEXW
info = GetWindowsVer();
517 if (
info.wProductType == VER_NT_SERVER)
524[[noreturn]]
void Process::ExitNoCleanup(
int RetCode) {
525 TerminateProcess(GetCurrentProcess(), RetCode);
538 size_t Size = MAX_PATH;
541 SetLastError(NO_ERROR);
551 Buf.
append(lpModuleName, lpModuleName + std::wcslen(lpModuleName));
554 return ::GetModuleHandleW(Buf.
data());
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file defines the BumpPtrAllocator interface.
static constexpr StringLiteral Filename
static bool coreFilesPrevented
static const char colorcodes[2][2][16][11]
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
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 append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void truncate(size_type N)
Like resize, but requires that N is less than size().
void push_back(const T &Elt)
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.
Represent a constant reference to a string, i.e.
static constexpr size_t npos
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
constexpr const char * data() const
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]]].
static LLVM_ABI void UseANSIEscapeCodes(bool enable)
Enables or disables whether ANSI escape sequences are used to output colors.
static LLVM_ABI std::error_code SafelyCloseFileDescriptor(int FD)
static LLVM_ABI 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...
static LLVM_ABI std::error_code FixupStandardFileDescriptors()
static LLVM_ABI Pid getProcessId()
Get the process's identifier.
static LLVM_ABI size_t GetMallocUsage()
Return process memory usage.
static LLVM_ABI bool ColorNeedsFlush()
Whether changing colors requires the output to be flushed.
static LLVM_ABI const char * ResetColor()
Resets the terminals colors, or returns an escape sequence to do so.
static LLVM_ABI unsigned GetRandomNumber()
Get the result of a process wide random number generator.
static LLVM_ABI bool FileDescriptorIsDisplayed(int fd)
This function determines if the given file descriptor is connected to a "tty" or "console" window.
static LLVM_ABI Expected< unsigned > getPageSize()
Get the process's page size.
static LLVM_ABI const char * OutputColor(char c, bool bold, bool bg)
This function returns the colorcode escape sequences.
static LLVM_ABI const char * OutputBold(bool bg)
Same as OutputColor, but only enables the bold attribute.
static LLVM_ABI unsigned StandardErrColumns()
This function determines the number of columns in the window if standard error is connected to a "tty...
static LLVM_ABI std::optional< std::string > GetEnv(StringRef name)
static LLVM_ABI bool FileDescriptorHasColors(int fd)
This function determines if the given file descriptor is displayd and supports colors.
static LLVM_ABI bool StandardInIsUserInput()
This function determines if the standard input is connected directly to a user's input (keyboard prob...
static LLVM_ABI void PreventCoreFiles()
This function makes the necessary calls to the operating system to prevent core files or any other ki...
static LLVM_ABI bool StandardErrHasColors()
This function determines whether the terminal connected to standard error supports colors.
static LLVM_ABI const char * OutputReverse()
This function returns the escape sequence to reverse forground and background colors.
static LLVM_ABI bool StandardErrIsDisplayed()
This function determines if the standard error is connected to a "tty" or "console" window.
static LLVM_ABI bool StandardOutHasColors()
This function determines whether the terminal connected to standard output supports colors.
static LLVM_ABI unsigned StandardOutColumns()
This function determines the number of columns in the window if standard output is connected to a "tt...
static LLVM_ABI bool StandardOutIsDisplayed()
This function determines if the standard output is connected to a "tty" or "console" window.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
LLVM_ABI void TokenizeWindowsCommandLineFull(StringRef Source, StringSaver &Saver, SmallVectorImpl< const char * > &NewArgv, bool MarkEOLs=false)
Tokenizes a Windows full command line, including command name at the start.
LLVM_ABI void remove_filename(SmallVectorImpl< char > &path, Style style=Style::native)
Remove the last component from path unless it is the root dir.
void make_preferred(SmallVectorImpl< char > &path, Style style=Style::native)
For Windows path styles, convert path to use the preferred path separators.
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
LLVM_ABI HMODULE loadSystemModuleSecure(LPCWSTR lpModuleName)
Retrieves the handle to a in-memory system module such as ntdll.dll, while ensuring we're not retriev...
LLVM_ABI std::error_code GetCommandLineArguments(SmallVectorImpl< const char * > &Args, BumpPtrAllocator &Alloc)
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.
LLVM_ABI bool RunningWindows8OrGreater()
Determines if the program is running on Windows 8 or newer.
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.
ScopedHandle< CryptContextTraits > ScopedCryptContext
LLVM_ABI llvm::VersionTuple GetWindowsOSVersion()
Returns the Windows version as Major.Minor.0.BuildNumber.
LLVM_ABI bool RunningWindows11OrGreater()
Determines if the program is running on Windows 11 or Windows Server 2022.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI std::error_code mapWindowsError(unsigned EV)
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.
BumpPtrAllocatorImpl<> BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.