Support: Add a utility to remap std{in,out,err} to /dev/null if closed
[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 // DragonFlyBSD, OpenBSD, and Bitrig have deprecated <malloc.h> for
31 // <stdlib.h> instead. Unix.h includes this for us already.
32 #if defined(HAVE_MALLOC_H) && !defined(__DragonFly__) && \
33     !defined(__OpenBSD__) && !defined(__Bitrig__)
34 #include <malloc.h>
35 #endif
36 #ifdef HAVE_MALLOC_MALLOC_H
37 #include <malloc/malloc.h>
38 #endif
39 #ifdef HAVE_SYS_IOCTL_H
40 #  include <sys/ioctl.h>
41 #endif
42 #ifdef HAVE_TERMIOS_H
43 #  include <termios.h>
44 #endif
45
46 //===----------------------------------------------------------------------===//
47 //=== WARNING: Implementation here must contain only generic UNIX code that
48 //===          is guaranteed to work on *all* UNIX variants.
49 //===----------------------------------------------------------------------===//
50
51 using namespace llvm;
52 using namespace sys;
53
54 process::id_type self_process::get_id() {
55   return getpid();
56 }
57
58 static std::pair<TimeValue, TimeValue> getRUsageTimes() {
59 #if defined(HAVE_GETRUSAGE)
60   struct rusage RU;
61   ::getrusage(RUSAGE_SELF, &RU);
62   return std::make_pair(
63       TimeValue(
64           static_cast<TimeValue::SecondsType>(RU.ru_utime.tv_sec),
65           static_cast<TimeValue::NanoSecondsType>(
66               RU.ru_utime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)),
67       TimeValue(
68           static_cast<TimeValue::SecondsType>(RU.ru_stime.tv_sec),
69           static_cast<TimeValue::NanoSecondsType>(
70               RU.ru_stime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)));
71 #else
72 #warning Cannot get usage times on this platform
73   return std::make_pair(TimeValue(), TimeValue());
74 #endif
75 }
76
77 TimeValue self_process::get_user_time() const {
78 #if _POSIX_TIMERS > 0 && _POSIX_CPUTIME > 0
79   // Try to get a high resolution CPU timer.
80   struct timespec TS;
81   if (::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &TS) == 0)
82     return TimeValue(static_cast<TimeValue::SecondsType>(TS.tv_sec),
83                      static_cast<TimeValue::NanoSecondsType>(TS.tv_nsec));
84 #endif
85
86   // Otherwise fall back to rusage based timing.
87   return getRUsageTimes().first;
88 }
89
90 TimeValue self_process::get_system_time() const {
91   // We can only collect system time by inspecting the results of getrusage.
92   return getRUsageTimes().second;
93 }
94
95 // On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
96 // offset in mmap(3) should be aligned to the AllocationGranularity.
97 static unsigned getPageSize() {
98 #if defined(HAVE_GETPAGESIZE)
99   const int page_size = ::getpagesize();
100 #elif defined(HAVE_SYSCONF)
101   long page_size = ::sysconf(_SC_PAGE_SIZE);
102 #else
103 #warning Cannot get the page size on this machine
104 #endif
105   return static_cast<unsigned>(page_size);
106 }
107
108 // This constructor guaranteed to be run exactly once on a single thread, and
109 // sets up various process invariants that can be queried cheaply from then on.
110 self_process::self_process() : PageSize(getPageSize()) {
111 }
112
113
114 size_t Process::GetMallocUsage() {
115 #if defined(HAVE_MALLINFO)
116   struct mallinfo mi;
117   mi = ::mallinfo();
118   return mi.uordblks;
119 #elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
120   malloc_statistics_t Stats;
121   malloc_zone_statistics(malloc_default_zone(), &Stats);
122   return Stats.size_in_use;   // darwin
123 #elif defined(HAVE_SBRK)
124   // Note this is only an approximation and more closely resembles
125   // the value returned by mallinfo in the arena field.
126   static char *StartOfMemory = reinterpret_cast<char*>(::sbrk(0));
127   char *EndOfMemory = (char*)sbrk(0);
128   if (EndOfMemory != ((char*)-1) && StartOfMemory != ((char*)-1))
129     return EndOfMemory - StartOfMemory;
130   else
131     return 0;
132 #else
133 #warning Cannot get malloc info on this platform
134   return 0;
135 #endif
136 }
137
138 void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
139                            TimeValue &sys_time) {
140   elapsed = TimeValue::now();
141   std::tie(user_time, sys_time) = getRUsageTimes();
142 }
143
144 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
145 #include <mach/mach.h>
146 #endif
147
148 // Some LLVM programs such as bugpoint produce core files as a normal part of
149 // their operation. To prevent the disk from filling up, this function
150 // does what's necessary to prevent their generation.
151 void Process::PreventCoreFiles() {
152 #if HAVE_SETRLIMIT
153   struct rlimit rlim;
154   rlim.rlim_cur = rlim.rlim_max = 0;
155   setrlimit(RLIMIT_CORE, &rlim);
156 #endif
157
158 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
159   // Disable crash reporting on Mac OS X 10.0-10.4
160
161   // get information about the original set of exception ports for the task
162   mach_msg_type_number_t Count = 0;
163   exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
164   exception_port_t OriginalPorts[EXC_TYPES_COUNT];
165   exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
166   thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
167   kern_return_t err =
168     task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
169                              &Count, OriginalPorts, OriginalBehaviors,
170                              OriginalFlavors);
171   if (err == KERN_SUCCESS) {
172     // replace each with MACH_PORT_NULL.
173     for (unsigned i = 0; i != Count; ++i)
174       task_set_exception_ports(mach_task_self(), OriginalMasks[i],
175                                MACH_PORT_NULL, OriginalBehaviors[i],
176                                OriginalFlavors[i]);
177   }
178
179   // Disable crash reporting on Mac OS X 10.5
180   signal(SIGABRT, _exit);
181   signal(SIGILL,  _exit);
182   signal(SIGFPE,  _exit);
183   signal(SIGSEGV, _exit);
184   signal(SIGBUS,  _exit);
185 #endif
186 }
187
188 Optional<std::string> Process::GetEnv(StringRef Name) {
189   std::string NameStr = Name.str();
190   const char *Val = ::getenv(NameStr.c_str());
191   if (!Val)
192     return None;
193   return std::string(Val);
194 }
195
196 std::error_code
197 Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
198                            ArrayRef<const char *> ArgsIn,
199                            SpecificBumpPtrAllocator<char> &) {
200   ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
201
202   return std::error_code();
203 }
204
205 namespace {
206 class FDCloser {
207 public:
208   FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
209   void keepOpen() { KeepOpen = true; }
210   ~FDCloser() {
211     if (!KeepOpen && FD >= 0)
212       ::close(FD);
213   }
214
215 private:
216   FDCloser(const FDCloser &) LLVM_DELETED_FUNCTION;
217   void operator=(const FDCloser &) LLVM_DELETED_FUNCTION;
218
219   int &FD;
220   bool KeepOpen;
221 };
222 }
223
224 std::error_code Process::FixupStandardFileDescriptors() {
225   int NullFD = -1;
226   FDCloser FDC(NullFD);
227   const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
228   for (int StandardFD : StandardFDs) {
229     struct stat st;
230     errno = 0;
231     while (fstat(StandardFD, &st) < 0) {
232       assert(errno && "expected errno to be set if fstat failed!");
233       // fstat should return EBADF if the file descriptor is closed.
234       if (errno == EBADF)
235         break;
236       // retry fstat if we got EINTR, otherwise bubble up the failure.
237       if (errno != EINTR)
238         return std::error_code(errno, std::generic_category());
239     }
240     // if fstat succeeds, move on to the next FD.
241     if (!errno)
242       continue;
243     assert(errno == EBADF && "expected errno to have EBADF at this point!");
244
245     if (NullFD < 0) {
246       while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
247         if (errno == EINTR)
248           continue;
249         return std::error_code(errno, std::generic_category());
250       }
251     }
252
253     if (NullFD == StandardFD)
254       FDC.keepOpen();
255     else if (dup2(NullFD, StandardFD) < 0)
256       return std::error_code(errno, std::generic_category());
257   }
258   return std::error_code();
259 }
260
261 bool Process::StandardInIsUserInput() {
262   return FileDescriptorIsDisplayed(STDIN_FILENO);
263 }
264
265 bool Process::StandardOutIsDisplayed() {
266   return FileDescriptorIsDisplayed(STDOUT_FILENO);
267 }
268
269 bool Process::StandardErrIsDisplayed() {
270   return FileDescriptorIsDisplayed(STDERR_FILENO);
271 }
272
273 bool Process::FileDescriptorIsDisplayed(int fd) {
274 #if HAVE_ISATTY
275   return isatty(fd);
276 #else
277   // If we don't have isatty, just return false.
278   return false;
279 #endif
280 }
281
282 static unsigned getColumns(int FileID) {
283   // If COLUMNS is defined in the environment, wrap to that many columns.
284   if (const char *ColumnsStr = std::getenv("COLUMNS")) {
285     int Columns = std::atoi(ColumnsStr);
286     if (Columns > 0)
287       return Columns;
288   }
289
290   unsigned Columns = 0;
291
292 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
293   // Try to determine the width of the terminal.
294   struct winsize ws;
295   if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
296     Columns = ws.ws_col;
297 #endif
298
299   return Columns;
300 }
301
302 unsigned Process::StandardOutColumns() {
303   if (!StandardOutIsDisplayed())
304     return 0;
305
306   return getColumns(1);
307 }
308
309 unsigned Process::StandardErrColumns() {
310   if (!StandardErrIsDisplayed())
311     return 0;
312
313   return getColumns(2);
314 }
315
316 #ifdef HAVE_TERMINFO
317 // We manually declare these extern functions because finding the correct
318 // headers from various terminfo, curses, or other sources is harder than
319 // writing their specs down.
320 extern "C" int setupterm(char *term, int filedes, int *errret);
321 extern "C" struct term *set_curterm(struct term *termp);
322 extern "C" int del_curterm(struct term *termp);
323 extern "C" int tigetnum(char *capname);
324 #endif
325
326 #ifdef HAVE_TERMINFO
327 static ManagedStatic<sys::Mutex> TermColorMutex;
328 #endif
329
330 static bool terminalHasColors(int fd) {
331 #ifdef HAVE_TERMINFO
332   // First, acquire a global lock because these C routines are thread hostile.
333   MutexGuard G(*TermColorMutex);
334
335   int errret = 0;
336   if (setupterm((char *)nullptr, fd, &errret) != 0)
337     // Regardless of why, if we can't get terminfo, we shouldn't try to print
338     // colors.
339     return false;
340
341   // Test whether the terminal as set up supports color output. How to do this
342   // isn't entirely obvious. We can use the curses routine 'has_colors' but it
343   // would be nice to avoid a dependency on curses proper when we can make do
344   // with a minimal terminfo parsing library. Also, we don't really care whether
345   // the terminal supports the curses-specific color changing routines, merely
346   // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
347   // strategy here is just to query the baseline colors capability and if it
348   // supports colors at all to assume it will translate the escape codes into
349   // whatever range of colors it does support. We can add more detailed tests
350   // here if users report them as necessary.
351   //
352   // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
353   // the terminfo says that no colors are supported.
354   bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
355
356   // Now extract the structure allocated by setupterm and free its memory
357   // through a really silly dance.
358   struct term *termp = set_curterm((struct term *)nullptr);
359   (void)del_curterm(termp); // Drop any errors here.
360
361   // Return true if we found a color capabilities for the current terminal.
362   if (HasColors)
363     return true;
364 #endif
365
366   // Otherwise, be conservative.
367   return false;
368 }
369
370 bool Process::FileDescriptorHasColors(int fd) {
371   // A file descriptor has colors if it is displayed and the terminal has
372   // colors.
373   return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
374 }
375
376 bool Process::StandardOutHasColors() {
377   return FileDescriptorHasColors(STDOUT_FILENO);
378 }
379
380 bool Process::StandardErrHasColors() {
381   return FileDescriptorHasColors(STDERR_FILENO);
382 }
383
384 void Process::UseANSIEscapeCodes(bool /*enable*/) {
385   // No effect.
386 }
387
388 bool Process::ColorNeedsFlush() {
389   // No, we use ANSI escape sequences.
390   return false;
391 }
392
393 const char *Process::OutputColor(char code, bool bold, bool bg) {
394   return colorcodes[bg?1:0][bold?1:0][code&7];
395 }
396
397 const char *Process::OutputBold(bool bg) {
398   return "\033[1m";
399 }
400
401 const char *Process::OutputReverse() {
402   return "\033[7m";
403 }
404
405 const char *Process::ResetColor() {
406   return "\033[0m";
407 }
408
409 #if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
410 static unsigned GetRandomNumberSeed() {
411   // Attempt to get the initial seed from /dev/urandom, if possible.
412   if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
413     unsigned seed;
414     int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
415     ::fclose(RandomSource);
416
417     // Return the seed if the read was successful.
418     if (count == 1)
419       return seed;
420   }
421
422   // Otherwise, swizzle the current time and the process ID to form a reasonable
423   // seed.
424   TimeValue Now = TimeValue::now();
425   return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
426 }
427 #endif
428
429 unsigned llvm::sys::Process::GetRandomNumber() {
430 #if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
431   return arc4random();
432 #else
433   static int x = (::srand(GetRandomNumberSeed()), 0);
434   (void)x;
435   return ::rand();
436 #endif
437 }