LLVM API Documentation

Unix/Process.inc
Go to the documentation of this file.
00001 //===- Unix/Process.cpp - Unix Process Implementation --------- -*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file provides the generic Unix implementation of the Process class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "Unix.h"
00015 #include "llvm/ADT/Hashing.h"
00016 #include "llvm/ADT/StringRef.h"
00017 #include "llvm/Support/Mutex.h"
00018 #include "llvm/Support/MutexGuard.h"
00019 #include "llvm/Support/TimeValue.h"
00020 #ifdef HAVE_SYS_TIME_H
00021 #include <sys/time.h>
00022 #endif
00023 #ifdef HAVE_SYS_RESOURCE_H
00024 #include <sys/resource.h>
00025 #endif
00026 // DragonFlyBSD, OpenBSD, and Bitrig have deprecated <malloc.h> for
00027 // <stdlib.h> instead. Unix.h includes this for us already.
00028 #if defined(HAVE_MALLOC_H) && !defined(__DragonFly__) && \
00029     !defined(__OpenBSD__) && !defined(__Bitrig__)
00030 #include <malloc.h>
00031 #endif
00032 #ifdef HAVE_MALLOC_MALLOC_H
00033 #include <malloc/malloc.h>
00034 #endif
00035 #ifdef HAVE_SYS_IOCTL_H
00036 #  include <sys/ioctl.h>
00037 #endif
00038 #ifdef HAVE_TERMIOS_H
00039 #  include <termios.h>
00040 #endif
00041 
00042 //===----------------------------------------------------------------------===//
00043 //=== WARNING: Implementation here must contain only generic UNIX code that
00044 //===          is guaranteed to work on *all* UNIX variants.
00045 //===----------------------------------------------------------------------===//
00046 
00047 using namespace llvm;
00048 using namespace sys;
00049 
00050 process::id_type self_process::get_id() {
00051   return getpid();
00052 }
00053 
00054 static std::pair<TimeValue, TimeValue> getRUsageTimes() {
00055 #if defined(HAVE_GETRUSAGE)
00056   struct rusage RU;
00057   ::getrusage(RUSAGE_SELF, &RU);
00058   return std::make_pair(
00059       TimeValue(
00060           static_cast<TimeValue::SecondsType>(RU.ru_utime.tv_sec),
00061           static_cast<TimeValue::NanoSecondsType>(
00062               RU.ru_utime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)),
00063       TimeValue(
00064           static_cast<TimeValue::SecondsType>(RU.ru_stime.tv_sec),
00065           static_cast<TimeValue::NanoSecondsType>(
00066               RU.ru_stime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)));
00067 #else
00068 #warning Cannot get usage times on this platform
00069   return std::make_pair(TimeValue(), TimeValue());
00070 #endif
00071 }
00072 
00073 TimeValue self_process::get_user_time() const {
00074 #if _POSIX_TIMERS > 0 && _POSIX_CPUTIME > 0
00075   // Try to get a high resolution CPU timer.
00076   struct timespec TS;
00077   if (::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &TS) == 0)
00078     return TimeValue(static_cast<TimeValue::SecondsType>(TS.tv_sec),
00079                      static_cast<TimeValue::NanoSecondsType>(TS.tv_nsec));
00080 #endif
00081 
00082   // Otherwise fall back to rusage based timing.
00083   return getRUsageTimes().first;
00084 }
00085 
00086 TimeValue self_process::get_system_time() const {
00087   // We can only collect system time by inspecting the results of getrusage.
00088   return getRUsageTimes().second;
00089 }
00090 
00091 // On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
00092 // offset in mmap(3) should be aligned to the AllocationGranularity.
00093 static unsigned getPageSize() {
00094 #if defined(HAVE_GETPAGESIZE)
00095   const int page_size = ::getpagesize();
00096 #elif defined(HAVE_SYSCONF)
00097   long page_size = ::sysconf(_SC_PAGE_SIZE);
00098 #else
00099 #warning Cannot get the page size on this machine
00100 #endif
00101   return static_cast<unsigned>(page_size);
00102 }
00103 
00104 // This constructor guaranteed to be run exactly once on a single thread, and
00105 // sets up various process invariants that can be queried cheaply from then on.
00106 self_process::self_process() : PageSize(getPageSize()) {
00107 }
00108 
00109 
00110 size_t Process::GetMallocUsage() {
00111 #if defined(HAVE_MALLINFO)
00112   struct mallinfo mi;
00113   mi = ::mallinfo();
00114   return mi.uordblks;
00115 #elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
00116   malloc_statistics_t Stats;
00117   malloc_zone_statistics(malloc_default_zone(), &Stats);
00118   return Stats.size_in_use;   // darwin
00119 #elif defined(HAVE_SBRK)
00120   // Note this is only an approximation and more closely resembles
00121   // the value returned by mallinfo in the arena field.
00122   static char *StartOfMemory = reinterpret_cast<char*>(::sbrk(0));
00123   char *EndOfMemory = (char*)sbrk(0);
00124   if (EndOfMemory != ((char*)-1) && StartOfMemory != ((char*)-1))
00125     return EndOfMemory - StartOfMemory;
00126   else
00127     return 0;
00128 #else
00129 #warning Cannot get malloc info on this platform
00130   return 0;
00131 #endif
00132 }
00133 
00134 void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
00135                            TimeValue &sys_time) {
00136   elapsed = TimeValue::now();
00137   std::tie(user_time, sys_time) = getRUsageTimes();
00138 }
00139 
00140 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
00141 #include <mach/mach.h>
00142 #endif
00143 
00144 // Some LLVM programs such as bugpoint produce core files as a normal part of
00145 // their operation. To prevent the disk from filling up, this function
00146 // does what's necessary to prevent their generation.
00147 void Process::PreventCoreFiles() {
00148 #if HAVE_SETRLIMIT
00149   struct rlimit rlim;
00150   rlim.rlim_cur = rlim.rlim_max = 0;
00151   setrlimit(RLIMIT_CORE, &rlim);
00152 #endif
00153 
00154 #if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
00155   // Disable crash reporting on Mac OS X 10.0-10.4
00156 
00157   // get information about the original set of exception ports for the task
00158   mach_msg_type_number_t Count = 0;
00159   exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
00160   exception_port_t OriginalPorts[EXC_TYPES_COUNT];
00161   exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
00162   thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
00163   kern_return_t err =
00164     task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
00165                              &Count, OriginalPorts, OriginalBehaviors,
00166                              OriginalFlavors);
00167   if (err == KERN_SUCCESS) {
00168     // replace each with MACH_PORT_NULL.
00169     for (unsigned i = 0; i != Count; ++i)
00170       task_set_exception_ports(mach_task_self(), OriginalMasks[i],
00171                                MACH_PORT_NULL, OriginalBehaviors[i],
00172                                OriginalFlavors[i]);
00173   }
00174 
00175   // Disable crash reporting on Mac OS X 10.5
00176   signal(SIGABRT, _exit);
00177   signal(SIGILL,  _exit);
00178   signal(SIGFPE,  _exit);
00179   signal(SIGSEGV, _exit);
00180   signal(SIGBUS,  _exit);
00181 #endif
00182 }
00183 
00184 Optional<std::string> Process::GetEnv(StringRef Name) {
00185   std::string NameStr = Name.str();
00186   const char *Val = ::getenv(NameStr.c_str());
00187   if (!Val)
00188     return None;
00189   return std::string(Val);
00190 }
00191 
00192 std::error_code
00193 Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
00194                            ArrayRef<const char *> ArgsIn,
00195                            SpecificBumpPtrAllocator<char> &) {
00196   ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
00197 
00198   return std::error_code();
00199 }
00200 
00201 bool Process::StandardInIsUserInput() {
00202   return FileDescriptorIsDisplayed(STDIN_FILENO);
00203 }
00204 
00205 bool Process::StandardOutIsDisplayed() {
00206   return FileDescriptorIsDisplayed(STDOUT_FILENO);
00207 }
00208 
00209 bool Process::StandardErrIsDisplayed() {
00210   return FileDescriptorIsDisplayed(STDERR_FILENO);
00211 }
00212 
00213 bool Process::FileDescriptorIsDisplayed(int fd) {
00214 #if HAVE_ISATTY
00215   return isatty(fd);
00216 #else
00217   // If we don't have isatty, just return false.
00218   return false;
00219 #endif
00220 }
00221 
00222 static unsigned getColumns(int FileID) {
00223   // If COLUMNS is defined in the environment, wrap to that many columns.
00224   if (const char *ColumnsStr = std::getenv("COLUMNS")) {
00225     int Columns = std::atoi(ColumnsStr);
00226     if (Columns > 0)
00227       return Columns;
00228   }
00229 
00230   unsigned Columns = 0;
00231 
00232 #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
00233   // Try to determine the width of the terminal.
00234   struct winsize ws;
00235   if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
00236     Columns = ws.ws_col;
00237 #endif
00238 
00239   return Columns;
00240 }
00241 
00242 unsigned Process::StandardOutColumns() {
00243   if (!StandardOutIsDisplayed())
00244     return 0;
00245 
00246   return getColumns(1);
00247 }
00248 
00249 unsigned Process::StandardErrColumns() {
00250   if (!StandardErrIsDisplayed())
00251     return 0;
00252 
00253   return getColumns(2);
00254 }
00255 
00256 #ifdef HAVE_TERMINFO
00257 // We manually declare these extern functions because finding the correct
00258 // headers from various terminfo, curses, or other sources is harder than
00259 // writing their specs down.
00260 extern "C" int setupterm(char *term, int filedes, int *errret);
00261 extern "C" struct term *set_curterm(struct term *termp);
00262 extern "C" int del_curterm(struct term *termp);
00263 extern "C" int tigetnum(char *capname);
00264 #endif
00265 
00266 static bool terminalHasColors(int fd) {
00267 #ifdef HAVE_TERMINFO
00268   // First, acquire a global lock because these C routines are thread hostile.
00269   static sys::Mutex M;
00270   MutexGuard G(M);
00271 
00272   int errret = 0;
00273   if (setupterm((char *)nullptr, fd, &errret) != 0)
00274     // Regardless of why, if we can't get terminfo, we shouldn't try to print
00275     // colors.
00276     return false;
00277 
00278   // Test whether the terminal as set up supports color output. How to do this
00279   // isn't entirely obvious. We can use the curses routine 'has_colors' but it
00280   // would be nice to avoid a dependency on curses proper when we can make do
00281   // with a minimal terminfo parsing library. Also, we don't really care whether
00282   // the terminal supports the curses-specific color changing routines, merely
00283   // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
00284   // strategy here is just to query the baseline colors capability and if it
00285   // supports colors at all to assume it will translate the escape codes into
00286   // whatever range of colors it does support. We can add more detailed tests
00287   // here if users report them as necessary.
00288   //
00289   // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
00290   // the terminfo says that no colors are supported.
00291   bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
00292 
00293   // Now extract the structure allocated by setupterm and free its memory
00294   // through a really silly dance.
00295   struct term *termp = set_curterm((struct term *)nullptr);
00296   (void)del_curterm(termp); // Drop any errors here.
00297 
00298   // Return true if we found a color capabilities for the current terminal.
00299   if (HasColors)
00300     return true;
00301 #endif
00302 
00303   // Otherwise, be conservative.
00304   return false;
00305 }
00306 
00307 bool Process::FileDescriptorHasColors(int fd) {
00308   // A file descriptor has colors if it is displayed and the terminal has
00309   // colors.
00310   return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
00311 }
00312 
00313 bool Process::StandardOutHasColors() {
00314   return FileDescriptorHasColors(STDOUT_FILENO);
00315 }
00316 
00317 bool Process::StandardErrHasColors() {
00318   return FileDescriptorHasColors(STDERR_FILENO);
00319 }
00320 
00321 void Process::UseANSIEscapeCodes(bool /*enable*/) {
00322   // No effect.
00323 }
00324 
00325 bool Process::ColorNeedsFlush() {
00326   // No, we use ANSI escape sequences.
00327   return false;
00328 }
00329 
00330 const char *Process::OutputColor(char code, bool bold, bool bg) {
00331   return colorcodes[bg?1:0][bold?1:0][code&7];
00332 }
00333 
00334 const char *Process::OutputBold(bool bg) {
00335   return "\033[1m";
00336 }
00337 
00338 const char *Process::OutputReverse() {
00339   return "\033[7m";
00340 }
00341 
00342 const char *Process::ResetColor() {
00343   return "\033[0m";
00344 }
00345 
00346 #if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
00347 static unsigned GetRandomNumberSeed() {
00348   // Attempt to get the initial seed from /dev/urandom, if possible.
00349   if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
00350     unsigned seed;
00351     int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
00352     ::fclose(RandomSource);
00353 
00354     // Return the seed if the read was successful.
00355     if (count == 1)
00356       return seed;
00357   }
00358 
00359   // Otherwise, swizzle the current time and the process ID to form a reasonable
00360   // seed.
00361   TimeValue Now = TimeValue::now();
00362   return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
00363 }
00364 #endif
00365 
00366 unsigned llvm::sys::Process::GetRandomNumber() {
00367 #if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
00368   return arc4random();
00369 #else
00370   static int x = (::srand(GetRandomNumberSeed()), 0);
00371   (void)x;
00372   return ::rand();
00373 #endif
00374 }