Process.inc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. #include "Unix.h"
  14. #include "llvm/ADT/Hashing.h"
  15. #include "llvm/ADT/StringRef.h"
  16. #include "llvm/Support/ManagedStatic.h"
  17. #include "llvm/Support/Mutex.h"
  18. #include "llvm/Support/MutexGuard.h"
  19. #include "llvm/Support/TimeValue.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. //=== WARNING: Implementation here must contain only generic UNIX code that
  55. //=== is guaranteed to work on *all* UNIX variants.
  56. //===----------------------------------------------------------------------===//
  57. using namespace llvm;
  58. using namespace sys;
  59. static std::pair<TimeValue, TimeValue> getRUsageTimes() {
  60. #if defined(HAVE_GETRUSAGE)
  61. struct rusage RU;
  62. ::getrusage(RUSAGE_SELF, &RU);
  63. return std::make_pair(
  64. TimeValue(
  65. static_cast<TimeValue::SecondsType>(RU.ru_utime.tv_sec),
  66. static_cast<TimeValue::NanoSecondsType>(
  67. RU.ru_utime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)),
  68. TimeValue(
  69. static_cast<TimeValue::SecondsType>(RU.ru_stime.tv_sec),
  70. static_cast<TimeValue::NanoSecondsType>(
  71. RU.ru_stime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)));
  72. #else
  73. #warning Cannot get usage times on this platform
  74. return std::make_pair(TimeValue(), TimeValue());
  75. #endif
  76. }
  77. // On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
  78. // offset in mmap(3) should be aligned to the AllocationGranularity.
  79. unsigned Process::getPageSize() {
  80. #if defined(HAVE_GETPAGESIZE)
  81. static const int page_size = ::getpagesize();
  82. #elif defined(HAVE_SYSCONF)
  83. static long page_size = ::sysconf(_SC_PAGE_SIZE);
  84. #else
  85. #warning Cannot get the page size on this machine
  86. #endif
  87. return static_cast<unsigned>(page_size);
  88. }
  89. size_t Process::GetMallocUsage() {
  90. #if 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. void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
  118. TimeValue &sys_time) {
  119. elapsed = TimeValue::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 =
  143. task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
  144. &Count, OriginalPorts, OriginalBehaviors,
  145. OriginalFlavors);
  146. if (err == KERN_SUCCESS) {
  147. // replace each with MACH_PORT_NULL.
  148. for (unsigned i = 0; i != Count; ++i)
  149. task_set_exception_ports(mach_task_self(), OriginalMasks[i],
  150. MACH_PORT_NULL, OriginalBehaviors[i],
  151. OriginalFlavors[i]);
  152. }
  153. // Disable crash reporting on Mac OS X 10.5
  154. signal(SIGABRT, _exit);
  155. signal(SIGILL, _exit);
  156. signal(SIGFPE, _exit);
  157. signal(SIGSEGV, _exit);
  158. signal(SIGBUS, _exit);
  159. #endif
  160. }
  161. 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 None;
  166. return std::string(Val);
  167. }
  168. std::error_code
  169. Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
  170. ArrayRef<const char *> ArgsIn,
  171. SpecificBumpPtrAllocator<char> &) {
  172. ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
  173. return std::error_code();
  174. }
  175. namespace {
  176. class FDCloser {
  177. public:
  178. FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
  179. void keepOpen() { KeepOpen = true; }
  180. ~FDCloser() {
  181. if (!KeepOpen && FD >= 0)
  182. ::close(FD);
  183. }
  184. private:
  185. FDCloser(const FDCloser &) = delete;
  186. void operator=(const FDCloser &) = delete;
  187. int &FD;
  188. bool KeepOpen;
  189. };
  190. }
  191. std::error_code Process::FixupStandardFileDescriptors() {
  192. int NullFD = -1;
  193. FDCloser FDC(NullFD);
  194. const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
  195. for (int StandardFD : StandardFDs) {
  196. struct stat st;
  197. errno = 0;
  198. while (fstat(StandardFD, &st) < 0) {
  199. assert(errno && "expected errno to be set if fstat failed!");
  200. // fstat should return EBADF if the file descriptor is closed.
  201. if (errno == EBADF)
  202. break;
  203. // retry fstat if we got EINTR, otherwise bubble up the failure.
  204. if (errno != EINTR)
  205. return std::error_code(errno, std::generic_category());
  206. }
  207. // if fstat succeeds, move on to the next FD.
  208. if (!errno)
  209. continue;
  210. assert(errno == EBADF && "expected errno to have EBADF at this point!");
  211. if (NullFD < 0) {
  212. while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
  213. if (errno == EINTR)
  214. continue;
  215. return std::error_code(errno, std::generic_category());
  216. }
  217. }
  218. if (NullFD == StandardFD)
  219. FDC.keepOpen();
  220. else if (dup2(NullFD, StandardFD) < 0)
  221. return std::error_code(errno, std::generic_category());
  222. }
  223. return std::error_code();
  224. }
  225. std::error_code Process::SafelyCloseFileDescriptor(int FD) {
  226. // Create a signal set filled with *all* signals.
  227. sigset_t FullSet;
  228. if (sigfillset(&FullSet) < 0)
  229. return std::error_code(errno, std::generic_category());
  230. // Atomically swap our current signal mask with a full mask.
  231. sigset_t SavedSet;
  232. #if LLVM_ENABLE_THREADS
  233. if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
  234. return std::error_code(EC, std::generic_category());
  235. #else
  236. if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
  237. return std::error_code(errno, std::generic_category());
  238. #endif
  239. // Attempt to close the file descriptor.
  240. // We need to save the error, if one occurs, because our subsequent call to
  241. // pthread_sigmask might tamper with errno.
  242. int ErrnoFromClose = 0;
  243. if (fs::msf_close(FD) < 0)
  244. ErrnoFromClose = errno;
  245. // Restore the signal mask back to what we saved earlier.
  246. int EC = 0;
  247. #if LLVM_ENABLE_THREADS
  248. EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
  249. #else
  250. if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
  251. EC = errno;
  252. #endif
  253. // The error code from close takes precedence over the one from
  254. // pthread_sigmask.
  255. if (ErrnoFromClose)
  256. return std::error_code(ErrnoFromClose, std::generic_category());
  257. return std::error_code(EC, std::generic_category());
  258. }
  259. bool Process::StandardInIsUserInput() {
  260. return FileDescriptorIsDisplayed(STDIN_FILENO);
  261. }
  262. bool Process::StandardOutIsDisplayed() {
  263. return FileDescriptorIsDisplayed(STDOUT_FILENO);
  264. }
  265. bool Process::StandardErrIsDisplayed() {
  266. return FileDescriptorIsDisplayed(STDERR_FILENO);
  267. }
  268. bool Process::FileDescriptorIsDisplayed(int fd) {
  269. #if HAVE_ISATTY
  270. return isatty(fd);
  271. #else
  272. // If we don't have isatty, just return false.
  273. return false;
  274. #endif
  275. }
  276. static unsigned getColumns(int FileID) {
  277. // If COLUMNS is defined in the environment, wrap to that many columns.
  278. if (const char *ColumnsStr = std::getenv("COLUMNS")) {
  279. int Columns = std::atoi(ColumnsStr);
  280. if (Columns > 0)
  281. return Columns;
  282. }
  283. unsigned Columns = 0;
  284. #if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
  285. // Try to determine the width of the terminal.
  286. struct winsize ws;
  287. if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
  288. Columns = ws.ws_col;
  289. #endif
  290. return Columns;
  291. }
  292. unsigned Process::StandardOutColumns() {
  293. if (!StandardOutIsDisplayed())
  294. return 0;
  295. return getColumns(1);
  296. }
  297. unsigned Process::StandardErrColumns() {
  298. if (!StandardErrIsDisplayed())
  299. return 0;
  300. return getColumns(2);
  301. }
  302. #ifdef HAVE_TERMINFO
  303. // We manually declare these extern functions because finding the correct
  304. // headers from various terminfo, curses, or other sources is harder than
  305. // writing their specs down.
  306. extern "C" int setupterm(char *term, int filedes, int *errret);
  307. extern "C" struct term *set_curterm(struct term *termp);
  308. extern "C" int del_curterm(struct term *termp);
  309. extern "C" int tigetnum(char *capname);
  310. #endif
  311. #ifdef HAVE_TERMINFO
  312. static ManagedStatic<sys::Mutex> TermColorMutex;
  313. #endif
  314. static bool terminalHasColors(int fd) {
  315. #ifdef HAVE_TERMINFO
  316. // First, acquire a global lock because these C routines are thread hostile.
  317. MutexGuard G(*TermColorMutex);
  318. int errret = 0;
  319. if (setupterm((char *)nullptr, fd, &errret) != 0)
  320. // Regardless of why, if we can't get terminfo, we shouldn't try to print
  321. // colors.
  322. return false;
  323. // Test whether the terminal as set up supports color output. How to do this
  324. // isn't entirely obvious. We can use the curses routine 'has_colors' but it
  325. // would be nice to avoid a dependency on curses proper when we can make do
  326. // with a minimal terminfo parsing library. Also, we don't really care whether
  327. // the terminal supports the curses-specific color changing routines, merely
  328. // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
  329. // strategy here is just to query the baseline colors capability and if it
  330. // supports colors at all to assume it will translate the escape codes into
  331. // whatever range of colors it does support. We can add more detailed tests
  332. // here if users report them as necessary.
  333. //
  334. // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
  335. // the terminfo says that no colors are supported.
  336. bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
  337. // Now extract the structure allocated by setupterm and free its memory
  338. // through a really silly dance.
  339. struct term *termp = set_curterm((struct term *)nullptr);
  340. (void)del_curterm(termp); // Drop any errors here.
  341. // Return true if we found a color capabilities for the current terminal.
  342. if (HasColors)
  343. return true;
  344. #endif
  345. // Otherwise, be conservative.
  346. return false;
  347. }
  348. bool Process::FileDescriptorHasColors(int fd) {
  349. // A file descriptor has colors if it is displayed and the terminal has
  350. // colors.
  351. return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
  352. }
  353. bool Process::StandardOutHasColors() {
  354. return FileDescriptorHasColors(STDOUT_FILENO);
  355. }
  356. bool Process::StandardErrHasColors() {
  357. return FileDescriptorHasColors(STDERR_FILENO);
  358. }
  359. void Process::UseANSIEscapeCodes(bool /*enable*/) {
  360. // No effect.
  361. }
  362. bool Process::ColorNeedsFlush() {
  363. // No, we use ANSI escape sequences.
  364. return false;
  365. }
  366. const char *Process::OutputColor(char code, bool bold, bool bg) {
  367. return colorcodes[bg?1:0][bold?1:0][code&7];
  368. }
  369. const char *Process::OutputBold(bool bg) {
  370. return "\033[1m";
  371. }
  372. const char *Process::OutputReverse() {
  373. return "\033[7m";
  374. }
  375. const char *Process::ResetColor() {
  376. return "\033[0m";
  377. }
  378. #if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
  379. static unsigned GetRandomNumberSeed() {
  380. // Attempt to get the initial seed from /dev/urandom, if possible.
  381. if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
  382. unsigned seed;
  383. int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
  384. ::fclose(RandomSource);
  385. // Return the seed if the read was successful.
  386. if (count == 1)
  387. return seed;
  388. }
  389. // Otherwise, swizzle the current time and the process ID to form a reasonable
  390. // seed.
  391. TimeValue Now = TimeValue::now();
  392. return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
  393. }
  394. #endif
  395. unsigned llvm::sys::Process::GetRandomNumber() {
  396. #if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
  397. return arc4random();
  398. #else
  399. static int x = (::srand(GetRandomNumberSeed()), 0);
  400. (void)x;
  401. return ::rand();
  402. #endif
  403. }