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 std::chrono::nanoseconds &user_time,
126 std::chrono::nanoseconds &sys_time) {
127 elapsed = std::chrono::system_clock::now();
128 std::tie(user_time, sys_time) = getRUsageTimes();
131#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
132#include <mach/mach.h>
140 getrlimit(RLIMIT_CORE, &rlim);
156 rlim.rlim_cur = std::min<rlim_t>(1, rlim.rlim_max);
160 setrlimit(RLIMIT_CORE, &rlim);
162#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
166 mach_msg_type_number_t
Count = 0;
167 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
168 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
169 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
170 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
171 kern_return_t err = task_get_exception_ports(
172 mach_task_self(), EXC_MASK_ALL, OriginalMasks, &
Count, OriginalPorts,
173 OriginalBehaviors, OriginalFlavors);
174 if (err == KERN_SUCCESS) {
176 for (
unsigned i = 0; i !=
Count; ++i)
177 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
178 MACH_PORT_NULL, OriginalBehaviors[i],
183 signal(SIGABRT, _exit);
184 signal(SIGILL, _exit);
185 signal(SIGFPE, _exit);
186 signal(SIGSEGV, _exit);
187 signal(SIGBUS, _exit);
194 std::string NameStr =
Name.str();
195 const char *Val = ::getenv(NameStr.c_str());
198 return std::string(Val);
204 FDCloser(
int &FD) : FD(FD), KeepOpen(
false) {}
205 void keepOpen() { KeepOpen =
true; }
207 if (!KeepOpen && FD >= 0)
212 FDCloser(
const FDCloser &) =
delete;
213 void operator=(
const FDCloser &) =
delete;
222 FDCloser FDC(NullFD);
224 for (
int StandardFD : StandardFDs) {
228 assert(errno &&
"expected errno to be set if fstat failed!");
236 assert(errno == EBADF &&
"expected errno to have EBADF at this point!");
241 auto Open = [&]() { return ::open(
"/dev/null", O_RDWR); };
246 if (NullFD == StandardFD)
248 else if (dup2(NullFD, StandardFD) < 0)
251 return std::error_code();
256 sigset_t FullSet, SavedSet;
257 if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
261#if LLVM_ENABLE_THREADS
262 if (
int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
263 return std::error_code(EC, std::generic_category());
265 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
271 int ErrnoFromClose = 0;
273 ErrnoFromClose = errno;
276#if LLVM_ENABLE_THREADS
277 EC = pthread_sigmask(SIG_SETMASK, &SavedSet,
nullptr);
279 if (sigprocmask(SIG_SETMASK, &SavedSet,
nullptr) < 0)
285 return std::error_code(ErrnoFromClose, std::generic_category());
286 return std::error_code(EC, std::generic_category());
310static unsigned getColumns(
int FileID) {
313 if (
const char *ColumnsStr = std::getenv(
"COLUMNS")) {
314 int Columns = std::atoi(ColumnsStr);
321 unsigned Columns = 0;
323#if defined(HAVE_SYS_IOCTL_H) && !defined(__sun__)
325 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
333 if (!StandardOutIsDisplayed())
336 return getColumns(0);
340 if (!StandardErrIsDisplayed())
343 return getColumns(1);
346static bool terminalHasColors() {
349 if (
const char *TermStr = std::getenv(
"TERM")) {
352 .
Case(
"cygwin",
true)
368 return FileDescriptorIsDisplayed(fd) && terminalHasColors();
389 return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 15];
398#if !HAVE_DECL_ARC4RANDOM
399static unsigned GetRandomNumberSeed() {
401 int urandomFD = open(
"/dev/urandom", O_RDONLY);
403 if (urandomFD != -1) {
407 int count =
read(urandomFD, (
void *)&seed,
sizeof(seed));
412 if (
count ==
sizeof(seed))
418 const auto Now = std::chrono::high_resolution_clock::now();
419 return hash_combine(Now.time_since_epoch().count(), ::getpid());
424#if HAVE_DECL_ARC4RANDOM
427 static int x = (
static_cast<void>(::srand(GetRandomNumberSeed())), 0);
433[[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]
StringRef - 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 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)
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.
FunctionAddr 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.