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