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/Support/ManagedStatic.h"
22 #ifdef HAVE_SYS_TIME_H
25 #ifdef HAVE_SYS_RESOURCE_H
26 #include <sys/resource.h>
28 #ifdef HAVE_SYS_STAT_H
34 #if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
37 #if defined(HAVE_MALLCTL)
38 #include <malloc_np.h>
40 #ifdef HAVE_MALLOC_MALLOC_H
41 #include <malloc/malloc.h>
43 #ifdef HAVE_SYS_IOCTL_H
44 # include <sys/ioctl.h>
50 //===----------------------------------------------------------------------===//
51 //=== WARNING: Implementation here must contain only generic UNIX code that
52 //=== is guaranteed to work on *all* UNIX variants.
53 //===----------------------------------------------------------------------===//
58 static std::pair<std::chrono::microseconds, std::chrono::microseconds> getRUsageTimes() {
59 #if defined(HAVE_GETRUSAGE)
61 ::getrusage(RUSAGE_SELF, &RU);
62 return { toDuration(RU.ru_utime), toDuration(RU.ru_stime) };
64 #warning Cannot get usage times on this platform
65 return { std::chrono::microseconds::zero(), std::chrono::microseconds::zero() };
69 Process::Pid Process::getProcessId() {
70 static_assert(sizeof(Pid) >= sizeof(pid_t),
71 "Process::Pid should be big enough to store pid_t");
72 return Pid(::getpid());
75 // On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
76 // offset in mmap(3) should be aligned to the AllocationGranularity.
77 Expected<unsigned> Process::getPageSize() {
78 #if defined(HAVE_GETPAGESIZE)
79 static const int page_size = ::getpagesize();
80 #elif defined(HAVE_SYSCONF)
81 static long page_size = ::sysconf(_SC_PAGE_SIZE);
83 #error Cannot get the page size on this machine
86 return errorCodeToError(std::error_code(errno, std::generic_category()));
88 return static_cast<unsigned>(page_size);
91 size_t Process::GetMallocUsage() {
92 #if defined(HAVE_MALLINFO2)
96 #elif defined(HAVE_MALLINFO)
100 #elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
101 malloc_statistics_t Stats;
102 malloc_zone_statistics(malloc_default_zone(), &Stats);
103 return Stats.size_in_use; // darwin
104 #elif defined(HAVE_MALLCTL)
107 if (mallctl("stats.allocated", &alloc, &sz, NULL, 0) == 0)
110 #elif defined(HAVE_SBRK)
111 // Note this is only an approximation and more closely resembles
112 // the value returned by mallinfo in the arena field.
113 static char *StartOfMemory = reinterpret_cast<char*>(::sbrk(0));
114 char *EndOfMemory = (char*)sbrk(0);
115 if (EndOfMemory != ((char*)-1) && StartOfMemory != ((char*)-1))
116 return EndOfMemory - StartOfMemory;
119 #warning Cannot get malloc info on this platform
124 void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
125 std::chrono::nanoseconds &sys_time) {
126 elapsed = std::chrono::system_clock::now();
127 std::tie(user_time, sys_time) = getRUsageTimes();
130 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
131 #include <mach/mach.h>
134 // Some LLVM programs such as bugpoint produce core files as a normal part of
135 // their operation. To prevent the disk from filling up, this function
136 // does what's necessary to prevent their generation.
137 void Process::PreventCoreFiles() {
140 rlim.rlim_cur = rlim.rlim_max = 0;
141 setrlimit(RLIMIT_CORE, &rlim);
144 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
145 // Disable crash reporting on Mac OS X 10.0-10.4
147 // get information about the original set of exception ports for the task
148 mach_msg_type_number_t Count = 0;
149 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
150 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
151 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
152 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
154 task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
155 &Count, OriginalPorts, OriginalBehaviors,
157 if (err == KERN_SUCCESS) {
158 // replace each with MACH_PORT_NULL.
159 for (unsigned i = 0; i != Count; ++i)
160 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
161 MACH_PORT_NULL, OriginalBehaviors[i],
165 // Disable crash reporting on Mac OS X 10.5
166 signal(SIGABRT, _exit);
167 signal(SIGILL, _exit);
168 signal(SIGFPE, _exit);
169 signal(SIGSEGV, _exit);
170 signal(SIGBUS, _exit);
173 coreFilesPrevented = true;
176 Optional<std::string> Process::GetEnv(StringRef Name) {
177 std::string NameStr = Name.str();
178 const char *Val = ::getenv(NameStr.c_str());
181 return std::string(Val);
187 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
188 void keepOpen() { KeepOpen = true; }
190 if (!KeepOpen && FD >= 0)
195 FDCloser(const FDCloser &) = delete;
196 void operator=(const FDCloser &) = delete;
203 std::error_code Process::FixupStandardFileDescriptors() {
205 FDCloser FDC(NullFD);
206 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
207 for (int StandardFD : StandardFDs) {
210 if (RetryAfterSignal(-1, ::fstat, StandardFD, &st) < 0) {
211 assert(errno && "expected errno to be set if fstat failed!");
212 // fstat should return EBADF if the file descriptor is closed.
214 return std::error_code(errno, std::generic_category());
216 // if fstat succeeds, move on to the next FD.
219 assert(errno == EBADF && "expected errno to have EBADF at this point!");
222 // Call ::open in a lambda to avoid overload resolution in
223 // RetryAfterSignal when open is overloaded, such as in Bionic.
224 auto Open = [&]() { return ::open("/dev/null", O_RDWR); };
225 if ((NullFD = RetryAfterSignal(-1, Open)) < 0)
226 return std::error_code(errno, std::generic_category());
229 if (NullFD == StandardFD)
231 else if (dup2(NullFD, StandardFD) < 0)
232 return std::error_code(errno, std::generic_category());
234 return std::error_code();
237 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
238 // Create a signal set filled with *all* signals.
239 sigset_t FullSet, SavedSet;
240 if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
241 return std::error_code(errno, std::generic_category());
243 // Atomically swap our current signal mask with a full mask.
244 #if LLVM_ENABLE_THREADS
245 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
246 return std::error_code(EC, std::generic_category());
248 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
249 return std::error_code(errno, std::generic_category());
251 // Attempt to close the file descriptor.
252 // We need to save the error, if one occurs, because our subsequent call to
253 // pthread_sigmask might tamper with errno.
254 int ErrnoFromClose = 0;
256 ErrnoFromClose = errno;
257 // Restore the signal mask back to what we saved earlier.
259 #if LLVM_ENABLE_THREADS
260 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
262 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
265 // The error code from close takes precedence over the one from
268 return std::error_code(ErrnoFromClose, std::generic_category());
269 return std::error_code(EC, std::generic_category());
272 bool Process::StandardInIsUserInput() {
273 return FileDescriptorIsDisplayed(STDIN_FILENO);
276 bool Process::StandardOutIsDisplayed() {
277 return FileDescriptorIsDisplayed(STDOUT_FILENO);
280 bool Process::StandardErrIsDisplayed() {
281 return FileDescriptorIsDisplayed(STDERR_FILENO);
284 bool Process::FileDescriptorIsDisplayed(int fd) {
288 // If we don't have isatty, just return false.
293 static unsigned getColumns() {
294 // If COLUMNS is defined in the environment, wrap to that many columns.
295 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
296 int Columns = std::atoi(ColumnsStr);
301 // We used to call ioctl TIOCGWINSZ to determine the width. It is considered
306 unsigned Process::StandardOutColumns() {
307 if (!StandardOutIsDisplayed())
313 unsigned Process::StandardErrColumns() {
314 if (!StandardErrIsDisplayed())
320 #ifdef LLVM_ENABLE_TERMINFO
321 // We manually declare these extern functions because finding the correct
322 // headers from various terminfo, curses, or other sources is harder than
323 // writing their specs down.
324 extern "C" int setupterm(char *term, int filedes, int *errret);
325 extern "C" struct term *set_curterm(struct term *termp);
326 extern "C" int del_curterm(struct term *termp);
327 extern "C" int tigetnum(char *capname);
330 #ifdef LLVM_ENABLE_TERMINFO
331 static ManagedStatic<std::mutex> TermColorMutex;
334 static bool terminalHasColors(int fd) {
335 #ifdef LLVM_ENABLE_TERMINFO
336 // First, acquire a global lock because these C routines are thread hostile.
337 std::lock_guard<std::mutex> G(*TermColorMutex);
339 struct term *previous_term = set_curterm(nullptr);
341 if (setupterm(nullptr, fd, &errret) != 0)
342 // Regardless of why, if we can't get terminfo, we shouldn't try to print
346 // Test whether the terminal as set up supports color output. How to do this
347 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
348 // would be nice to avoid a dependency on curses proper when we can make do
349 // with a minimal terminfo parsing library. Also, we don't really care whether
350 // the terminal supports the curses-specific color changing routines, merely
351 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
352 // strategy here is just to query the baseline colors capability and if it
353 // supports colors at all to assume it will translate the escape codes into
354 // whatever range of colors it does support. We can add more detailed tests
355 // here if users report them as necessary.
357 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
358 // the terminfo says that no colors are supported.
359 bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
361 // Now extract the structure allocated by setupterm and free its memory
362 // through a really silly dance.
363 struct term *termp = set_curterm(previous_term);
364 (void)del_curterm(termp); // Drop any errors here.
366 // Return true if we found a color capabilities for the current terminal.
370 // When the terminfo database is not available, check if the current terminal
371 // is one of terminals that are known to support ANSI color escape codes.
372 if (const char *TermStr = std::getenv("TERM")) {
373 return StringSwitch<bool>(TermStr)
375 .Case("cygwin", true)
377 .StartsWith("screen", true)
378 .StartsWith("xterm", true)
379 .StartsWith("vt100", true)
380 .StartsWith("rxvt", true)
381 .EndsWith("color", true)
386 // Otherwise, be conservative.
390 bool Process::FileDescriptorHasColors(int fd) {
391 // A file descriptor has colors if it is displayed and the terminal has
393 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
396 bool Process::StandardOutHasColors() {
397 return FileDescriptorHasColors(STDOUT_FILENO);
400 bool Process::StandardErrHasColors() {
401 return FileDescriptorHasColors(STDERR_FILENO);
404 void Process::UseANSIEscapeCodes(bool /*enable*/) {
408 bool Process::ColorNeedsFlush() {
409 // No, we use ANSI escape sequences.
413 const char *Process::OutputColor(char code, bool bold, bool bg) {
414 return colorcodes[bg?1:0][bold?1:0][code&7];
417 const char *Process::OutputBold(bool bg) {
421 const char *Process::OutputReverse() {
425 const char *Process::ResetColor() {
429 #if !HAVE_DECL_ARC4RANDOM
430 static unsigned GetRandomNumberSeed() {
431 // Attempt to get the initial seed from /dev/urandom, if possible.
432 int urandomFD = open("/dev/urandom", O_RDONLY);
434 if (urandomFD != -1) {
436 // Don't use a buffered read to avoid reading more data
437 // from /dev/urandom than we need.
438 int count = read(urandomFD, (void *)&seed, sizeof(seed));
442 // Return the seed if the read was successful.
443 if (count == sizeof(seed))
447 // Otherwise, swizzle the current time and the process ID to form a reasonable
449 const auto Now = std::chrono::high_resolution_clock::now();
450 return hash_combine(Now.time_since_epoch().count(), ::getpid());
454 unsigned llvm::sys::Process::GetRandomNumber() {
455 #if HAVE_DECL_ARC4RANDOM
458 static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0);
464 [[noreturn]] void Process::ExitNoCleanup(int RetCode) { _Exit(RetCode); }