1 //===- Unix/Process.cpp - Unix Process Implementation --------- -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides the generic Unix implementation of the Process class.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/Hashing.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/Support/ManagedStatic.h"
18 #include "llvm/Support/Mutex.h"
19 #include "llvm/Support/MutexGuard.h"
20 #include "llvm/Support/TimeValue.h"
24 #ifdef HAVE_SYS_TIME_H
27 #ifdef HAVE_SYS_RESOURCE_H
28 #include <sys/resource.h>
30 // DragonFlyBSD, OpenBSD, and Bitrig have deprecated <malloc.h> for
31 // <stdlib.h> instead. Unix.h includes this for us already.
32 #if defined(HAVE_MALLOC_H) && !defined(__DragonFly__) && \
33 !defined(__OpenBSD__) && !defined(__Bitrig__)
36 #ifdef HAVE_MALLOC_MALLOC_H
37 #include <malloc/malloc.h>
39 #ifdef HAVE_SYS_IOCTL_H
40 # include <sys/ioctl.h>
46 //===----------------------------------------------------------------------===//
47 //=== WARNING: Implementation here must contain only generic UNIX code that
48 //=== is guaranteed to work on *all* UNIX variants.
49 //===----------------------------------------------------------------------===//
54 process::id_type self_process::get_id() {
58 static std::pair<TimeValue, TimeValue> getRUsageTimes() {
59 #if defined(HAVE_GETRUSAGE)
61 ::getrusage(RUSAGE_SELF, &RU);
62 return std::make_pair(
64 static_cast<TimeValue::SecondsType>(RU.ru_utime.tv_sec),
65 static_cast<TimeValue::NanoSecondsType>(
66 RU.ru_utime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)),
68 static_cast<TimeValue::SecondsType>(RU.ru_stime.tv_sec),
69 static_cast<TimeValue::NanoSecondsType>(
70 RU.ru_stime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)));
72 #warning Cannot get usage times on this platform
73 return std::make_pair(TimeValue(), TimeValue());
77 TimeValue self_process::get_user_time() const {
78 #if _POSIX_TIMERS > 0 && _POSIX_CPUTIME > 0
79 // Try to get a high resolution CPU timer.
81 if (::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &TS) == 0)
82 return TimeValue(static_cast<TimeValue::SecondsType>(TS.tv_sec),
83 static_cast<TimeValue::NanoSecondsType>(TS.tv_nsec));
86 // Otherwise fall back to rusage based timing.
87 return getRUsageTimes().first;
90 TimeValue self_process::get_system_time() const {
91 // We can only collect system time by inspecting the results of getrusage.
92 return getRUsageTimes().second;
95 // On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
96 // offset in mmap(3) should be aligned to the AllocationGranularity.
97 static unsigned getPageSize() {
98 #if defined(HAVE_GETPAGESIZE)
99 const int page_size = ::getpagesize();
100 #elif defined(HAVE_SYSCONF)
101 long page_size = ::sysconf(_SC_PAGE_SIZE);
103 #warning Cannot get the page size on this machine
105 return static_cast<unsigned>(page_size);
108 // This constructor guaranteed to be run exactly once on a single thread, and
109 // sets up various process invariants that can be queried cheaply from then on.
110 self_process::self_process() : PageSize(getPageSize()) {
114 size_t Process::GetMallocUsage() {
115 #if defined(HAVE_MALLINFO)
119 #elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
120 malloc_statistics_t Stats;
121 malloc_zone_statistics(malloc_default_zone(), &Stats);
122 return Stats.size_in_use; // darwin
123 #elif defined(HAVE_SBRK)
124 // Note this is only an approximation and more closely resembles
125 // the value returned by mallinfo in the arena field.
126 static char *StartOfMemory = reinterpret_cast<char*>(::sbrk(0));
127 char *EndOfMemory = (char*)sbrk(0);
128 if (EndOfMemory != ((char*)-1) && StartOfMemory != ((char*)-1))
129 return EndOfMemory - StartOfMemory;
133 #warning Cannot get malloc info on this platform
138 void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
139 TimeValue &sys_time) {
140 elapsed = TimeValue::now();
141 std::tie(user_time, sys_time) = getRUsageTimes();
144 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
145 #include <mach/mach.h>
148 // Some LLVM programs such as bugpoint produce core files as a normal part of
149 // their operation. To prevent the disk from filling up, this function
150 // does what's necessary to prevent their generation.
151 void Process::PreventCoreFiles() {
154 rlim.rlim_cur = rlim.rlim_max = 0;
155 setrlimit(RLIMIT_CORE, &rlim);
158 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
159 // Disable crash reporting on Mac OS X 10.0-10.4
161 // get information about the original set of exception ports for the task
162 mach_msg_type_number_t Count = 0;
163 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
164 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
165 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
166 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
168 task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
169 &Count, OriginalPorts, OriginalBehaviors,
171 if (err == KERN_SUCCESS) {
172 // replace each with MACH_PORT_NULL.
173 for (unsigned i = 0; i != Count; ++i)
174 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
175 MACH_PORT_NULL, OriginalBehaviors[i],
179 // Disable crash reporting on Mac OS X 10.5
180 signal(SIGABRT, _exit);
181 signal(SIGILL, _exit);
182 signal(SIGFPE, _exit);
183 signal(SIGSEGV, _exit);
184 signal(SIGBUS, _exit);
188 Optional<std::string> Process::GetEnv(StringRef Name) {
189 std::string NameStr = Name.str();
190 const char *Val = ::getenv(NameStr.c_str());
193 return std::string(Val);
197 Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
198 ArrayRef<const char *> ArgsIn,
199 SpecificBumpPtrAllocator<char> &) {
200 ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
202 return std::error_code();
208 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
209 void keepOpen() { KeepOpen = true; }
211 if (!KeepOpen && FD >= 0)
216 FDCloser(const FDCloser &) LLVM_DELETED_FUNCTION;
217 void operator=(const FDCloser &) LLVM_DELETED_FUNCTION;
224 std::error_code Process::FixupStandardFileDescriptors() {
226 FDCloser FDC(NullFD);
227 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
228 for (int StandardFD : StandardFDs) {
231 while (fstat(StandardFD, &st) < 0) {
232 assert(errno && "expected errno to be set if fstat failed!");
233 // fstat should return EBADF if the file descriptor is closed.
236 // retry fstat if we got EINTR, otherwise bubble up the failure.
238 return std::error_code(errno, std::generic_category());
240 // if fstat succeeds, move on to the next FD.
243 assert(errno == EBADF && "expected errno to have EBADF at this point!");
246 while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
249 return std::error_code(errno, std::generic_category());
253 if (NullFD == StandardFD)
255 else if (dup2(NullFD, StandardFD) < 0)
256 return std::error_code(errno, std::generic_category());
258 return std::error_code();
261 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
262 // Create a signal set filled with *all* signals.
264 if (sigfillset(&FullSet) < 0)
265 return std::error_code(errno, std::generic_category());
266 // Atomically swap our current signal mask with a full mask.
268 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
269 return std::error_code(EC, std::generic_category());
270 // Attempt to close the file descriptor.
271 // We need to save the error, if one occurs, because our subsequent call to
272 // pthread_sigmask might tamper with errno.
273 int ErrnoFromClose = 0;
275 ErrnoFromClose = errno;
276 // Restore the signal mask back to what we saved earlier.
277 int EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
278 // The error code from close takes precedence over the one from
281 return std::error_code(ErrnoFromClose, std::generic_category());
282 return std::error_code(EC, std::generic_category());
285 bool Process::StandardInIsUserInput() {
286 return FileDescriptorIsDisplayed(STDIN_FILENO);
289 bool Process::StandardOutIsDisplayed() {
290 return FileDescriptorIsDisplayed(STDOUT_FILENO);
293 bool Process::StandardErrIsDisplayed() {
294 return FileDescriptorIsDisplayed(STDERR_FILENO);
297 bool Process::FileDescriptorIsDisplayed(int fd) {
301 // If we don't have isatty, just return false.
306 static unsigned getColumns(int FileID) {
307 // If COLUMNS is defined in the environment, wrap to that many columns.
308 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
309 int Columns = std::atoi(ColumnsStr);
314 unsigned Columns = 0;
316 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
317 // Try to determine the width of the terminal.
319 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
326 unsigned Process::StandardOutColumns() {
327 if (!StandardOutIsDisplayed())
330 return getColumns(1);
333 unsigned Process::StandardErrColumns() {
334 if (!StandardErrIsDisplayed())
337 return getColumns(2);
341 // We manually declare these extern functions because finding the correct
342 // headers from various terminfo, curses, or other sources is harder than
343 // writing their specs down.
344 extern "C" int setupterm(char *term, int filedes, int *errret);
345 extern "C" struct term *set_curterm(struct term *termp);
346 extern "C" int del_curterm(struct term *termp);
347 extern "C" int tigetnum(char *capname);
351 static ManagedStatic<sys::Mutex> TermColorMutex;
354 static bool terminalHasColors(int fd) {
356 // First, acquire a global lock because these C routines are thread hostile.
357 MutexGuard G(*TermColorMutex);
360 if (setupterm((char *)nullptr, fd, &errret) != 0)
361 // Regardless of why, if we can't get terminfo, we shouldn't try to print
365 // Test whether the terminal as set up supports color output. How to do this
366 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
367 // would be nice to avoid a dependency on curses proper when we can make do
368 // with a minimal terminfo parsing library. Also, we don't really care whether
369 // the terminal supports the curses-specific color changing routines, merely
370 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
371 // strategy here is just to query the baseline colors capability and if it
372 // supports colors at all to assume it will translate the escape codes into
373 // whatever range of colors it does support. We can add more detailed tests
374 // here if users report them as necessary.
376 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
377 // the terminfo says that no colors are supported.
378 bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
380 // Now extract the structure allocated by setupterm and free its memory
381 // through a really silly dance.
382 struct term *termp = set_curterm((struct term *)nullptr);
383 (void)del_curterm(termp); // Drop any errors here.
385 // Return true if we found a color capabilities for the current terminal.
390 // Otherwise, be conservative.
394 bool Process::FileDescriptorHasColors(int fd) {
395 // A file descriptor has colors if it is displayed and the terminal has
397 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
400 bool Process::StandardOutHasColors() {
401 return FileDescriptorHasColors(STDOUT_FILENO);
404 bool Process::StandardErrHasColors() {
405 return FileDescriptorHasColors(STDERR_FILENO);
408 void Process::UseANSIEscapeCodes(bool /*enable*/) {
412 bool Process::ColorNeedsFlush() {
413 // No, we use ANSI escape sequences.
417 const char *Process::OutputColor(char code, bool bold, bool bg) {
418 return colorcodes[bg?1:0][bold?1:0][code&7];
421 const char *Process::OutputBold(bool bg) {
425 const char *Process::OutputReverse() {
429 const char *Process::ResetColor() {
433 #if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
434 static unsigned GetRandomNumberSeed() {
435 // Attempt to get the initial seed from /dev/urandom, if possible.
436 if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
438 int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
439 ::fclose(RandomSource);
441 // Return the seed if the read was successful.
446 // Otherwise, swizzle the current time and the process ID to form a reasonable
448 TimeValue Now = TimeValue::now();
449 return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
453 unsigned llvm::sys::Process::GetRandomNumber() {
454 #if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
457 static int x = (::srand(GetRandomNumberSeed()), 0);