16#include "llvm/Config/config.h"
17#include "llvm/Config/llvm-config.h"
22#include <sys/resource.h>
25#if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
28#if defined(HAVE_MALLCTL)
31#ifdef HAVE_MALLOC_MALLOC_H
32#include <malloc/malloc.h>
37#ifdef HAVE_SYS_IOCTL_H
49static std::pair<std::chrono::microseconds, std::chrono::microseconds>
51#if defined(HAVE_GETRUSAGE)
53 ::getrusage(RUSAGE_SELF, &RU);
57#warning Cannot get usage times on this platform
59 return {std::chrono::microseconds::zero(), std::chrono::microseconds::zero()};
64 static_assert(
sizeof(Pid) >=
sizeof(pid_t),
65 "Process::Pid should be big enough to store pid_t");
66 return Pid(::getpid());
72#if defined(HAVE_GETAUXVAL)
73 static const int page_size = ::getauxval(AT_PAGESZ);
74#elif defined(HAVE_GETPAGESIZE)
75 static const int page_size = ::getpagesize();
76#elif defined(HAVE_SYSCONF)
77 static long page_size = ::sysconf(_SC_PAGE_SIZE);
79#error Cannot get the page size on this machine
84 assert(page_size > 0 &&
"Page size cannot be 0");
85 assert((page_size % 1024) == 0 &&
"Page size must be aligned by 1024");
86 return static_cast<unsigned>(page_size);
90#if defined(HAVE_MALLINFO2)
94#elif defined(HAVE_MALLINFO)
98#elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
99 malloc_statistics_t
Stats;
100 malloc_zone_statistics(malloc_default_zone(), &
Stats);
101 return Stats.size_in_use;
102#elif defined(HAVE_MALLCTL)
105 if (mallctl(
"stats.allocated", &alloc, &sz, NULL, 0) == 0)
108#elif defined(HAVE_SBRK)
111 static char *StartOfMemory =
reinterpret_cast<char *
>(::sbrk(0));
112 char *EndOfMemory = (
char *)sbrk(0);
113 if (EndOfMemory != ((
char *)-1) && StartOfMemory != ((
char *)-1))
114 return EndOfMemory - StartOfMemory;
118#warning Cannot get malloc info on this platform
125#if defined(HAVE_GETRUSAGE)
127 if (::getrusage(RUSAGE_SELF, &RU) == 0)
134 std::chrono::nanoseconds &user_time,
135 std::chrono::nanoseconds &sys_time) {
136 elapsed = std::chrono::system_clock::now();
137 std::tie(user_time, sys_time) = getRUsageTimes();
140#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
141#include <mach/mach.h>
149 getrlimit(RLIMIT_CORE, &rlim);
165 rlim.rlim_cur = std::min<rlim_t>(1, rlim.rlim_max);
169 setrlimit(RLIMIT_CORE, &rlim);
171#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
175 mach_msg_type_number_t
Count = 0;
176 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
177 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
178 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
179 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
180 kern_return_t err = task_get_exception_ports(
181 mach_task_self(), EXC_MASK_ALL, OriginalMasks, &
Count, OriginalPorts,
182 OriginalBehaviors, OriginalFlavors);
183 if (err == KERN_SUCCESS) {
185 for (
unsigned i = 0; i !=
Count; ++i)
186 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
187 MACH_PORT_NULL, OriginalBehaviors[i],
192 signal(SIGABRT, _exit);
193 signal(SIGILL, _exit);
194 signal(SIGFPE, _exit);
195 signal(SIGSEGV, _exit);
196 signal(SIGBUS, _exit);
203 std::string NameStr =
Name.str();
204 const char *Val = ::getenv(NameStr.c_str());
207 return std::string(Val);
213 FDCloser(
int &FD) : FD(FD), KeepOpen(
false) {}
214 void keepOpen() { KeepOpen =
true; }
216 if (!KeepOpen && FD >= 0)
221 FDCloser(
const FDCloser &) =
delete;
222 void operator=(
const FDCloser &) =
delete;
231 FDCloser FDC(NullFD);
233 for (
int StandardFD : StandardFDs) {
237 assert(errno &&
"expected errno to be set if fstat failed!");
245 assert(errno == EBADF &&
"expected errno to have EBADF at this point!");
250 auto Open = [&]() { return ::open(
"/dev/null", O_RDWR); };
255 if (NullFD == StandardFD)
257 else if (dup2(NullFD, StandardFD) < 0)
260 return std::error_code();
265 sigset_t FullSet, SavedSet;
266 if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
270#if LLVM_ENABLE_THREADS
271 if (
int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
272 return std::error_code(EC, std::generic_category());
274 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
280 int ErrnoFromClose = 0;
282 ErrnoFromClose = errno;
285#if LLVM_ENABLE_THREADS
286 EC = pthread_sigmask(SIG_SETMASK, &SavedSet,
nullptr);
288 if (sigprocmask(SIG_SETMASK, &SavedSet,
nullptr) < 0)
294 return std::error_code(ErrnoFromClose, std::generic_category());
295 return std::error_code(EC, std::generic_category());
319static unsigned getColumns(
int FileID) {
322 if (
const char *ColumnsStr = std::getenv(
"COLUMNS")) {
323 int Columns = std::atoi(ColumnsStr);
330 unsigned Columns = 0;
332#if defined(HAVE_SYS_IOCTL_H) && !defined(__sun__)
334 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
342 if (!StandardOutIsDisplayed())
345 return getColumns(0);
349 if (!StandardErrIsDisplayed())
352 return getColumns(1);
355static bool terminalHasColors() {
358 if (
const char *TermStr = std::getenv(
"TERM")) {
360 .
Case(
"alacritty",
true)
362 .
Case(
"cygwin",
true)
363 .
Case(
"ghostty",
true)
380 return FileDescriptorIsDisplayed(fd) && terminalHasColors();
401 return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 15];
410#if !HAVE_DECL_ARC4RANDOM
411static unsigned GetRandomNumberSeed() {
413 int urandomFD = open(
"/dev/urandom", O_RDONLY);
415 if (urandomFD != -1) {
419 int count =
read(urandomFD, (
void *)&seed,
sizeof(seed));
424 if (
count ==
sizeof(seed))
430 const auto Now = std::chrono::high_resolution_clock::now();
431 return hash_combine(Now.time_since_epoch().count(), ::getpid());
436#if HAVE_DECL_ARC4RANDOM
439 static int x = (
static_cast<void>(::srand(GetRandomNumberSeed())), 0);
445[[noreturn]]
void Process::ExitNoCleanup(
int RetCode) { _Exit(RetCode); }
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Function Alias Analysis false
block placement Basic Block Placement Stats
static bool coreFilesPrevented
static const char colorcodes[2][2][16][11]
Represent a constant reference to a string, i.e.
A switch()-like statement whose cases are string literals.
StringSwitch & Case(StringLiteral S, T Value)
StringSwitch & StartsWith(StringLiteral S, T Value)
StringSwitch & EndsWith(StringLiteral S, T Value)
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 std::optional< ProcessStatistics > getStatistics()
Return CPU time and peak memory of this process so far, like sys::Wait reports for a child,...
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.
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
decltype(auto) RetryAfterSignal(const FailT &Fail, const Fun &F, const Args &... As)
std::chrono::nanoseconds toDuration(FILETIME Time)
ProcessStatistics toProcessStatistics(const struct rusage &RU)
Convert resource usage of this process or a waited child to statistics.
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.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
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.