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"
23 #ifdef HAVE_SYS_TIME_H
26 #ifdef HAVE_SYS_RESOURCE_H
27 #include <sys/resource.h>
29 #ifdef HAVE_SYS_STAT_H
35 // DragonFlyBSD, OpenBSD, and Bitrig have deprecated <malloc.h> for
36 // <stdlib.h> instead. Unix.h includes this for us already.
37 #if defined(HAVE_MALLOC_H) && !defined(__DragonFly__) && \
38 !defined(__OpenBSD__) && !defined(__Bitrig__)
41 #if defined(HAVE_MALLCTL)
42 #include <malloc_np.h>
44 #ifdef HAVE_MALLOC_MALLOC_H
45 #include <malloc/malloc.h>
47 #ifdef HAVE_SYS_IOCTL_H
48 # include <sys/ioctl.h>
54 //===----------------------------------------------------------------------===//
55 //=== WARNING: Implementation here must contain only generic UNIX code that
56 //=== is guaranteed to work on *all* UNIX variants.
57 //===----------------------------------------------------------------------===//
62 static std::pair<std::chrono::microseconds, std::chrono::microseconds> getRUsageTimes() {
63 #if defined(HAVE_GETRUSAGE)
65 ::getrusage(RUSAGE_SELF, &RU);
66 return { toDuration(RU.ru_utime), toDuration(RU.ru_stime) };
68 #warning Cannot get usage times on this platform
69 return { std::chrono::microseconds::zero(), std::chrono::microseconds::zero() };
73 // On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
74 // offset in mmap(3) should be aligned to the AllocationGranularity.
75 unsigned Process::getPageSize() {
76 #if defined(HAVE_GETPAGESIZE)
77 static const int page_size = ::getpagesize();
78 #elif defined(HAVE_SYSCONF)
79 static long page_size = ::sysconf(_SC_PAGE_SIZE);
81 #warning Cannot get the page size on this machine
83 return static_cast<unsigned>(page_size);
86 size_t Process::GetMallocUsage() {
87 #if defined(HAVE_MALLINFO)
91 #elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
92 malloc_statistics_t Stats;
93 malloc_zone_statistics(malloc_default_zone(), &Stats);
94 return Stats.size_in_use; // darwin
95 #elif defined(HAVE_MALLCTL)
98 if (mallctl("stats.allocated", &alloc, &sz, NULL, 0) == 0)
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;
110 #warning Cannot get malloc info on this platform
115 void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
116 std::chrono::nanoseconds &sys_time) {
117 elapsed = std::chrono::system_clock::now();
118 std::tie(user_time, sys_time) = getRUsageTimes();
121 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
122 #include <mach/mach.h>
125 // Some LLVM programs such as bugpoint produce core files as a normal part of
126 // their operation. To prevent the disk from filling up, this function
127 // does what's necessary to prevent their generation.
128 void Process::PreventCoreFiles() {
131 rlim.rlim_cur = rlim.rlim_max = 0;
132 setrlimit(RLIMIT_CORE, &rlim);
135 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
136 // Disable crash reporting on Mac OS X 10.0-10.4
138 // get information about the original set of exception ports for the task
139 mach_msg_type_number_t Count = 0;
140 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
141 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
142 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
143 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
145 task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
146 &Count, OriginalPorts, OriginalBehaviors,
148 if (err == KERN_SUCCESS) {
149 // replace each with MACH_PORT_NULL.
150 for (unsigned i = 0; i != Count; ++i)
151 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
152 MACH_PORT_NULL, OriginalBehaviors[i],
156 // Disable crash reporting on Mac OS X 10.5
157 signal(SIGABRT, _exit);
158 signal(SIGILL, _exit);
159 signal(SIGFPE, _exit);
160 signal(SIGSEGV, _exit);
161 signal(SIGBUS, _exit);
164 coreFilesPrevented = true;
167 Optional<std::string> Process::GetEnv(StringRef Name) {
168 std::string NameStr = Name.str();
169 const char *Val = ::getenv(NameStr.c_str());
172 return std::string(Val);
176 Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
177 ArrayRef<const char *> ArgsIn,
178 SpecificBumpPtrAllocator<char> &) {
179 ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
181 return std::error_code();
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 while (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.
215 // retry fstat if we got EINTR, otherwise bubble up the failure.
217 return std::error_code(errno, std::generic_category());
219 // if fstat succeeds, move on to the next FD.
222 assert(errno == EBADF && "expected errno to have EBADF at this point!");
225 while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
228 return std::error_code(errno, std::generic_category());
232 if (NullFD == StandardFD)
234 else if (dup2(NullFD, StandardFD) < 0)
235 return std::error_code(errno, std::generic_category());
237 return std::error_code();
240 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
241 // Create a signal set filled with *all* signals.
243 if (sigfillset(&FullSet) < 0)
244 return std::error_code(errno, std::generic_category());
245 // Atomically swap our current signal mask with a full mask.
247 #if LLVM_ENABLE_THREADS
248 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
249 return std::error_code(EC, std::generic_category());
251 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
252 return std::error_code(errno, std::generic_category());
254 // Attempt to close the file descriptor.
255 // We need to save the error, if one occurs, because our subsequent call to
256 // pthread_sigmask might tamper with errno.
257 int ErrnoFromClose = 0;
259 ErrnoFromClose = errno;
260 // Restore the signal mask back to what we saved earlier.
262 #if LLVM_ENABLE_THREADS
263 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
265 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
268 // The error code from close takes precedence over the one from
271 return std::error_code(ErrnoFromClose, std::generic_category());
272 return std::error_code(EC, std::generic_category());
275 bool Process::StandardInIsUserInput() {
276 return FileDescriptorIsDisplayed(STDIN_FILENO);
279 bool Process::StandardOutIsDisplayed() {
280 return FileDescriptorIsDisplayed(STDOUT_FILENO);
283 bool Process::StandardErrIsDisplayed() {
284 return FileDescriptorIsDisplayed(STDERR_FILENO);
287 bool Process::FileDescriptorIsDisplayed(int fd) {
291 // If we don't have isatty, just return false.
296 static unsigned getColumns(int FileID) {
297 // If COLUMNS is defined in the environment, wrap to that many columns.
298 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
299 int Columns = std::atoi(ColumnsStr);
304 unsigned Columns = 0;
306 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
307 // Try to determine the width of the terminal.
309 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
316 unsigned Process::StandardOutColumns() {
317 if (!StandardOutIsDisplayed())
320 return getColumns(1);
323 unsigned Process::StandardErrColumns() {
324 if (!StandardErrIsDisplayed())
327 return getColumns(2);
331 // We manually declare these extern functions because finding the correct
332 // headers from various terminfo, curses, or other sources is harder than
333 // writing their specs down.
334 extern "C" int setupterm(char *term, int filedes, int *errret);
335 extern "C" struct term *set_curterm(struct term *termp);
336 extern "C" int del_curterm(struct term *termp);
337 extern "C" int tigetnum(char *capname);
341 static ManagedStatic<sys::Mutex> TermColorMutex;
344 static bool terminalHasColors(int fd) {
346 // First, acquire a global lock because these C routines are thread hostile.
347 MutexGuard G(*TermColorMutex);
350 if (setupterm((char *)nullptr, fd, &errret) != 0)
351 // Regardless of why, if we can't get terminfo, we shouldn't try to print
355 // Test whether the terminal as set up supports color output. How to do this
356 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
357 // would be nice to avoid a dependency on curses proper when we can make do
358 // with a minimal terminfo parsing library. Also, we don't really care whether
359 // the terminal supports the curses-specific color changing routines, merely
360 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
361 // strategy here is just to query the baseline colors capability and if it
362 // supports colors at all to assume it will translate the escape codes into
363 // whatever range of colors it does support. We can add more detailed tests
364 // here if users report them as necessary.
366 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
367 // the terminfo says that no colors are supported.
368 bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
370 // Now extract the structure allocated by setupterm and free its memory
371 // through a really silly dance.
372 struct term *termp = set_curterm((struct term *)nullptr);
373 (void)del_curterm(termp); // Drop any errors here.
375 // Return true if we found a color capabilities for the current terminal.
380 // Otherwise, be conservative.
384 bool Process::FileDescriptorHasColors(int fd) {
385 // A file descriptor has colors if it is displayed and the terminal has
387 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
390 bool Process::StandardOutHasColors() {
391 return FileDescriptorHasColors(STDOUT_FILENO);
394 bool Process::StandardErrHasColors() {
395 return FileDescriptorHasColors(STDERR_FILENO);
398 void Process::UseANSIEscapeCodes(bool /*enable*/) {
402 bool Process::ColorNeedsFlush() {
403 // No, we use ANSI escape sequences.
407 const char *Process::OutputColor(char code, bool bold, bool bg) {
408 return colorcodes[bg?1:0][bold?1:0][code&7];
411 const char *Process::OutputBold(bool bg) {
415 const char *Process::OutputReverse() {
419 const char *Process::ResetColor() {
423 #if !HAVE_DECL_ARC4RANDOM
424 static unsigned GetRandomNumberSeed() {
425 // Attempt to get the initial seed from /dev/urandom, if possible.
426 int urandomFD = open("/dev/urandom", O_RDONLY);
428 if (urandomFD != -1) {
430 // Don't use a buffered read to avoid reading more data
431 // from /dev/urandom than we need.
432 int count = read(urandomFD, (void *)&seed, sizeof(seed));
436 // Return the seed if the read was successful.
437 if (count == sizeof(seed))
441 // Otherwise, swizzle the current time and the process ID to form a reasonable
443 const auto Now = std::chrono::high_resolution_clock::now();
444 return hash_combine(Now.time_since_epoch().count(), ::getpid());
448 unsigned llvm::sys::Process::GetRandomNumber() {
449 #if HAVE_DECL_ARC4RANDOM
452 static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0);