16#include "llvm/Config/config.h"
17#include "llvm/Config/llvm-config.h"
26#ifdef HAVE_SYS_RESOURCE_H
27#include <sys/resource.h>
35#if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
38#if defined(HAVE_MALLCTL)
41#ifdef HAVE_MALLOC_MALLOC_H
42#include <malloc/malloc.h>
44#ifdef HAVE_SYS_IOCTL_H
59static std::pair<std::chrono::microseconds, std::chrono::microseconds>
61#if defined(HAVE_GETRUSAGE)
63 ::getrusage(RUSAGE_SELF, &RU);
67#warning Cannot get usage times on this platform
69 return {std::chrono::microseconds::zero(), std::chrono::microseconds::zero()};
74 static_assert(
sizeof(Pid) >=
sizeof(pid_t),
75 "Process::Pid should be big enough to store pid_t");
76 return Pid(::getpid());
82#if defined(HAVE_GETPAGESIZE)
83 static const int page_size = ::getpagesize();
84#elif defined(HAVE_SYSCONF)
85 static long page_size = ::sysconf(_SC_PAGE_SIZE);
87#error Cannot get the page size on this machine
92 return static_cast<unsigned>(page_size);
95size_t Process::GetMallocUsage() {
96#if defined(HAVE_MALLINFO2)
100#elif defined(HAVE_MALLINFO)
104#elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
105 malloc_statistics_t
Stats;
106 malloc_zone_statistics(malloc_default_zone(), &
Stats);
107 return Stats.size_in_use;
108#elif defined(HAVE_MALLCTL)
111 if (mallctl(
"stats.allocated", &alloc, &sz, NULL, 0) == 0)
114#elif defined(HAVE_SBRK)
117 static char *StartOfMemory =
reinterpret_cast<char *
>(::sbrk(0));
118 char *EndOfMemory = (
char *)sbrk(0);
119 if (EndOfMemory != ((
char *)-1) && StartOfMemory != ((
char *)-1))
120 return EndOfMemory - StartOfMemory;
124#warning Cannot get malloc info on this platform
131 std::chrono::nanoseconds &user_time,
132 std::chrono::nanoseconds &sys_time) {
133 elapsed = std::chrono::system_clock::now();
134 std::tie(user_time, sys_time) = getRUsageTimes();
137#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
138#include <mach/mach.h>
144void Process::PreventCoreFiles() {
147 getrlimit(RLIMIT_CORE, &rlim);
163 rlim.rlim_cur = std::min<rlim_t>(1, rlim.rlim_max);
167 setrlimit(RLIMIT_CORE, &rlim);
170#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
174 mach_msg_type_number_t Count = 0;
175 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
176 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
177 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
178 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
179 kern_return_t err = task_get_exception_ports(
180 mach_task_self(), EXC_MASK_ALL, OriginalMasks, &Count, OriginalPorts,
181 OriginalBehaviors, OriginalFlavors);
182 if (err == KERN_SUCCESS) {
184 for (
unsigned i = 0; i != Count; ++i)
185 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
186 MACH_PORT_NULL, OriginalBehaviors[i],
191 signal(SIGABRT, _exit);
192 signal(SIGILL, _exit);
193 signal(SIGFPE, _exit);
194 signal(SIGSEGV, _exit);
195 signal(SIGBUS, _exit);
202 std::string NameStr =
Name.str();
203 const char *Val = ::getenv(NameStr.c_str());
206 return std::string(Val);
212 FDCloser(
int &FD) : FD(FD), KeepOpen(
false) {}
213 void keepOpen() { KeepOpen =
true; }
215 if (!KeepOpen && FD >= 0)
220 FDCloser(
const FDCloser &) =
delete;
221 void operator=(
const FDCloser &) =
delete;
228std::error_code Process::FixupStandardFileDescriptors() {
230 FDCloser FDC(NullFD);
231 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
232 for (
int StandardFD : StandardFDs) {
236 assert(errno &&
"expected errno to be set if fstat failed!");
244 assert(errno == EBADF &&
"expected errno to have EBADF at this point!");
249 auto Open = [&]() { return ::open(
"/dev/null", O_RDWR); };
254 if (NullFD == StandardFD)
256 else if (dup2(NullFD, StandardFD) < 0)
259 return std::error_code();
262std::error_code Process::SafelyCloseFileDescriptor(
int FD) {
264 sigset_t FullSet, SavedSet;
265 if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
269#if LLVM_ENABLE_THREADS
270 if (
int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
271 return std::error_code(EC, std::generic_category());
273 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
279 int ErrnoFromClose = 0;
281 ErrnoFromClose = errno;
284#if LLVM_ENABLE_THREADS
285 EC = pthread_sigmask(SIG_SETMASK, &SavedSet,
nullptr);
287 if (sigprocmask(SIG_SETMASK, &SavedSet,
nullptr) < 0)
293 return std::error_code(ErrnoFromClose, std::generic_category());
294 return std::error_code(EC, std::generic_category());
297bool Process::StandardInIsUserInput() {
298 return FileDescriptorIsDisplayed(STDIN_FILENO);
301bool Process::StandardOutIsDisplayed() {
302 return FileDescriptorIsDisplayed(STDOUT_FILENO);
305bool Process::StandardErrIsDisplayed() {
306 return FileDescriptorIsDisplayed(STDERR_FILENO);
309bool Process::FileDescriptorIsDisplayed(
int fd) {
318static unsigned getColumns() {
320 if (
const char *ColumnsStr = std::getenv(
"COLUMNS")) {
321 int Columns = std::atoi(ColumnsStr);
331unsigned Process::StandardOutColumns() {
332 if (!StandardOutIsDisplayed())
338unsigned Process::StandardErrColumns() {
339 if (!StandardErrIsDisplayed())
345static bool terminalHasColors() {
348 if (
const char *TermStr = std::getenv(
"TERM")) {
351 .
Case(
"cygwin",
true)
364bool Process::FileDescriptorHasColors(
int fd) {
367 return FileDescriptorIsDisplayed(fd) && terminalHasColors();
370bool Process::StandardOutHasColors() {
371 return FileDescriptorHasColors(STDOUT_FILENO);
374bool Process::StandardErrHasColors() {
375 return FileDescriptorHasColors(STDERR_FILENO);
378void Process::UseANSIEscapeCodes(
bool ) {
382bool Process::ColorNeedsFlush() {
387const char *Process::OutputColor(
char code,
bool bold,
bool bg) {
388 return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 15];
391const char *Process::OutputBold(
bool bg) {
return "\033[1m"; }
393const char *Process::OutputReverse() {
return "\033[7m"; }
395const char *Process::ResetColor() {
return "\033[0m"; }
397#if !HAVE_DECL_ARC4RANDOM
398static unsigned GetRandomNumberSeed() {
400 int urandomFD = open(
"/dev/urandom", O_RDONLY);
402 if (urandomFD != -1) {
406 int count =
read(urandomFD, (
void *)&seed,
sizeof(seed));
411 if (count ==
sizeof(seed))
417 const auto Now = std::chrono::high_resolution_clock::now();
418 return hash_combine(Now.time_since_epoch().count(), ::getpid());
423#if HAVE_DECL_ARC4RANDOM
426 static int x = (
static_cast<void>(::srand(GetRandomNumberSeed())), 0);
432[[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.