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 #ifdef HAVE_SYS_STAT_H
36 // DragonFlyBSD, OpenBSD, and Bitrig have deprecated <malloc.h> for
37 // <stdlib.h> instead. Unix.h includes this for us already.
38 #if defined(HAVE_MALLOC_H) && !defined(__DragonFly__) && \
39 !defined(__OpenBSD__) && !defined(__Bitrig__)
42 #ifdef HAVE_MALLOC_MALLOC_H
43 #include <malloc/malloc.h>
45 #ifdef HAVE_SYS_IOCTL_H
46 # include <sys/ioctl.h>
52 //===----------------------------------------------------------------------===//
53 //=== WARNING: Implementation here must contain only generic UNIX code that
54 //=== is guaranteed to work on *all* UNIX variants.
55 //===----------------------------------------------------------------------===//
60 static std::pair<TimeValue, TimeValue> getRUsageTimes() {
61 #if defined(HAVE_GETRUSAGE)
63 ::getrusage(RUSAGE_SELF, &RU);
64 return std::make_pair(
66 static_cast<TimeValue::SecondsType>(RU.ru_utime.tv_sec),
67 static_cast<TimeValue::NanoSecondsType>(
68 RU.ru_utime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)),
70 static_cast<TimeValue::SecondsType>(RU.ru_stime.tv_sec),
71 static_cast<TimeValue::NanoSecondsType>(
72 RU.ru_stime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)));
74 #warning Cannot get usage times on this platform
75 return std::make_pair(TimeValue(), TimeValue());
79 // On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
80 // offset in mmap(3) should be aligned to the AllocationGranularity.
81 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 #warning Cannot get the page size on this machine
89 return static_cast<unsigned>(page_size);
92 size_t Process::GetMallocUsage() {
93 #if defined(HAVE_MALLINFO)
97 #elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
98 malloc_statistics_t Stats;
99 malloc_zone_statistics(malloc_default_zone(), &Stats);
100 return Stats.size_in_use; // darwin
101 #elif defined(HAVE_SBRK)
102 // Note this is only an approximation and more closely resembles
103 // the value returned by mallinfo in the arena field.
104 static char *StartOfMemory = reinterpret_cast<char*>(::sbrk(0));
105 char *EndOfMemory = (char*)sbrk(0);
106 if (EndOfMemory != ((char*)-1) && StartOfMemory != ((char*)-1))
107 return EndOfMemory - StartOfMemory;
111 #warning Cannot get malloc info on this platform
116 void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
117 TimeValue &sys_time) {
118 elapsed = TimeValue::now();
119 std::tie(user_time, sys_time) = getRUsageTimes();
122 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
123 #include <mach/mach.h>
126 // Some LLVM programs such as bugpoint produce core files as a normal part of
127 // their operation. To prevent the disk from filling up, this function
128 // does what's necessary to prevent their generation.
129 void Process::PreventCoreFiles() {
132 rlim.rlim_cur = rlim.rlim_max = 0;
133 setrlimit(RLIMIT_CORE, &rlim);
136 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
137 // Disable crash reporting on Mac OS X 10.0-10.4
139 // get information about the original set of exception ports for the task
140 mach_msg_type_number_t Count = 0;
141 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
142 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
143 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
144 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
146 task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
147 &Count, OriginalPorts, OriginalBehaviors,
149 if (err == KERN_SUCCESS) {
150 // replace each with MACH_PORT_NULL.
151 for (unsigned i = 0; i != Count; ++i)
152 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
153 MACH_PORT_NULL, OriginalBehaviors[i],
157 // Disable crash reporting on Mac OS X 10.5
158 signal(SIGABRT, _exit);
159 signal(SIGILL, _exit);
160 signal(SIGFPE, _exit);
161 signal(SIGSEGV, _exit);
162 signal(SIGBUS, _exit);
166 Optional<std::string> Process::GetEnv(StringRef Name) {
167 std::string NameStr = Name.str();
168 const char *Val = ::getenv(NameStr.c_str());
171 return std::string(Val);
175 Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
176 ArrayRef<const char *> ArgsIn,
177 SpecificBumpPtrAllocator<char> &) {
178 ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
180 return std::error_code();
186 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
187 void keepOpen() { KeepOpen = true; }
189 if (!KeepOpen && FD >= 0)
194 FDCloser(const FDCloser &) LLVM_DELETED_FUNCTION;
195 void operator=(const FDCloser &) LLVM_DELETED_FUNCTION;
202 std::error_code Process::FixupStandardFileDescriptors() {
204 FDCloser FDC(NullFD);
205 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
206 for (int StandardFD : StandardFDs) {
209 while (fstat(StandardFD, &st) < 0) {
210 assert(errno && "expected errno to be set if fstat failed!");
211 // fstat should return EBADF if the file descriptor is closed.
214 // retry fstat if we got EINTR, otherwise bubble up the failure.
216 return std::error_code(errno, std::generic_category());
218 // if fstat succeeds, move on to the next FD.
221 assert(errno == EBADF && "expected errno to have EBADF at this point!");
224 while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
227 return std::error_code(errno, std::generic_category());
231 if (NullFD == StandardFD)
233 else if (dup2(NullFD, StandardFD) < 0)
234 return std::error_code(errno, std::generic_category());
236 return std::error_code();
239 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
240 // Create a signal set filled with *all* signals.
242 if (sigfillset(&FullSet) < 0)
243 return std::error_code(errno, std::generic_category());
244 // Atomically swap our current signal mask with a full mask.
246 #if LLVM_ENABLE_THREADS
247 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
248 return std::error_code(EC, std::generic_category());
250 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
251 return std::error_code(errno, std::generic_category());
253 // Attempt to close the file descriptor.
254 // We need to save the error, if one occurs, because our subsequent call to
255 // pthread_sigmask might tamper with errno.
256 int ErrnoFromClose = 0;
258 ErrnoFromClose = errno;
259 // Restore the signal mask back to what we saved earlier.
261 #if LLVM_ENABLE_THREADS
262 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
264 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
267 // The error code from close takes precedence over the one from
270 return std::error_code(ErrnoFromClose, std::generic_category());
271 return std::error_code(EC, std::generic_category());
274 bool Process::StandardInIsUserInput() {
275 return FileDescriptorIsDisplayed(STDIN_FILENO);
278 bool Process::StandardOutIsDisplayed() {
279 return FileDescriptorIsDisplayed(STDOUT_FILENO);
282 bool Process::StandardErrIsDisplayed() {
283 return FileDescriptorIsDisplayed(STDERR_FILENO);
286 bool Process::FileDescriptorIsDisplayed(int fd) {
290 // If we don't have isatty, just return false.
295 static unsigned getColumns(int FileID) {
296 // If COLUMNS is defined in the environment, wrap to that many columns.
297 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
298 int Columns = std::atoi(ColumnsStr);
303 unsigned Columns = 0;
305 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
306 // Try to determine the width of the terminal.
308 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
315 unsigned Process::StandardOutColumns() {
316 if (!StandardOutIsDisplayed())
319 return getColumns(1);
322 unsigned Process::StandardErrColumns() {
323 if (!StandardErrIsDisplayed())
326 return getColumns(2);
330 // We manually declare these extern functions because finding the correct
331 // headers from various terminfo, curses, or other sources is harder than
332 // writing their specs down.
333 extern "C" int setupterm(char *term, int filedes, int *errret);
334 extern "C" struct term *set_curterm(struct term *termp);
335 extern "C" int del_curterm(struct term *termp);
336 extern "C" int tigetnum(char *capname);
340 static ManagedStatic<sys::Mutex> TermColorMutex;
343 static bool terminalHasColors(int fd) {
345 // First, acquire a global lock because these C routines are thread hostile.
346 MutexGuard G(*TermColorMutex);
349 if (setupterm((char *)nullptr, fd, &errret) != 0)
350 // Regardless of why, if we can't get terminfo, we shouldn't try to print
354 // Test whether the terminal as set up supports color output. How to do this
355 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
356 // would be nice to avoid a dependency on curses proper when we can make do
357 // with a minimal terminfo parsing library. Also, we don't really care whether
358 // the terminal supports the curses-specific color changing routines, merely
359 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
360 // strategy here is just to query the baseline colors capability and if it
361 // supports colors at all to assume it will translate the escape codes into
362 // whatever range of colors it does support. We can add more detailed tests
363 // here if users report them as necessary.
365 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
366 // the terminfo says that no colors are supported.
367 bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
369 // Now extract the structure allocated by setupterm and free its memory
370 // through a really silly dance.
371 struct term *termp = set_curterm((struct term *)nullptr);
372 (void)del_curterm(termp); // Drop any errors here.
374 // Return true if we found a color capabilities for the current terminal.
379 // Otherwise, be conservative.
383 bool Process::FileDescriptorHasColors(int fd) {
384 // A file descriptor has colors if it is displayed and the terminal has
386 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
389 bool Process::StandardOutHasColors() {
390 return FileDescriptorHasColors(STDOUT_FILENO);
393 bool Process::StandardErrHasColors() {
394 return FileDescriptorHasColors(STDERR_FILENO);
397 void Process::UseANSIEscapeCodes(bool /*enable*/) {
401 bool Process::ColorNeedsFlush() {
402 // No, we use ANSI escape sequences.
406 const char *Process::OutputColor(char code, bool bold, bool bg) {
407 return colorcodes[bg?1:0][bold?1:0][code&7];
410 const char *Process::OutputBold(bool bg) {
414 const char *Process::OutputReverse() {
418 const char *Process::ResetColor() {
422 #if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
423 static unsigned GetRandomNumberSeed() {
424 // Attempt to get the initial seed from /dev/urandom, if possible.
425 if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
427 int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
428 ::fclose(RandomSource);
430 // Return the seed if the read was successful.
435 // Otherwise, swizzle the current time and the process ID to form a reasonable
437 TimeValue Now = TimeValue::now();
438 return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
442 unsigned llvm::sys::Process::GetRandomNumber() {
443 #if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
446 static int x = (::srand(GetRandomNumberSeed()), 0);