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