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