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