1 //===- Unix/Process.cpp - Unix Process Implementation --------- -*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file provides the generic Unix implementation of the Process class.
11 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/Hashing.h"
15 #include "llvm/ADT/StringRef.h"
16 #include "llvm/Config/config.h"
17 #include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_THREADS
23 #ifdef HAVE_SYS_TIME_H
26 #ifdef HAVE_SYS_RESOURCE_H
27 #include <sys/resource.h>
29 #ifdef HAVE_SYS_STAT_H
35 #if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
38 #if defined(HAVE_MALLCTL)
39 #include <malloc_np.h>
41 #ifdef HAVE_MALLOC_MALLOC_H
42 #include <malloc/malloc.h>
44 #ifdef HAVE_SYS_IOCTL_H
45 #include <sys/ioctl.h>
51 //===----------------------------------------------------------------------===//
52 //=== WARNING: Implementation here must contain only generic UNIX code that
53 //=== is guaranteed to work on *all* UNIX variants.
54 //===----------------------------------------------------------------------===//
59 static std::pair<std::chrono::microseconds, std::chrono::microseconds>
61 #if defined(HAVE_GETRUSAGE)
63 ::getrusage(RUSAGE_SELF, &RU);
64 return {toDuration(RU.ru_utime), toDuration(RU.ru_stime)};
66 #ifndef __MVS__ // Exclude for MVS in case -pedantic is used
67 #warning Cannot get usage times on this platform
69 return {std::chrono::microseconds::zero(), std::chrono::microseconds::zero()};
73 Process::Pid Process::getProcessId() {
74 static_assert(sizeof(Pid) >= sizeof(pid_t),
75 "Process::Pid should be big enough to store pid_t");
76 return Pid(::getpid());
79 // On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
80 // offset in mmap(3) should be aligned to the AllocationGranularity.
81 Expected<unsigned> Process::getPageSize() {
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
90 return errorCodeToError(errnoAsErrorCode());
92 return static_cast<unsigned>(page_size);
95 size_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; // darwin
108 #elif defined(HAVE_MALLCTL)
111 if (mallctl("stats.allocated", &alloc, &sz, NULL, 0) == 0)
114 #elif defined(HAVE_SBRK)
115 // Note this is only an approximation and more closely resembles
116 // the value returned by mallinfo in the arena field.
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;
123 #ifndef __MVS__ // Exclude for MVS in case -pedantic is used
124 #warning Cannot get malloc info on this platform
130 void Process::GetTimeUsage(TimePoint<> &elapsed,
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>
141 // Some LLVM programs such as bugpoint produce core files as a normal part of
142 // their operation. To prevent the disk from filling up, this function
143 // does what's necessary to prevent their generation.
144 void Process::PreventCoreFiles() {
147 getrlimit(RLIMIT_CORE, &rlim);
149 // On Linux, if the kernel.core_pattern sysctl starts with a '|' (i.e. it
150 // is being piped to a coredump handler such as systemd-coredumpd), the
151 // kernel ignores RLIMIT_CORE (since we aren't creating a file in the file
152 // system) except for the magic value of 1, which disables coredumps when
153 // piping. 1 byte is too small for any kind of valid core dump, so it
154 // also disables coredumps if kernel.core_pattern creates files directly.
155 // While most piped coredump handlers do respect the crashing processes'
156 // RLIMIT_CORE, this is notable not the case for Debian's systemd-coredump
157 // due to a local patch that changes sysctl.d/50-coredump.conf to ignore
158 // the specified limit and instead use RLIM_INFINITY.
160 // The alternative to using RLIMIT_CORE=1 would be to use prctl() with the
161 // PR_SET_DUMPABLE flag, however that also prevents ptrace(), so makes it
162 // impossible to attach a debugger.
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__)
171 // Disable crash reporting on Mac OS X 10.0-10.4
173 // get information about the original set of exception ports for the task
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) {
183 // replace each with MACH_PORT_NULL.
184 for (unsigned i = 0; i != Count; ++i)
185 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
186 MACH_PORT_NULL, OriginalBehaviors[i],
190 // Disable crash reporting on Mac OS X 10.5
191 signal(SIGABRT, _exit);
192 signal(SIGILL, _exit);
193 signal(SIGFPE, _exit);
194 signal(SIGSEGV, _exit);
195 signal(SIGBUS, _exit);
198 coreFilesPrevented = true;
201 std::optional<std::string> Process::GetEnv(StringRef Name) {
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;
228 std::error_code Process::FixupStandardFileDescriptors() {
230 FDCloser FDC(NullFD);
231 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
232 for (int StandardFD : StandardFDs) {
235 if (RetryAfterSignal(-1, ::fstat, StandardFD, &st) < 0) {
236 assert(errno && "expected errno to be set if fstat failed!");
237 // fstat should return EBADF if the file descriptor is closed.
239 return errnoAsErrorCode();
241 // if fstat succeeds, move on to the next FD.
244 assert(errno == EBADF && "expected errno to have EBADF at this point!");
247 // Call ::open in a lambda to avoid overload resolution in
248 // RetryAfterSignal when open is overloaded, such as in Bionic.
249 auto Open = [&]() { return ::open("/dev/null", O_RDWR); };
250 if ((NullFD = RetryAfterSignal(-1, Open)) < 0)
251 return errnoAsErrorCode();
254 if (NullFD == StandardFD)
256 else if (dup2(NullFD, StandardFD) < 0)
257 return errnoAsErrorCode();
259 return std::error_code();
262 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
263 // Create a signal set filled with *all* signals.
264 sigset_t FullSet, SavedSet;
265 if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
266 return errnoAsErrorCode();
268 // Atomically swap our current signal mask with a full mask.
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)
274 return errnoAsErrorCode();
276 // Attempt to close the file descriptor.
277 // We need to save the error, if one occurs, because our subsequent call to
278 // pthread_sigmask might tamper with errno.
279 int ErrnoFromClose = 0;
281 ErrnoFromClose = errno;
282 // Restore the signal mask back to what we saved earlier.
284 #if LLVM_ENABLE_THREADS
285 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
287 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
290 // The error code from close takes precedence over the one from
293 return std::error_code(ErrnoFromClose, std::generic_category());
294 return std::error_code(EC, std::generic_category());
297 bool Process::StandardInIsUserInput() {
298 return FileDescriptorIsDisplayed(STDIN_FILENO);
301 bool Process::StandardOutIsDisplayed() {
302 return FileDescriptorIsDisplayed(STDOUT_FILENO);
305 bool Process::StandardErrIsDisplayed() {
306 return FileDescriptorIsDisplayed(STDERR_FILENO);
309 bool Process::FileDescriptorIsDisplayed(int fd) {
313 // If we don't have isatty, just return false.
318 static unsigned getColumns() {
319 // If COLUMNS is defined in the environment, wrap to that many columns.
320 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
321 int Columns = std::atoi(ColumnsStr);
326 // We used to call ioctl TIOCGWINSZ to determine the width. It is considered
331 unsigned Process::StandardOutColumns() {
332 if (!StandardOutIsDisplayed())
338 unsigned Process::StandardErrColumns() {
339 if (!StandardErrIsDisplayed())
345 static bool terminalHasColors() {
346 // Check if the current terminal is one of terminals that are known to support
347 // ANSI color escape codes.
348 if (const char *TermStr = std::getenv("TERM")) {
349 return StringSwitch<bool>(TermStr)
351 .Case("cygwin", true)
353 .StartsWith("screen", true)
354 .StartsWith("xterm", true)
355 .StartsWith("vt100", true)
356 .StartsWith("rxvt", true)
357 .EndsWith("color", true)
364 bool Process::FileDescriptorHasColors(int fd) {
365 // A file descriptor has colors if it is displayed and the terminal has
367 return FileDescriptorIsDisplayed(fd) && terminalHasColors();
370 bool Process::StandardOutHasColors() {
371 return FileDescriptorHasColors(STDOUT_FILENO);
374 bool Process::StandardErrHasColors() {
375 return FileDescriptorHasColors(STDERR_FILENO);
378 void Process::UseANSIEscapeCodes(bool /*enable*/) {
382 bool Process::ColorNeedsFlush() {
383 // No, we use ANSI escape sequences.
387 const char *Process::OutputColor(char code, bool bold, bool bg) {
388 return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 15];
391 const char *Process::OutputBold(bool bg) { return "\033[1m"; }
393 const char *Process::OutputReverse() { return "\033[7m"; }
395 const char *Process::ResetColor() { return "\033[0m"; }
397 #if !HAVE_DECL_ARC4RANDOM
398 static unsigned GetRandomNumberSeed() {
399 // Attempt to get the initial seed from /dev/urandom, if possible.
400 int urandomFD = open("/dev/urandom", O_RDONLY);
402 if (urandomFD != -1) {
404 // Don't use a buffered read to avoid reading more data
405 // from /dev/urandom than we need.
406 int count = read(urandomFD, (void *)&seed, sizeof(seed));
410 // Return the seed if the read was successful.
411 if (count == sizeof(seed))
415 // Otherwise, swizzle the current time and the process ID to form a reasonable
417 const auto Now = std::chrono::high_resolution_clock::now();
418 return hash_combine(Now.time_since_epoch().count(), ::getpid());
422 unsigned llvm::sys::Process::GetRandomNumber() {
423 #if HAVE_DECL_ARC4RANDOM
426 static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0);
432 [[noreturn]] void Process::ExitNoCleanup(int RetCode) { _Exit(RetCode); }