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 process::id_type self_process::get_id() {
64 static std::pair<TimeValue, TimeValue> getRUsageTimes() {
65 #if defined(HAVE_GETRUSAGE)
67 ::getrusage(RUSAGE_SELF, &RU);
68 return std::make_pair(
70 static_cast<TimeValue::SecondsType>(RU.ru_utime.tv_sec),
71 static_cast<TimeValue::NanoSecondsType>(
72 RU.ru_utime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)),
74 static_cast<TimeValue::SecondsType>(RU.ru_stime.tv_sec),
75 static_cast<TimeValue::NanoSecondsType>(
76 RU.ru_stime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)));
78 #warning Cannot get usage times on this platform
79 return std::make_pair(TimeValue(), TimeValue());
83 TimeValue self_process::get_user_time() const {
84 #if _POSIX_TIMERS > 0 && _POSIX_CPUTIME > 0
85 // Try to get a high resolution CPU timer.
87 if (::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &TS) == 0)
88 return TimeValue(static_cast<TimeValue::SecondsType>(TS.tv_sec),
89 static_cast<TimeValue::NanoSecondsType>(TS.tv_nsec));
92 // Otherwise fall back to rusage based timing.
93 return getRUsageTimes().first;
96 TimeValue self_process::get_system_time() const {
97 // We can only collect system time by inspecting the results of getrusage.
98 return getRUsageTimes().second;
101 // On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
102 // offset in mmap(3) should be aligned to the AllocationGranularity.
103 static unsigned getPageSize() {
104 #if defined(HAVE_GETPAGESIZE)
105 const int page_size = ::getpagesize();
106 #elif defined(HAVE_SYSCONF)
107 long page_size = ::sysconf(_SC_PAGE_SIZE);
109 #warning Cannot get the page size on this machine
111 return static_cast<unsigned>(page_size);
114 // This constructor guaranteed to be run exactly once on a single thread, and
115 // sets up various process invariants that can be queried cheaply from then on.
116 self_process::self_process() : PageSize(getPageSize()) {
120 size_t Process::GetMallocUsage() {
121 #if defined(HAVE_MALLINFO)
125 #elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
126 malloc_statistics_t Stats;
127 malloc_zone_statistics(malloc_default_zone(), &Stats);
128 return Stats.size_in_use; // darwin
129 #elif defined(HAVE_SBRK)
130 // Note this is only an approximation and more closely resembles
131 // the value returned by mallinfo in the arena field.
132 static char *StartOfMemory = reinterpret_cast<char*>(::sbrk(0));
133 char *EndOfMemory = (char*)sbrk(0);
134 if (EndOfMemory != ((char*)-1) && StartOfMemory != ((char*)-1))
135 return EndOfMemory - StartOfMemory;
139 #warning Cannot get malloc info on this platform
144 void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
145 TimeValue &sys_time) {
146 elapsed = TimeValue::now();
147 std::tie(user_time, sys_time) = getRUsageTimes();
150 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
151 #include <mach/mach.h>
154 // Some LLVM programs such as bugpoint produce core files as a normal part of
155 // their operation. To prevent the disk from filling up, this function
156 // does what's necessary to prevent their generation.
157 void Process::PreventCoreFiles() {
160 rlim.rlim_cur = rlim.rlim_max = 0;
161 setrlimit(RLIMIT_CORE, &rlim);
164 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
165 // Disable crash reporting on Mac OS X 10.0-10.4
167 // get information about the original set of exception ports for the task
168 mach_msg_type_number_t Count = 0;
169 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
170 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
171 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
172 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
174 task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
175 &Count, OriginalPorts, OriginalBehaviors,
177 if (err == KERN_SUCCESS) {
178 // replace each with MACH_PORT_NULL.
179 for (unsigned i = 0; i != Count; ++i)
180 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
181 MACH_PORT_NULL, OriginalBehaviors[i],
185 // Disable crash reporting on Mac OS X 10.5
186 signal(SIGABRT, _exit);
187 signal(SIGILL, _exit);
188 signal(SIGFPE, _exit);
189 signal(SIGSEGV, _exit);
190 signal(SIGBUS, _exit);
194 Optional<std::string> Process::GetEnv(StringRef Name) {
195 std::string NameStr = Name.str();
196 const char *Val = ::getenv(NameStr.c_str());
199 return std::string(Val);
203 Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
204 ArrayRef<const char *> ArgsIn,
205 SpecificBumpPtrAllocator<char> &) {
206 ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
208 return std::error_code();
214 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
215 void keepOpen() { KeepOpen = true; }
217 if (!KeepOpen && FD >= 0)
222 FDCloser(const FDCloser &) LLVM_DELETED_FUNCTION;
223 void operator=(const FDCloser &) LLVM_DELETED_FUNCTION;
230 std::error_code Process::FixupStandardFileDescriptors() {
232 FDCloser FDC(NullFD);
233 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
234 for (int StandardFD : StandardFDs) {
237 while (fstat(StandardFD, &st) < 0) {
238 assert(errno && "expected errno to be set if fstat failed!");
239 // fstat should return EBADF if the file descriptor is closed.
242 // retry fstat if we got EINTR, otherwise bubble up the failure.
244 return std::error_code(errno, std::generic_category());
246 // if fstat succeeds, move on to the next FD.
249 assert(errno == EBADF && "expected errno to have EBADF at this point!");
252 while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
255 return std::error_code(errno, std::generic_category());
259 if (NullFD == StandardFD)
261 else if (dup2(NullFD, StandardFD) < 0)
262 return std::error_code(errno, std::generic_category());
264 return std::error_code();
267 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
268 // Create a signal set filled with *all* signals.
270 if (sigfillset(&FullSet) < 0)
271 return std::error_code(errno, std::generic_category());
272 // Atomically swap our current signal mask with a full mask.
274 #if LLVM_ENABLE_THREADS
275 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
276 return std::error_code(EC, std::generic_category());
278 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
279 return std::error_code(errno, std::generic_category());
281 // Attempt to close the file descriptor.
282 // We need to save the error, if one occurs, because our subsequent call to
283 // pthread_sigmask might tamper with errno.
284 int ErrnoFromClose = 0;
286 ErrnoFromClose = errno;
287 // Restore the signal mask back to what we saved earlier.
289 #if LLVM_ENABLE_THREADS
290 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
292 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
295 // The error code from close takes precedence over the one from
298 return std::error_code(ErrnoFromClose, std::generic_category());
299 return std::error_code(EC, std::generic_category());
302 bool Process::StandardInIsUserInput() {
303 return FileDescriptorIsDisplayed(STDIN_FILENO);
306 bool Process::StandardOutIsDisplayed() {
307 return FileDescriptorIsDisplayed(STDOUT_FILENO);
310 bool Process::StandardErrIsDisplayed() {
311 return FileDescriptorIsDisplayed(STDERR_FILENO);
314 bool Process::FileDescriptorIsDisplayed(int fd) {
318 // If we don't have isatty, just return false.
323 static unsigned getColumns(int FileID) {
324 // If COLUMNS is defined in the environment, wrap to that many columns.
325 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
326 int Columns = std::atoi(ColumnsStr);
331 unsigned Columns = 0;
333 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
334 // Try to determine the width of the terminal.
336 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
343 unsigned Process::StandardOutColumns() {
344 if (!StandardOutIsDisplayed())
347 return getColumns(1);
350 unsigned Process::StandardErrColumns() {
351 if (!StandardErrIsDisplayed())
354 return getColumns(2);
358 // We manually declare these extern functions because finding the correct
359 // headers from various terminfo, curses, or other sources is harder than
360 // writing their specs down.
361 extern "C" int setupterm(char *term, int filedes, int *errret);
362 extern "C" struct term *set_curterm(struct term *termp);
363 extern "C" int del_curterm(struct term *termp);
364 extern "C" int tigetnum(char *capname);
368 static ManagedStatic<sys::Mutex> TermColorMutex;
371 static bool terminalHasColors(int fd) {
373 // First, acquire a global lock because these C routines are thread hostile.
374 MutexGuard G(*TermColorMutex);
377 if (setupterm((char *)nullptr, fd, &errret) != 0)
378 // Regardless of why, if we can't get terminfo, we shouldn't try to print
382 // Test whether the terminal as set up supports color output. How to do this
383 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
384 // would be nice to avoid a dependency on curses proper when we can make do
385 // with a minimal terminfo parsing library. Also, we don't really care whether
386 // the terminal supports the curses-specific color changing routines, merely
387 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
388 // strategy here is just to query the baseline colors capability and if it
389 // supports colors at all to assume it will translate the escape codes into
390 // whatever range of colors it does support. We can add more detailed tests
391 // here if users report them as necessary.
393 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
394 // the terminfo says that no colors are supported.
395 bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
397 // Now extract the structure allocated by setupterm and free its memory
398 // through a really silly dance.
399 struct term *termp = set_curterm((struct term *)nullptr);
400 (void)del_curterm(termp); // Drop any errors here.
402 // Return true if we found a color capabilities for the current terminal.
407 // Otherwise, be conservative.
411 bool Process::FileDescriptorHasColors(int fd) {
412 // A file descriptor has colors if it is displayed and the terminal has
414 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
417 bool Process::StandardOutHasColors() {
418 return FileDescriptorHasColors(STDOUT_FILENO);
421 bool Process::StandardErrHasColors() {
422 return FileDescriptorHasColors(STDERR_FILENO);
425 void Process::UseANSIEscapeCodes(bool /*enable*/) {
429 bool Process::ColorNeedsFlush() {
430 // No, we use ANSI escape sequences.
434 const char *Process::OutputColor(char code, bool bold, bool bg) {
435 return colorcodes[bg?1:0][bold?1:0][code&7];
438 const char *Process::OutputBold(bool bg) {
442 const char *Process::OutputReverse() {
446 const char *Process::ResetColor() {
450 #if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
451 static unsigned GetRandomNumberSeed() {
452 // Attempt to get the initial seed from /dev/urandom, if possible.
453 if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
455 int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
456 ::fclose(RandomSource);
458 // Return the seed if the read was successful.
463 // Otherwise, swizzle the current time and the process ID to form a reasonable
465 TimeValue Now = TimeValue::now();
466 return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
470 unsigned llvm::sys::Process::GetRandomNumber() {
471 #if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
474 static int x = (::srand(GetRandomNumberSeed()), 0);