Process.inc 14 KB

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