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>
33 // DragonFlyBSD, OpenBSD, and Bitrig have deprecated <malloc.h> for
34 // <stdlib.h> instead. Unix.h includes this for us already.
35 #if defined(HAVE_MALLOC_H) && !defined(__DragonFly__) && \
36 !defined(__OpenBSD__) && !defined(__Bitrig__)
39 #ifdef HAVE_MALLOC_MALLOC_H
40 #include <malloc/malloc.h>
42 #ifdef HAVE_SYS_IOCTL_H
43 # include <sys/ioctl.h>
49 //===----------------------------------------------------------------------===//
50 //=== WARNING: Implementation here must contain only generic UNIX code that
51 //=== is guaranteed to work on *all* UNIX variants.
52 //===----------------------------------------------------------------------===//
57 process::id_type self_process::get_id() {
61 static std::pair<TimeValue, TimeValue> getRUsageTimes() {
62 #if defined(HAVE_GETRUSAGE)
64 ::getrusage(RUSAGE_SELF, &RU);
65 return std::make_pair(
67 static_cast<TimeValue::SecondsType>(RU.ru_utime.tv_sec),
68 static_cast<TimeValue::NanoSecondsType>(
69 RU.ru_utime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)),
71 static_cast<TimeValue::SecondsType>(RU.ru_stime.tv_sec),
72 static_cast<TimeValue::NanoSecondsType>(
73 RU.ru_stime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)));
75 #warning Cannot get usage times on this platform
76 return std::make_pair(TimeValue(), TimeValue());
80 TimeValue self_process::get_user_time() const {
81 #if _POSIX_TIMERS > 0 && _POSIX_CPUTIME > 0
82 // Try to get a high resolution CPU timer.
84 if (::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &TS) == 0)
85 return TimeValue(static_cast<TimeValue::SecondsType>(TS.tv_sec),
86 static_cast<TimeValue::NanoSecondsType>(TS.tv_nsec));
89 // Otherwise fall back to rusage based timing.
90 return getRUsageTimes().first;
93 TimeValue self_process::get_system_time() const {
94 // We can only collect system time by inspecting the results of getrusage.
95 return getRUsageTimes().second;
98 // On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
99 // offset in mmap(3) should be aligned to the AllocationGranularity.
100 static unsigned getPageSize() {
101 #if defined(HAVE_GETPAGESIZE)
102 const int page_size = ::getpagesize();
103 #elif defined(HAVE_SYSCONF)
104 long page_size = ::sysconf(_SC_PAGE_SIZE);
106 #warning Cannot get the page size on this machine
108 return static_cast<unsigned>(page_size);
111 // This constructor guaranteed to be run exactly once on a single thread, and
112 // sets up various process invariants that can be queried cheaply from then on.
113 self_process::self_process() : PageSize(getPageSize()) {
117 size_t Process::GetMallocUsage() {
118 #if defined(HAVE_MALLINFO)
122 #elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
123 malloc_statistics_t Stats;
124 malloc_zone_statistics(malloc_default_zone(), &Stats);
125 return Stats.size_in_use; // darwin
126 #elif defined(HAVE_SBRK)
127 // Note this is only an approximation and more closely resembles
128 // the value returned by mallinfo in the arena field.
129 static char *StartOfMemory = reinterpret_cast<char*>(::sbrk(0));
130 char *EndOfMemory = (char*)sbrk(0);
131 if (EndOfMemory != ((char*)-1) && StartOfMemory != ((char*)-1))
132 return EndOfMemory - StartOfMemory;
136 #warning Cannot get malloc info on this platform
141 void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
142 TimeValue &sys_time) {
143 elapsed = TimeValue::now();
144 std::tie(user_time, sys_time) = getRUsageTimes();
147 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
148 #include <mach/mach.h>
151 // Some LLVM programs such as bugpoint produce core files as a normal part of
152 // their operation. To prevent the disk from filling up, this function
153 // does what's necessary to prevent their generation.
154 void Process::PreventCoreFiles() {
157 rlim.rlim_cur = rlim.rlim_max = 0;
158 setrlimit(RLIMIT_CORE, &rlim);
161 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
162 // Disable crash reporting on Mac OS X 10.0-10.4
164 // get information about the original set of exception ports for the task
165 mach_msg_type_number_t Count = 0;
166 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
167 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
168 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
169 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
171 task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
172 &Count, OriginalPorts, OriginalBehaviors,
174 if (err == KERN_SUCCESS) {
175 // replace each with MACH_PORT_NULL.
176 for (unsigned i = 0; i != Count; ++i)
177 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
178 MACH_PORT_NULL, OriginalBehaviors[i],
182 // Disable crash reporting on Mac OS X 10.5
183 signal(SIGABRT, _exit);
184 signal(SIGILL, _exit);
185 signal(SIGFPE, _exit);
186 signal(SIGSEGV, _exit);
187 signal(SIGBUS, _exit);
191 Optional<std::string> Process::GetEnv(StringRef Name) {
192 std::string NameStr = Name.str();
193 const char *Val = ::getenv(NameStr.c_str());
196 return std::string(Val);
200 Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
201 ArrayRef<const char *> ArgsIn,
202 SpecificBumpPtrAllocator<char> &) {
203 ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
205 return std::error_code();
211 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
212 void keepOpen() { KeepOpen = true; }
214 if (!KeepOpen && FD >= 0)
219 FDCloser(const FDCloser &) LLVM_DELETED_FUNCTION;
220 void operator=(const FDCloser &) LLVM_DELETED_FUNCTION;
227 std::error_code Process::FixupStandardFileDescriptors() {
229 FDCloser FDC(NullFD);
230 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
231 for (int StandardFD : StandardFDs) {
234 while (fstat(StandardFD, &st) < 0) {
235 assert(errno && "expected errno to be set if fstat failed!");
236 // fstat should return EBADF if the file descriptor is closed.
239 // retry fstat if we got EINTR, otherwise bubble up the failure.
241 return std::error_code(errno, std::generic_category());
243 // if fstat succeeds, move on to the next FD.
246 assert(errno == EBADF && "expected errno to have EBADF at this point!");
249 while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
252 return std::error_code(errno, std::generic_category());
256 if (NullFD == StandardFD)
258 else if (dup2(NullFD, StandardFD) < 0)
259 return std::error_code(errno, std::generic_category());
261 return std::error_code();
264 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
265 // Create a signal set filled with *all* signals.
267 if (sigfillset(&FullSet) < 0)
268 return std::error_code(errno, std::generic_category());
269 // Atomically swap our current signal mask with a full mask.
271 #if LLVM_ENABLE_THREADS
272 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
273 return std::error_code(EC, std::generic_category());
275 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
276 return std::error_code(errno, std::generic_category());
278 // Attempt to close the file descriptor.
279 // We need to save the error, if one occurs, because our subsequent call to
280 // pthread_sigmask might tamper with errno.
281 int ErrnoFromClose = 0;
283 ErrnoFromClose = errno;
284 // Restore the signal mask back to what we saved earlier.
286 #if LLVM_ENABLE_THREADS
287 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
289 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
292 // The error code from close takes precedence over the one from
295 return std::error_code(ErrnoFromClose, std::generic_category());
296 return std::error_code(EC, std::generic_category());
299 bool Process::StandardInIsUserInput() {
300 return FileDescriptorIsDisplayed(STDIN_FILENO);
303 bool Process::StandardOutIsDisplayed() {
304 return FileDescriptorIsDisplayed(STDOUT_FILENO);
307 bool Process::StandardErrIsDisplayed() {
308 return FileDescriptorIsDisplayed(STDERR_FILENO);
311 bool Process::FileDescriptorIsDisplayed(int fd) {
315 // If we don't have isatty, just return false.
320 static unsigned getColumns(int FileID) {
321 // If COLUMNS is defined in the environment, wrap to that many columns.
322 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
323 int Columns = std::atoi(ColumnsStr);
328 unsigned Columns = 0;
330 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
331 // Try to determine the width of the terminal.
333 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
340 unsigned Process::StandardOutColumns() {
341 if (!StandardOutIsDisplayed())
344 return getColumns(1);
347 unsigned Process::StandardErrColumns() {
348 if (!StandardErrIsDisplayed())
351 return getColumns(2);
355 // We manually declare these extern functions because finding the correct
356 // headers from various terminfo, curses, or other sources is harder than
357 // writing their specs down.
358 extern "C" int setupterm(char *term, int filedes, int *errret);
359 extern "C" struct term *set_curterm(struct term *termp);
360 extern "C" int del_curterm(struct term *termp);
361 extern "C" int tigetnum(char *capname);
365 static ManagedStatic<sys::Mutex> TermColorMutex;
368 static bool terminalHasColors(int fd) {
370 // First, acquire a global lock because these C routines are thread hostile.
371 MutexGuard G(*TermColorMutex);
374 if (setupterm((char *)nullptr, fd, &errret) != 0)
375 // Regardless of why, if we can't get terminfo, we shouldn't try to print
379 // Test whether the terminal as set up supports color output. How to do this
380 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
381 // would be nice to avoid a dependency on curses proper when we can make do
382 // with a minimal terminfo parsing library. Also, we don't really care whether
383 // the terminal supports the curses-specific color changing routines, merely
384 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
385 // strategy here is just to query the baseline colors capability and if it
386 // supports colors at all to assume it will translate the escape codes into
387 // whatever range of colors it does support. We can add more detailed tests
388 // here if users report them as necessary.
390 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
391 // the terminfo says that no colors are supported.
392 bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
394 // Now extract the structure allocated by setupterm and free its memory
395 // through a really silly dance.
396 struct term *termp = set_curterm((struct term *)nullptr);
397 (void)del_curterm(termp); // Drop any errors here.
399 // Return true if we found a color capabilities for the current terminal.
404 // Otherwise, be conservative.
408 bool Process::FileDescriptorHasColors(int fd) {
409 // A file descriptor has colors if it is displayed and the terminal has
411 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
414 bool Process::StandardOutHasColors() {
415 return FileDescriptorHasColors(STDOUT_FILENO);
418 bool Process::StandardErrHasColors() {
419 return FileDescriptorHasColors(STDERR_FILENO);
422 void Process::UseANSIEscapeCodes(bool /*enable*/) {
426 bool Process::ColorNeedsFlush() {
427 // No, we use ANSI escape sequences.
431 const char *Process::OutputColor(char code, bool bold, bool bg) {
432 return colorcodes[bg?1:0][bold?1:0][code&7];
435 const char *Process::OutputBold(bool bg) {
439 const char *Process::OutputReverse() {
443 const char *Process::ResetColor() {
447 #if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
448 static unsigned GetRandomNumberSeed() {
449 // Attempt to get the initial seed from /dev/urandom, if possible.
450 if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
452 int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
453 ::fclose(RandomSource);
455 // Return the seed if the read was successful.
460 // Otherwise, swizzle the current time and the process ID to form a reasonable
462 TimeValue Now = TimeValue::now();
463 return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
467 unsigned llvm::sys::Process::GetRandomNumber() {
468 #if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
471 static int x = (::srand(GetRandomNumberSeed()), 0);