blob: 68baab8a0b61c804ca115d167efd4f6780d25c67 [file] [log] [blame]
Reid Spencer33b9d772004-09-11 04:56:56 +00001//===- Unix/Process.cpp - Unix Process Implementation --------- -*- C++ -*-===//
Michael J. Spencer447762d2010-11-29 18:16:10 +00002//
Reid Spencer33b9d772004-09-11 04:56:56 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Michael J. Spencer447762d2010-11-29 18:16:10 +00007//
Reid Spencer33b9d772004-09-11 04:56:56 +00008//===----------------------------------------------------------------------===//
9//
10// This file provides the generic Unix implementation of the Process class.
11//
12//===----------------------------------------------------------------------===//
13
Reid Spencerac38f3a2004-12-20 00:59:28 +000014#include "Unix.h"
Daniel Dunbar5f1c9562012-05-08 20:38:00 +000015#include "llvm/ADT/Hashing.h"
Rui Ueyama471d0c52013-09-10 19:45:51 +000016#include "llvm/ADT/StringRef.h"
Nico Weber432a3882018-04-30 14:59:11 +000017#include "llvm/Config/config.h"
Chris Bienemanfa35e112014-09-22 22:39:20 +000018#include "llvm/Support/ManagedStatic.h"
Chandler Carruthcad7e5e2013-08-07 08:47:36 +000019#include "llvm/Support/Mutex.h"
20#include "llvm/Support/MutexGuard.h"
David Majnemer121a1742014-10-06 23:16:18 +000021#if HAVE_FCNTL_H
22#include <fcntl.h>
23#endif
Reid Spencerac38f3a2004-12-20 00:59:28 +000024#ifdef HAVE_SYS_TIME_H
25#include <sys/time.h>
26#endif
27#ifdef HAVE_SYS_RESOURCE_H
28#include <sys/resource.h>
29#endif
Benjamin Kramer24165212014-10-12 22:49:26 +000030#ifdef HAVE_SYS_STAT_H
31#include <sys/stat.h>
32#endif
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000033#if HAVE_SIGNAL_H
34#include <signal.h>
35#endif
Erich Keaned8f61f82017-07-21 22:48:47 +000036// DragonFlyBSD, and OpenBSD have deprecated <malloc.h> for
Eric Christopher22738d02012-08-06 20:52:18 +000037// <stdlib.h> instead. Unix.h includes this for us already.
38#if defined(HAVE_MALLOC_H) && !defined(__DragonFly__) && \
Erich Keaned8f61f82017-07-21 22:48:47 +000039 !defined(__OpenBSD__)
Reid Spencerac38f3a2004-12-20 00:59:28 +000040#include <malloc.h>
41#endif
Davide Italianofaafae32015-02-19 07:27:14 +000042#if defined(HAVE_MALLCTL)
43#include <malloc_np.h>
44#endif
Chris Lattner698fa762005-11-14 07:00:29 +000045#ifdef HAVE_MALLOC_MALLOC_H
46#include <malloc/malloc.h>
47#endif
Douglas Gregor15436612009-05-11 18:05:52 +000048#ifdef HAVE_SYS_IOCTL_H
49# include <sys/ioctl.h>
50#endif
Douglas Gregorb81294d2009-05-18 17:21:34 +000051#ifdef HAVE_TERMIOS_H
52# include <termios.h>
53#endif
Reid Spencer33b9d772004-09-11 04:56:56 +000054
55//===----------------------------------------------------------------------===//
56//=== WARNING: Implementation here must contain only generic UNIX code that
57//=== is guaranteed to work on *all* UNIX variants.
58//===----------------------------------------------------------------------===//
59
Chris Lattner2f107cf2006-09-14 06:01:41 +000060using namespace llvm;
Reid Spencer33b9d772004-09-11 04:56:56 +000061using namespace sys;
Chandler Carruth97683aa2012-12-31 11:17:50 +000062
Pavel Labath757ca882016-10-24 10:59:17 +000063static std::pair<std::chrono::microseconds, std::chrono::microseconds> getRUsageTimes() {
Chandler Carruthef7f9682013-01-04 23:19:55 +000064#if defined(HAVE_GETRUSAGE)
65 struct rusage RU;
66 ::getrusage(RUSAGE_SELF, &RU);
Pavel Labath757ca882016-10-24 10:59:17 +000067 return { toDuration(RU.ru_utime), toDuration(RU.ru_stime) };
Chandler Carruthef7f9682013-01-04 23:19:55 +000068#else
69#warning Cannot get usage times on this platform
Pavel Labath775bbc32016-11-09 11:43:57 +000070 return { std::chrono::microseconds::zero(), std::chrono::microseconds::zero() };
Chandler Carruthef7f9682013-01-04 23:19:55 +000071#endif
72}
73
NAKAMURA Takumi7a042342013-09-04 14:12:26 +000074// On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
75// offset in mmap(3) should be aligned to the AllocationGranularity.
Rafael Espindolac0610bf2014-12-04 16:59:36 +000076unsigned Process::getPageSize() {
NAKAMURA Takumi3bbbe2e2013-08-21 13:47:12 +000077#if defined(HAVE_GETPAGESIZE)
Rafael Espindolac0610bf2014-12-04 16:59:36 +000078 static const int page_size = ::getpagesize();
Reid Spencerac38f3a2004-12-20 00:59:28 +000079#elif defined(HAVE_SYSCONF)
Rafael Espindolac0610bf2014-12-04 16:59:36 +000080 static long page_size = ::sysconf(_SC_PAGE_SIZE);
Reid Spencerac38f3a2004-12-20 00:59:28 +000081#else
82#warning Cannot get the page size on this machine
83#endif
Reid Spencer33b9d772004-09-11 04:56:56 +000084 return static_cast<unsigned>(page_size);
85}
86
Chris Lattner698fa762005-11-14 07:00:29 +000087size_t Process::GetMallocUsage() {
Reid Spencer1cf74ce2004-12-20 16:06:44 +000088#if defined(HAVE_MALLINFO)
Reid Spencerac38f3a2004-12-20 00:59:28 +000089 struct mallinfo mi;
90 mi = ::mallinfo();
91 return mi.uordblks;
Chris Lattner16cbc6a2005-11-14 07:27:56 +000092#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
Davide Italianofaafae32015-02-19 07:27:14 +000096#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;
Davide Italiano8d981962015-02-21 02:36:54 +0000101 return 0;
Reid Spencer1cf74ce2004-12-20 16:06:44 +0000102#elif defined(HAVE_SBRK)
Reid Spencerac38f3a2004-12-20 00:59:28 +0000103 // Note this is only an approximation and more closely resembles
104 // the value returned by mallinfo in the arena field.
Chris Lattner698fa762005-11-14 07:00:29 +0000105 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;
Davide Italiano8d981962015-02-21 02:36:54 +0000109 return 0;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000110#else
111#warning Cannot get malloc info on this platform
112 return 0;
113#endif
114}
115
Pavel Labath757ca882016-10-24 10:59:17 +0000116void Process::GetTimeUsage(TimePoint<> &elapsed, std::chrono::nanoseconds &user_time,
117 std::chrono::nanoseconds &sys_time) {
118 elapsed = std::chrono::system_clock::now();
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000119 std::tie(user_time, sys_time) = getRUsageTimes();
Reid Spencerac38f3a2004-12-20 00:59:28 +0000120}
121
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000122#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
Nate Begeman48405152008-04-12 00:47:46 +0000123#include <mach/mach.h>
124#endif
125
Reid Spencercf15b872004-12-27 06:17:27 +0000126// Some LLVM programs such as bugpoint produce core files as a normal part of
127// their operation. To prevent the disk from filling up, this function
128// does what's necessary to prevent their generation.
129void Process::PreventCoreFiles() {
130#if HAVE_SETRLIMIT
131 struct rlimit rlim;
132 rlim.rlim_cur = rlim.rlim_max = 0;
Chris Lattnerf64397b2006-05-14 18:53:09 +0000133 setrlimit(RLIMIT_CORE, &rlim);
Reid Spencercf15b872004-12-27 06:17:27 +0000134#endif
Chris Lattner2f107cf2006-09-14 06:01:41 +0000135
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000136#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
Nate Begeman48405152008-04-12 00:47:46 +0000137 // Disable crash reporting on Mac OS X 10.0-10.4
138
139 // get information about the original set of exception ports for the task
140 mach_msg_type_number_t Count = 0;
141 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
142 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
143 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
144 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
Michael J. Spencer447762d2010-11-29 18:16:10 +0000145 kern_return_t err =
Nate Begeman48405152008-04-12 00:47:46 +0000146 task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
147 &Count, OriginalPorts, OriginalBehaviors,
148 OriginalFlavors);
149 if (err == KERN_SUCCESS) {
150 // replace each with MACH_PORT_NULL.
151 for (unsigned i = 0; i != Count; ++i)
Michael J. Spencer447762d2010-11-29 18:16:10 +0000152 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
Nate Begeman48405152008-04-12 00:47:46 +0000153 MACH_PORT_NULL, OriginalBehaviors[i],
154 OriginalFlavors[i]);
155 }
156
157 // Disable crash reporting on Mac OS X 10.5
Nate Begemanf8be3832008-03-31 22:19:25 +0000158 signal(SIGABRT, _exit);
159 signal(SIGILL, _exit);
160 signal(SIGFPE, _exit);
161 signal(SIGSEGV, _exit);
162 signal(SIGBUS, _exit);
Chris Lattner2f107cf2006-09-14 06:01:41 +0000163#endif
Leny Kholodov1b73e662016-05-04 16:56:51 +0000164
165 coreFilesPrevented = true;
Reid Spencercf15b872004-12-27 06:17:27 +0000166}
Reid Spencerac38f3a2004-12-20 00:59:28 +0000167
Rui Ueyama471d0c52013-09-10 19:45:51 +0000168Optional<std::string> Process::GetEnv(StringRef Name) {
169 std::string NameStr = Name.str();
170 const char *Val = ::getenv(NameStr.c_str());
171 if (!Val)
172 return None;
173 return std::string(Val);
174}
175
David Majnemer121a1742014-10-06 23:16:18 +0000176namespace {
177class FDCloser {
178public:
179 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
180 void keepOpen() { KeepOpen = true; }
181 ~FDCloser() {
182 if (!KeepOpen && FD >= 0)
183 ::close(FD);
184 }
185
186private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000187 FDCloser(const FDCloser &) = delete;
188 void operator=(const FDCloser &) = delete;
David Majnemer121a1742014-10-06 23:16:18 +0000189
190 int &FD;
191 bool KeepOpen;
192};
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000193}
David Majnemer121a1742014-10-06 23:16:18 +0000194
195std::error_code Process::FixupStandardFileDescriptors() {
196 int NullFD = -1;
197 FDCloser FDC(NullFD);
198 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
199 for (int StandardFD : StandardFDs) {
200 struct stat st;
201 errno = 0;
Pavel Labathfe09f502017-06-29 13:15:31 +0000202 if (RetryAfterSignal(-1, fstat, StandardFD, &st) < 0) {
David Majnemer121a1742014-10-06 23:16:18 +0000203 assert(errno && "expected errno to be set if fstat failed!");
204 // fstat should return EBADF if the file descriptor is closed.
Pavel Labathfe09f502017-06-29 13:15:31 +0000205 if (errno != EBADF)
David Majnemer121a1742014-10-06 23:16:18 +0000206 return std::error_code(errno, std::generic_category());
207 }
208 // if fstat succeeds, move on to the next FD.
209 if (!errno)
210 continue;
211 assert(errno == EBADF && "expected errno to have EBADF at this point!");
212
213 if (NullFD < 0) {
Pavel Labathfe09f502017-06-29 13:15:31 +0000214 if ((NullFD = RetryAfterSignal(-1, open, "/dev/null", O_RDWR)) < 0)
David Majnemer121a1742014-10-06 23:16:18 +0000215 return std::error_code(errno, std::generic_category());
David Majnemer121a1742014-10-06 23:16:18 +0000216 }
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
David Majnemer51c2afc2014-10-07 05:48:40 +0000226std::error_code Process::SafelyCloseFileDescriptor(int FD) {
227 // Create a signal set filled with *all* signals.
228 sigset_t FullSet;
229 if (sigfillset(&FullSet) < 0)
230 return std::error_code(errno, std::generic_category());
231 // Atomically swap our current signal mask with a full mask.
232 sigset_t SavedSet;
David Majnemerecc17772014-10-08 08:48:43 +0000233#if LLVM_ENABLE_THREADS
David Majnemer51c2afc2014-10-07 05:48:40 +0000234 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
235 return std::error_code(EC, std::generic_category());
David Majnemerecc17772014-10-08 08:48:43 +0000236#else
237 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
238 return std::error_code(errno, std::generic_category());
239#endif
David Majnemer51c2afc2014-10-07 05:48:40 +0000240 // Attempt to close the file descriptor.
241 // We need to save the error, if one occurs, because our subsequent call to
242 // pthread_sigmask might tamper with errno.
243 int ErrnoFromClose = 0;
244 if (::close(FD) < 0)
245 ErrnoFromClose = errno;
246 // Restore the signal mask back to what we saved earlier.
David Majnemerecc17772014-10-08 08:48:43 +0000247 int EC = 0;
248#if LLVM_ENABLE_THREADS
249 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
250#else
251 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
252 EC = errno;
253#endif
David Majnemer51c2afc2014-10-07 05:48:40 +0000254 // The error code from close takes precedence over the one from
255 // pthread_sigmask.
256 if (ErrnoFromClose)
257 return std::error_code(ErrnoFromClose, std::generic_category());
258 return std::error_code(EC, std::generic_category());
259}
260
Reid Spencer6f802ba2005-01-01 22:29:26 +0000261bool Process::StandardInIsUserInput() {
Dan Gohmane5929232009-09-11 20:46:33 +0000262 return FileDescriptorIsDisplayed(STDIN_FILENO);
Reid Spencer6f802ba2005-01-01 22:29:26 +0000263}
264
265bool Process::StandardOutIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000266 return FileDescriptorIsDisplayed(STDOUT_FILENO);
Reid Spencer6f802ba2005-01-01 22:29:26 +0000267}
268
269bool Process::StandardErrIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000270 return FileDescriptorIsDisplayed(STDERR_FILENO);
271}
272
273bool Process::FileDescriptorIsDisplayed(int fd) {
Reid Spencer6f802ba2005-01-01 22:29:26 +0000274#if HAVE_ISATTY
Dan Gohmane5929232009-09-11 20:46:33 +0000275 return isatty(fd);
Duncan Sands44d423a2009-09-06 10:53:22 +0000276#else
Reid Spencer6f802ba2005-01-01 22:29:26 +0000277 // If we don't have isatty, just return false.
278 return false;
Duncan Sands44d423a2009-09-06 10:53:22 +0000279#endif
Reid Spencer6f802ba2005-01-01 22:29:26 +0000280}
Douglas Gregor15436612009-05-11 18:05:52 +0000281
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000282static unsigned getColumns(int FileID) {
Douglas Gregor15436612009-05-11 18:05:52 +0000283 // If COLUMNS is defined in the environment, wrap to that many columns.
284 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
285 int Columns = std::atoi(ColumnsStr);
286 if (Columns > 0)
287 return Columns;
288 }
289
290 unsigned Columns = 0;
291
Douglas Gregorb81294d2009-05-18 17:21:34 +0000292#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
Douglas Gregor15436612009-05-11 18:05:52 +0000293 // Try to determine the width of the terminal.
294 struct winsize ws;
295 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
296 Columns = ws.ws_col;
297#endif
298
299 return Columns;
300}
301
302unsigned Process::StandardOutColumns() {
303 if (!StandardOutIsDisplayed())
304 return 0;
305
306 return getColumns(1);
307}
308
309unsigned Process::StandardErrColumns() {
310 if (!StandardErrIsDisplayed())
311 return 0;
312
313 return getColumns(2);
314}
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000315
Chandler Carruth91219852013-08-12 10:40:11 +0000316#ifdef HAVE_TERMINFO
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000317// We manually declare these extern functions because finding the correct
Chandler Carruth91219852013-08-12 10:40:11 +0000318// headers from various terminfo, curses, or other sources is harder than
319// writing their specs down.
320extern "C" int setupterm(char *term, int filedes, int *errret);
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000321extern "C" struct term *set_curterm(struct term *termp);
322extern "C" int del_curterm(struct term *termp);
Chandler Carruth91219852013-08-12 10:40:11 +0000323extern "C" int tigetnum(char *capname);
324#endif
325
Chris Bieneman78272172014-09-24 18:35:58 +0000326#ifdef HAVE_TERMINFO
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000327static ManagedStatic<sys::Mutex> TermColorMutex;
Chris Bieneman78272172014-09-24 18:35:58 +0000328#endif
Chris Bienemanfa35e112014-09-22 22:39:20 +0000329
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000330static bool terminalHasColors(int fd) {
Chandler Carruthf11f1e42013-08-12 09:49:17 +0000331#ifdef HAVE_TERMINFO
332 // First, acquire a global lock because these C routines are thread hostile.
Chris Bienemanfa35e112014-09-22 22:39:20 +0000333 MutexGuard G(*TermColorMutex);
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000334
335 int errret = 0;
Serge Gueltonf4dc59b2017-05-11 08:53:00 +0000336 if (setupterm(nullptr, fd, &errret) != 0)
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000337 // Regardless of why, if we can't get terminfo, we shouldn't try to print
338 // colors.
339 return false;
340
Chandler Carruthf11f1e42013-08-12 09:49:17 +0000341 // Test whether the terminal as set up supports color output. How to do this
342 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
343 // would be nice to avoid a dependency on curses proper when we can make do
344 // with a minimal terminfo parsing library. Also, we don't really care whether
345 // the terminal supports the curses-specific color changing routines, merely
346 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
347 // strategy here is just to query the baseline colors capability and if it
348 // supports colors at all to assume it will translate the escape codes into
349 // whatever range of colors it does support. We can add more detailed tests
350 // here if users report them as necessary.
351 //
352 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
353 // the terminfo says that no colors are supported.
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000354 bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
355
356 // Now extract the structure allocated by setupterm and free its memory
357 // through a really silly dance.
Serge Gueltonf4dc59b2017-05-11 08:53:00 +0000358 struct term *termp = set_curterm(nullptr);
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000359 (void)del_curterm(termp); // Drop any errors here.
360
361 // Return true if we found a color capabilities for the current terminal.
362 if (HasColors)
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000363 return true;
Petr Hosekcc7a8f12018-01-19 17:10:55 +0000364#else
365 // When the terminfo database is not available, check if the current terminal
366 // is one of terminals that are known to support ANSI color escape codes.
367 if (const char *TermStr = std::getenv("TERM")) {
368 return StringSwitch<bool>(TermStr)
369 .Case("ansi", true)
370 .Case("cygwin", true)
371 .Case("linux", true)
372 .StartsWith("screen", true)
373 .StartsWith("xterm", true)
374 .StartsWith("vt100", true)
375 .StartsWith("rxvt", true)
376 .EndsWith("color", true)
377 .Default(false);
378 }
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000379#endif
380
381 // Otherwise, be conservative.
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000382 return false;
383}
384
Daniel Dunbar712de822012-07-20 18:29:38 +0000385bool Process::FileDescriptorHasColors(int fd) {
386 // A file descriptor has colors if it is displayed and the terminal has
387 // colors.
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000388 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
Daniel Dunbar712de822012-07-20 18:29:38 +0000389}
390
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000391bool Process::StandardOutHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000392 return FileDescriptorHasColors(STDOUT_FILENO);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000393}
394
395bool Process::StandardErrHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000396 return FileDescriptorHasColors(STDERR_FILENO);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000397}
398
Nico Rieck92d649a2013-09-11 00:36:48 +0000399void Process::UseANSIEscapeCodes(bool /*enable*/) {
400 // No effect.
401}
402
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000403bool Process::ColorNeedsFlush() {
404 // No, we use ANSI escape sequences.
405 return false;
406}
407
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000408const char *Process::OutputColor(char code, bool bold, bool bg) {
409 return colorcodes[bg?1:0][bold?1:0][code&7];
410}
411
412const char *Process::OutputBold(bool bg) {
413 return "\033[1m";
414}
415
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000416const char *Process::OutputReverse() {
417 return "\033[7m";
418}
419
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000420const char *Process::ResetColor() {
421 return "\033[0m";
422}
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000423
Joerg Sonnenberger8472f842016-09-29 21:10:38 +0000424#if !HAVE_DECL_ARC4RANDOM
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000425static unsigned GetRandomNumberSeed() {
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000426 // Attempt to get the initial seed from /dev/urandom, if possible.
Rafael Espindola515f8df2015-12-11 22:52:32 +0000427 int urandomFD = open("/dev/urandom", O_RDONLY);
428
429 if (urandomFD != -1) {
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000430 unsigned seed;
Rafael Espindola515f8df2015-12-11 22:52:32 +0000431 // Don't use a buffered read to avoid reading more data
432 // from /dev/urandom than we need.
433 int count = read(urandomFD, (void *)&seed, sizeof(seed));
434
435 close(urandomFD);
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000436
437 // Return the seed if the read was successful.
Rafael Espindola515f8df2015-12-11 22:52:32 +0000438 if (count == sizeof(seed))
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000439 return seed;
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000440 }
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000441
442 // Otherwise, swizzle the current time and the process ID to form a reasonable
443 // seed.
Pavel Labath757ca882016-10-24 10:59:17 +0000444 const auto Now = std::chrono::high_resolution_clock::now();
445 return hash_combine(Now.time_since_epoch().count(), ::getpid());
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000446}
447#endif
448
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000449unsigned llvm::sys::Process::GetRandomNumber() {
Joerg Sonnenberger8472f842016-09-29 21:10:38 +0000450#if HAVE_DECL_ARC4RANDOM
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000451 return arc4random();
452#else
Richard Trieu7a083812016-02-18 22:09:30 +0000453 static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0);
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000454 (void)x;
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000455 return ::rand();
456#endif
457}