Support: Don't call close again if we get EINTR
[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 std::error_code Process::SafelyCloseFileDescriptor(int FD) {
262   // Create a signal set filled with *all* signals.
263   sigset_t FullSet;
264   if (sigfillset(&FullSet) < 0)
265     return std::error_code(errno, std::generic_category());
266   // Atomically swap our current signal mask with a full mask.
267   sigset_t SavedSet;
268   if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
269     return std::error_code(EC, std::generic_category());
270   // Attempt to close the file descriptor.
271   // We need to save the error, if one occurs, because our subsequent call to
272   // pthread_sigmask might tamper with errno.
273   int ErrnoFromClose = 0;
274   if (::close(FD) < 0)
275     ErrnoFromClose = errno;
276   // Restore the signal mask back to what we saved earlier.
277   int EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
278   // The error code from close takes precedence over the one from
279   // pthread_sigmask.
280   if (ErrnoFromClose)
281     return std::error_code(ErrnoFromClose, std::generic_category());
282   return std::error_code(EC, std::generic_category());
283 }
284
285 bool Process::StandardInIsUserInput() {
286   return FileDescriptorIsDisplayed(STDIN_FILENO);
287 }
288
289 bool Process::StandardOutIsDisplayed() {
290   return FileDescriptorIsDisplayed(STDOUT_FILENO);
291 }
292
293 bool Process::StandardErrIsDisplayed() {
294   return FileDescriptorIsDisplayed(STDERR_FILENO);
295 }
296
297 bool Process::FileDescriptorIsDisplayed(int fd) {
298 #if HAVE_ISATTY
299   return isatty(fd);
300 #else
301   // If we don't have isatty, just return false.
302   return false;
303 #endif
304 }
305
306 static unsigned getColumns(int FileID) {
307   // If COLUMNS is defined in the environment, wrap to that many columns.
308   if (const char *ColumnsStr = std::getenv("COLUMNS")) {
309     int Columns = std::atoi(ColumnsStr);
310     if (Columns > 0)
311       return Columns;
312   }
313
314   unsigned Columns = 0;
315
316 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
317   // Try to determine the width of the terminal.
318   struct winsize ws;
319   if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
320     Columns = ws.ws_col;
321 #endif
322
323   return Columns;
324 }
325
326 unsigned Process::StandardOutColumns() {
327   if (!StandardOutIsDisplayed())
328     return 0;
329
330   return getColumns(1);
331 }
332
333 unsigned Process::StandardErrColumns() {
334   if (!StandardErrIsDisplayed())
335     return 0;
336
337   return getColumns(2);
338 }
339
340 #ifdef HAVE_TERMINFO
341 // We manually declare these extern functions because finding the correct
342 // headers from various terminfo, curses, or other sources is harder than
343 // writing their specs down.
344 extern "C" int setupterm(char *term, int filedes, int *errret);
345 extern "C" struct term *set_curterm(struct term *termp);
346 extern "C" int del_curterm(struct term *termp);
347 extern "C" int tigetnum(char *capname);
348 #endif
349
350 #ifdef HAVE_TERMINFO
351 static ManagedStatic<sys::Mutex> TermColorMutex;
352 #endif
353
354 static bool terminalHasColors(int fd) {
355 #ifdef HAVE_TERMINFO
356   // First, acquire a global lock because these C routines are thread hostile.
357   MutexGuard G(*TermColorMutex);
358
359   int errret = 0;
360   if (setupterm((char *)nullptr, fd, &errret) != 0)
361     // Regardless of why, if we can't get terminfo, we shouldn't try to print
362     // colors.
363     return false;
364
365   // Test whether the terminal as set up supports color output. How to do this
366   // isn't entirely obvious. We can use the curses routine 'has_colors' but it
367   // would be nice to avoid a dependency on curses proper when we can make do
368   // with a minimal terminfo parsing library. Also, we don't really care whether
369   // the terminal supports the curses-specific color changing routines, merely
370   // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
371   // strategy here is just to query the baseline colors capability and if it
372   // supports colors at all to assume it will translate the escape codes into
373   // whatever range of colors it does support. We can add more detailed tests
374   // here if users report them as necessary.
375   //
376   // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
377   // the terminfo says that no colors are supported.
378   bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
379
380   // Now extract the structure allocated by setupterm and free its memory
381   // through a really silly dance.
382   struct term *termp = set_curterm((struct term *)nullptr);
383   (void)del_curterm(termp); // Drop any errors here.
384
385   // Return true if we found a color capabilities for the current terminal.
386   if (HasColors)
387     return true;
388 #endif
389
390   // Otherwise, be conservative.
391   return false;
392 }
393
394 bool Process::FileDescriptorHasColors(int fd) {
395   // A file descriptor has colors if it is displayed and the terminal has
396   // colors.
397   return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
398 }
399
400 bool Process::StandardOutHasColors() {
401   return FileDescriptorHasColors(STDOUT_FILENO);
402 }
403
404 bool Process::StandardErrHasColors() {
405   return FileDescriptorHasColors(STDERR_FILENO);
406 }
407
408 void Process::UseANSIEscapeCodes(bool /*enable*/) {
409   // No effect.
410 }
411
412 bool Process::ColorNeedsFlush() {
413   // No, we use ANSI escape sequences.
414   return false;
415 }
416
417 const char *Process::OutputColor(char code, bool bold, bool bg) {
418   return colorcodes[bg?1:0][bold?1:0][code&7];
419 }
420
421 const char *Process::OutputBold(bool bg) {
422   return "\033[1m";
423 }
424
425 const char *Process::OutputReverse() {
426   return "\033[7m";
427 }
428
429 const char *Process::ResetColor() {
430   return "\033[0m";
431 }
432
433 #if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
434 static unsigned GetRandomNumberSeed() {
435   // Attempt to get the initial seed from /dev/urandom, if possible.
436   if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
437     unsigned seed;
438     int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
439     ::fclose(RandomSource);
440
441     // Return the seed if the read was successful.
442     if (count == 1)
443       return seed;
444   }
445
446   // Otherwise, swizzle the current time and the process ID to form a reasonable
447   // seed.
448   TimeValue Now = TimeValue::now();
449   return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
450 }
451 #endif
452
453 unsigned llvm::sys::Process::GetRandomNumber() {
454 #if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
455   return arc4random();
456 #else
457   static int x = (::srand(GetRandomNumberSeed()), 0);
458   (void)x;
459   return ::rand();
460 #endif
461 }