a429bb3984c888a81bafe78031102c08686910ad
[oota-llvm.git] / lib / Support / Unix / Process.inc
1 //===- Unix/Process.cpp - Unix Process Implementation --------- -*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides the generic Unix implementation of the Process class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "Unix.h"
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"
21 #if HAVE_FCNTL_H
22 #include <fcntl.h>
23 #endif
24 #ifdef HAVE_SYS_TIME_H
25 #include <sys/time.h>
26 #endif
27 #ifdef HAVE_SYS_RESOURCE_H
28 #include <sys/resource.h>
29 #endif
30 #ifdef HAVE_SYS_STAT_H
31 #include <sys/stat.h>
32 #endif
33 #if HAVE_SIGNAL_H
34 #include <signal.h>
35 #endif
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__)
40 #include <malloc.h>
41 #endif
42 #ifdef HAVE_MALLOC_MALLOC_H
43 #include <malloc/malloc.h>
44 #endif
45 #ifdef HAVE_SYS_IOCTL_H
46 #  include <sys/ioctl.h>
47 #endif
48 #ifdef HAVE_TERMIOS_H
49 #  include <termios.h>
50 #endif
51
52 //===----------------------------------------------------------------------===//
53 //=== WARNING: Implementation here must contain only generic UNIX code that
54 //===          is guaranteed to work on *all* UNIX variants.
55 //===----------------------------------------------------------------------===//
56
57 using namespace llvm;
58 using namespace sys;
59
60 process::id_type self_process::get_id() {
61   return getpid();
62 }
63
64 static std::pair<TimeValue, TimeValue> getRUsageTimes() {
65 #if defined(HAVE_GETRUSAGE)
66   struct rusage RU;
67   ::getrusage(RUSAGE_SELF, &RU);
68   return std::make_pair(
69       TimeValue(
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)),
73       TimeValue(
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)));
77 #else
78 #warning Cannot get usage times on this platform
79   return std::make_pair(TimeValue(), TimeValue());
80 #endif
81 }
82
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.
86   struct timespec TS;
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));
90 #endif
91
92   // Otherwise fall back to rusage based timing.
93   return getRUsageTimes().first;
94 }
95
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;
99 }
100
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);
108 #else
109 #warning Cannot get the page size on this machine
110 #endif
111   return static_cast<unsigned>(page_size);
112 }
113
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()) {
117 }
118
119
120 size_t Process::GetMallocUsage() {
121 #if defined(HAVE_MALLINFO)
122   struct mallinfo mi;
123   mi = ::mallinfo();
124   return mi.uordblks;
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;
136   else
137     return 0;
138 #else
139 #warning Cannot get malloc info on this platform
140   return 0;
141 #endif
142 }
143
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();
148 }
149
150 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
151 #include <mach/mach.h>
152 #endif
153
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() {
158 #if HAVE_SETRLIMIT
159   struct rlimit rlim;
160   rlim.rlim_cur = rlim.rlim_max = 0;
161   setrlimit(RLIMIT_CORE, &rlim);
162 #endif
163
164 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
165   // Disable crash reporting on Mac OS X 10.0-10.4
166
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];
173   kern_return_t err =
174     task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
175                              &Count, OriginalPorts, OriginalBehaviors,
176                              OriginalFlavors);
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],
182                                OriginalFlavors[i]);
183   }
184
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);
191 #endif
192 }
193
194 Optional<std::string> Process::GetEnv(StringRef Name) {
195   std::string NameStr = Name.str();
196   const char *Val = ::getenv(NameStr.c_str());
197   if (!Val)
198     return None;
199   return std::string(Val);
200 }
201
202 std::error_code
203 Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
204                            ArrayRef<const char *> ArgsIn,
205                            SpecificBumpPtrAllocator<char> &) {
206   ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
207
208   return std::error_code();
209 }
210
211 namespace {
212 class FDCloser {
213 public:
214   FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
215   void keepOpen() { KeepOpen = true; }
216   ~FDCloser() {
217     if (!KeepOpen && FD >= 0)
218       ::close(FD);
219   }
220
221 private:
222   FDCloser(const FDCloser &) LLVM_DELETED_FUNCTION;
223   void operator=(const FDCloser &) LLVM_DELETED_FUNCTION;
224
225   int &FD;
226   bool KeepOpen;
227 };
228 }
229
230 std::error_code Process::FixupStandardFileDescriptors() {
231   int NullFD = -1;
232   FDCloser FDC(NullFD);
233   const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
234   for (int StandardFD : StandardFDs) {
235     struct stat st;
236     errno = 0;
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.
240       if (errno == EBADF)
241         break;
242       // retry fstat if we got EINTR, otherwise bubble up the failure.
243       if (errno != EINTR)
244         return std::error_code(errno, std::generic_category());
245     }
246     // if fstat succeeds, move on to the next FD.
247     if (!errno)
248       continue;
249     assert(errno == EBADF && "expected errno to have EBADF at this point!");
250
251     if (NullFD < 0) {
252       while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
253         if (errno == EINTR)
254           continue;
255         return std::error_code(errno, std::generic_category());
256       }
257     }
258
259     if (NullFD == StandardFD)
260       FDC.keepOpen();
261     else if (dup2(NullFD, StandardFD) < 0)
262       return std::error_code(errno, std::generic_category());
263   }
264   return std::error_code();
265 }
266
267 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
268   // Create a signal set filled with *all* signals.
269   sigset_t FullSet;
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.
273   sigset_t SavedSet;
274 #if LLVM_ENABLE_THREADS
275   if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
276     return std::error_code(EC, std::generic_category());
277 #else
278   if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
279     return std::error_code(errno, std::generic_category());
280 #endif
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;
285   if (::close(FD) < 0)
286     ErrnoFromClose = errno;
287   // Restore the signal mask back to what we saved earlier.
288   int EC = 0;
289 #if LLVM_ENABLE_THREADS
290   EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
291 #else
292   if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
293     EC = errno;
294 #endif
295   // The error code from close takes precedence over the one from
296   // pthread_sigmask.
297   if (ErrnoFromClose)
298     return std::error_code(ErrnoFromClose, std::generic_category());
299   return std::error_code(EC, std::generic_category());
300 }
301
302 bool Process::StandardInIsUserInput() {
303   return FileDescriptorIsDisplayed(STDIN_FILENO);
304 }
305
306 bool Process::StandardOutIsDisplayed() {
307   return FileDescriptorIsDisplayed(STDOUT_FILENO);
308 }
309
310 bool Process::StandardErrIsDisplayed() {
311   return FileDescriptorIsDisplayed(STDERR_FILENO);
312 }
313
314 bool Process::FileDescriptorIsDisplayed(int fd) {
315 #if HAVE_ISATTY
316   return isatty(fd);
317 #else
318   // If we don't have isatty, just return false.
319   return false;
320 #endif
321 }
322
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);
327     if (Columns > 0)
328       return Columns;
329   }
330
331   unsigned Columns = 0;
332
333 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
334   // Try to determine the width of the terminal.
335   struct winsize ws;
336   if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
337     Columns = ws.ws_col;
338 #endif
339
340   return Columns;
341 }
342
343 unsigned Process::StandardOutColumns() {
344   if (!StandardOutIsDisplayed())
345     return 0;
346
347   return getColumns(1);
348 }
349
350 unsigned Process::StandardErrColumns() {
351   if (!StandardErrIsDisplayed())
352     return 0;
353
354   return getColumns(2);
355 }
356
357 #ifdef HAVE_TERMINFO
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);
365 #endif
366
367 #ifdef HAVE_TERMINFO
368 static ManagedStatic<sys::Mutex> TermColorMutex;
369 #endif
370
371 static bool terminalHasColors(int fd) {
372 #ifdef HAVE_TERMINFO
373   // First, acquire a global lock because these C routines are thread hostile.
374   MutexGuard G(*TermColorMutex);
375
376   int errret = 0;
377   if (setupterm((char *)nullptr, fd, &errret) != 0)
378     // Regardless of why, if we can't get terminfo, we shouldn't try to print
379     // colors.
380     return false;
381
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.
392   //
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;
396
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.
401
402   // Return true if we found a color capabilities for the current terminal.
403   if (HasColors)
404     return true;
405 #endif
406
407   // Otherwise, be conservative.
408   return false;
409 }
410
411 bool Process::FileDescriptorHasColors(int fd) {
412   // A file descriptor has colors if it is displayed and the terminal has
413   // colors.
414   return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
415 }
416
417 bool Process::StandardOutHasColors() {
418   return FileDescriptorHasColors(STDOUT_FILENO);
419 }
420
421 bool Process::StandardErrHasColors() {
422   return FileDescriptorHasColors(STDERR_FILENO);
423 }
424
425 void Process::UseANSIEscapeCodes(bool /*enable*/) {
426   // No effect.
427 }
428
429 bool Process::ColorNeedsFlush() {
430   // No, we use ANSI escape sequences.
431   return false;
432 }
433
434 const char *Process::OutputColor(char code, bool bold, bool bg) {
435   return colorcodes[bg?1:0][bold?1:0][code&7];
436 }
437
438 const char *Process::OutputBold(bool bg) {
439   return "\033[1m";
440 }
441
442 const char *Process::OutputReverse() {
443   return "\033[7m";
444 }
445
446 const char *Process::ResetColor() {
447   return "\033[0m";
448 }
449
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")) {
454     unsigned seed;
455     int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
456     ::fclose(RandomSource);
457
458     // Return the seed if the read was successful.
459     if (count == 1)
460       return seed;
461   }
462
463   // Otherwise, swizzle the current time and the process ID to form a reasonable
464   // seed.
465   TimeValue Now = TimeValue::now();
466   return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
467 }
468 #endif
469
470 unsigned llvm::sys::Process::GetRandomNumber() {
471 #if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
472   return arc4random();
473 #else
474   static int x = (::srand(GetRandomNumberSeed()), 0);
475   (void)x;
476   return ::rand();
477 #endif
478 }