16#include "llvm/Config/config.h"
25#ifdef HAVE_SYS_RESOURCE_H
26#include <sys/resource.h>
34#if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
37#if defined(HAVE_MALLCTL)
40#ifdef HAVE_MALLOC_MALLOC_H
41#include <malloc/malloc.h>
43#ifdef HAVE_SYS_IOCTL_H
58static std::pair<std::chrono::microseconds, std::chrono::microseconds>
60#if defined(HAVE_GETRUSAGE)
62 ::getrusage(RUSAGE_SELF, &RU);
66#warning Cannot get usage times on this platform
68 return {std::chrono::microseconds::zero(), std::chrono::microseconds::zero()};
73 static_assert(
sizeof(Pid) >=
sizeof(pid_t),
74 "Process::Pid should be big enough to store pid_t");
75 return Pid(::getpid());
81#if defined(HAVE_GETPAGESIZE)
82 static const int page_size = ::getpagesize();
83#elif defined(HAVE_SYSCONF)
84 static long page_size = ::sysconf(_SC_PAGE_SIZE);
86#error Cannot get the page size on this machine
91 return static_cast<unsigned>(page_size);
94size_t Process::GetMallocUsage() {
95#if defined(HAVE_MALLINFO2)
99#elif defined(HAVE_MALLINFO)
103#elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
104 malloc_statistics_t
Stats;
105 malloc_zone_statistics(malloc_default_zone(), &
Stats);
106 return Stats.size_in_use;
107#elif defined(HAVE_MALLCTL)
110 if (mallctl(
"stats.allocated", &alloc, &sz, NULL, 0) == 0)
113#elif defined(HAVE_SBRK)
116 static char *StartOfMemory =
reinterpret_cast<char *
>(::sbrk(0));
117 char *EndOfMemory = (
char *)sbrk(0);
118 if (EndOfMemory != ((
char *)-1) && StartOfMemory != ((
char *)-1))
119 return EndOfMemory - StartOfMemory;
123#warning Cannot get malloc info on this platform
130 std::chrono::nanoseconds &user_time,
131 std::chrono::nanoseconds &sys_time) {
132 elapsed = std::chrono::system_clock::now();
133 std::tie(user_time, sys_time) = getRUsageTimes();
136#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
137#include <mach/mach.h>
143void Process::PreventCoreFiles() {
146 getrlimit(RLIMIT_CORE, &rlim);
162 rlim.rlim_cur = std::min<rlim_t>(1, rlim.rlim_max);
166 setrlimit(RLIMIT_CORE, &rlim);
169#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
173 mach_msg_type_number_t Count = 0;
174 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
175 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
176 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
177 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
178 kern_return_t err = task_get_exception_ports(
179 mach_task_self(), EXC_MASK_ALL, OriginalMasks, &Count, OriginalPorts,
180 OriginalBehaviors, OriginalFlavors);
181 if (err == KERN_SUCCESS) {
183 for (
unsigned i = 0; i != Count; ++i)
184 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
185 MACH_PORT_NULL, OriginalBehaviors[i],
190 signal(SIGABRT, _exit);
191 signal(SIGILL, _exit);
192 signal(SIGFPE, _exit);
193 signal(SIGSEGV, _exit);
194 signal(SIGBUS, _exit);
201 std::string NameStr =
Name.str();
202 const char *Val = ::getenv(NameStr.c_str());
205 return std::string(Val);
211 FDCloser(
int &FD) : FD(FD), KeepOpen(
false) {}
212 void keepOpen() { KeepOpen =
true; }
214 if (!KeepOpen && FD >= 0)
219 FDCloser(
const FDCloser &) =
delete;
220 void operator=(
const FDCloser &) =
delete;
227std::error_code Process::FixupStandardFileDescriptors() {
229 FDCloser FDC(NullFD);
230 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
231 for (
int StandardFD : StandardFDs) {
235 assert(errno &&
"expected errno to be set if fstat failed!");
243 assert(errno == EBADF &&
"expected errno to have EBADF at this point!");
248 auto Open = [&]() { return ::open(
"/dev/null", O_RDWR); };
253 if (NullFD == StandardFD)
255 else if (dup2(NullFD, StandardFD) < 0)
258 return std::error_code();
261std::error_code Process::SafelyCloseFileDescriptor(
int FD) {
263 sigset_t FullSet, SavedSet;
264 if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
268#if LLVM_ENABLE_THREADS
269 if (
int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
270 return std::error_code(EC, std::generic_category());
272 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
278 int ErrnoFromClose = 0;
280 ErrnoFromClose = errno;
283#if LLVM_ENABLE_THREADS
284 EC = pthread_sigmask(SIG_SETMASK, &SavedSet,
nullptr);
286 if (sigprocmask(SIG_SETMASK, &SavedSet,
nullptr) < 0)
292 return std::error_code(ErrnoFromClose, std::generic_category());
293 return std::error_code(EC, std::generic_category());
296bool Process::StandardInIsUserInput() {
297 return FileDescriptorIsDisplayed(STDIN_FILENO);
300bool Process::StandardOutIsDisplayed() {
301 return FileDescriptorIsDisplayed(STDOUT_FILENO);
304bool Process::StandardErrIsDisplayed() {
305 return FileDescriptorIsDisplayed(STDERR_FILENO);
308bool Process::FileDescriptorIsDisplayed(
int fd) {
317static unsigned getColumns() {
319 if (
const char *ColumnsStr = std::getenv(
"COLUMNS")) {
320 int Columns = std::atoi(ColumnsStr);
330unsigned Process::StandardOutColumns() {
331 if (!StandardOutIsDisplayed())
337unsigned Process::StandardErrColumns() {
338 if (!StandardErrIsDisplayed())
344static bool terminalHasColors() {
347 if (
const char *TermStr = std::getenv(
"TERM")) {
350 .
Case(
"cygwin",
true)
363bool Process::FileDescriptorHasColors(
int fd) {
366 return FileDescriptorIsDisplayed(fd) && terminalHasColors();
369bool Process::StandardOutHasColors() {
370 return FileDescriptorHasColors(STDOUT_FILENO);
373bool Process::StandardErrHasColors() {
374 return FileDescriptorHasColors(STDERR_FILENO);
377void Process::UseANSIEscapeCodes(
bool ) {
381bool Process::ColorNeedsFlush() {
386const char *Process::OutputColor(
char code,
bool bold,
bool bg) {
387 return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 15];
390const char *Process::OutputBold(
bool bg) {
return "\033[1m"; }
392const char *Process::OutputReverse() {
return "\033[7m"; }
394const char *Process::ResetColor() {
return "\033[0m"; }
396#if !HAVE_DECL_ARC4RANDOM
397static unsigned GetRandomNumberSeed() {
399 int urandomFD = open(
"/dev/urandom", O_RDONLY);
401 if (urandomFD != -1) {
405 int count =
read(urandomFD, (
void *)&seed,
sizeof(seed));
410 if (count ==
sizeof(seed))
416 const auto Now = std::chrono::high_resolution_clock::now();
417 return hash_combine(Now.time_since_epoch().count(), ::getpid());
422#if HAVE_DECL_ARC4RANDOM
425 static int x = (
static_cast<void>(::srand(GetRandomNumberSeed())), 0);
431[[noreturn]]
void Process::ExitNoCleanup(
int RetCode) { _Exit(RetCode); }
block placement Basic Block Placement Stats
static bool coreFilesPrevented
static const char colorcodes[2][2][16][11]
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Tagged union holding either a T or a Error.
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 unsigned GetRandomNumber()
Get the result of a process wide random number generator.
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.
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...
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.