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