Process.inc 14 KB

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