blob: a429bb3984c888a81bafe78031102c08686910ad [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"
Chris Bienemanfa35e112014-09-22 22:39:20 +000017#include "llvm/Support/ManagedStatic.h"
Chandler Carruthcad7e5e2013-08-07 08:47:36 +000018#include "llvm/Support/Mutex.h"
19#include "llvm/Support/MutexGuard.h"
Daniel Dunbar5f1c9562012-05-08 20:38:00 +000020#include "llvm/Support/TimeValue.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
David Majnemer73483222014-10-07 05:56:45 +000033#if HAVE_SIGNAL_H
34#include <signal.h>
35#endif
Eric Christopher22738d02012-08-06 20:52:18 +000036// DragonFlyBSD, OpenBSD, and Bitrig have deprecated <malloc.h> for
37// <stdlib.h> instead. Unix.h includes this for us already.
38#if defined(HAVE_MALLOC_H) && !defined(__DragonFly__) && \
39 !defined(__OpenBSD__) && !defined(__Bitrig__)
Reid Spencerac38f3a2004-12-20 00:59:28 +000040#include <malloc.h>
41#endif
Chris Lattner698fa762005-11-14 07:00:29 +000042#ifdef HAVE_MALLOC_MALLOC_H
43#include <malloc/malloc.h>
44#endif
Douglas Gregor15436612009-05-11 18:05:52 +000045#ifdef HAVE_SYS_IOCTL_H
46# include <sys/ioctl.h>
47#endif
Douglas Gregorb81294d2009-05-18 17:21:34 +000048#ifdef HAVE_TERMIOS_H
49# include <termios.h>
50#endif
Reid Spencer33b9d772004-09-11 04:56:56 +000051
52//===----------------------------------------------------------------------===//
53//=== WARNING: Implementation here must contain only generic UNIX code that
54//=== is guaranteed to work on *all* UNIX variants.
55//===----------------------------------------------------------------------===//
56
Chris Lattner2f107cf2006-09-14 06:01:41 +000057using namespace llvm;
Reid Spencer33b9d772004-09-11 04:56:56 +000058using namespace sys;
Chandler Carruth97683aa2012-12-31 11:17:50 +000059
60process::id_type self_process::get_id() {
61 return getpid();
62}
63
Chandler Carruthef7f9682013-01-04 23:19:55 +000064static std::pair<TimeValue, TimeValue> getRUsageTimes() {
65#if defined(HAVE_GETRUSAGE)
66 struct rusage RU;
67 ::getrusage(RUSAGE_SELF, &RU);
68 return std::make_pair(
69 TimeValue(
70 static_cast<TimeValue::SecondsType>(RU.ru_utime.tv_sec),
71 static_cast<TimeValue::NanoSecondsType>(
72 RU.ru_utime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)),
73 TimeValue(
74 static_cast<TimeValue::SecondsType>(RU.ru_stime.tv_sec),
75 static_cast<TimeValue::NanoSecondsType>(
76 RU.ru_stime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)));
77#else
78#warning Cannot get usage times on this platform
79 return std::make_pair(TimeValue(), TimeValue());
80#endif
81}
82
83TimeValue self_process::get_user_time() const {
Chandler Carruthb5429f42013-01-05 00:42:50 +000084#if _POSIX_TIMERS > 0 && _POSIX_CPUTIME > 0
Chandler Carruthef7f9682013-01-04 23:19:55 +000085 // Try to get a high resolution CPU timer.
86 struct timespec TS;
87 if (::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &TS) == 0)
88 return TimeValue(static_cast<TimeValue::SecondsType>(TS.tv_sec),
89 static_cast<TimeValue::NanoSecondsType>(TS.tv_nsec));
90#endif
91
92 // Otherwise fall back to rusage based timing.
93 return getRUsageTimes().first;
94}
95
96TimeValue self_process::get_system_time() const {
97 // We can only collect system time by inspecting the results of getrusage.
98 return getRUsageTimes().second;
99}
100
NAKAMURA Takumi7a042342013-09-04 14:12:26 +0000101// On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
102// offset in mmap(3) should be aligned to the AllocationGranularity.
Chandler Carruth15dcad92012-12-31 23:23:35 +0000103static unsigned getPageSize() {
NAKAMURA Takumi3bbbe2e2013-08-21 13:47:12 +0000104#if defined(HAVE_GETPAGESIZE)
Owen Andersona83e8682009-08-19 21:48:34 +0000105 const int page_size = ::getpagesize();
Reid Spencerac38f3a2004-12-20 00:59:28 +0000106#elif defined(HAVE_SYSCONF)
Owen Andersona83e8682009-08-19 21:48:34 +0000107 long page_size = ::sysconf(_SC_PAGE_SIZE);
Reid Spencerac38f3a2004-12-20 00:59:28 +0000108#else
109#warning Cannot get the page size on this machine
110#endif
Reid Spencer33b9d772004-09-11 04:56:56 +0000111 return static_cast<unsigned>(page_size);
112}
113
Chandler Carruth15dcad92012-12-31 23:23:35 +0000114// This constructor guaranteed to be run exactly once on a single thread, and
115// sets up various process invariants that can be queried cheaply from then on.
116self_process::self_process() : PageSize(getPageSize()) {
117}
118
119
Chris Lattner698fa762005-11-14 07:00:29 +0000120size_t Process::GetMallocUsage() {
Reid Spencer1cf74ce2004-12-20 16:06:44 +0000121#if defined(HAVE_MALLINFO)
Reid Spencerac38f3a2004-12-20 00:59:28 +0000122 struct mallinfo mi;
123 mi = ::mallinfo();
124 return mi.uordblks;
Chris Lattner16cbc6a2005-11-14 07:27:56 +0000125#elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
126 malloc_statistics_t Stats;
127 malloc_zone_statistics(malloc_default_zone(), &Stats);
128 return Stats.size_in_use; // darwin
Reid Spencer1cf74ce2004-12-20 16:06:44 +0000129#elif defined(HAVE_SBRK)
Reid Spencerac38f3a2004-12-20 00:59:28 +0000130 // Note this is only an approximation and more closely resembles
131 // the value returned by mallinfo in the arena field.
Chris Lattner698fa762005-11-14 07:00:29 +0000132 static char *StartOfMemory = reinterpret_cast<char*>(::sbrk(0));
133 char *EndOfMemory = (char*)sbrk(0);
134 if (EndOfMemory != ((char*)-1) && StartOfMemory != ((char*)-1))
135 return EndOfMemory - StartOfMemory;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000136 else
137 return 0;
138#else
139#warning Cannot get malloc info on this platform
140 return 0;
141#endif
142}
143
Chandler Carruthef7f9682013-01-04 23:19:55 +0000144void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
145 TimeValue &sys_time) {
Reid Spencerac38f3a2004-12-20 00:59:28 +0000146 elapsed = TimeValue::now();
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000147 std::tie(user_time, sys_time) = getRUsageTimes();
Reid Spencerac38f3a2004-12-20 00:59:28 +0000148}
149
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000150#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
Nate Begeman48405152008-04-12 00:47:46 +0000151#include <mach/mach.h>
152#endif
153
Reid Spencercf15b872004-12-27 06:17:27 +0000154// Some LLVM programs such as bugpoint produce core files as a normal part of
155// their operation. To prevent the disk from filling up, this function
156// does what's necessary to prevent their generation.
157void Process::PreventCoreFiles() {
158#if HAVE_SETRLIMIT
159 struct rlimit rlim;
160 rlim.rlim_cur = rlim.rlim_max = 0;
Chris Lattnerf64397b2006-05-14 18:53:09 +0000161 setrlimit(RLIMIT_CORE, &rlim);
Reid Spencercf15b872004-12-27 06:17:27 +0000162#endif
Chris Lattner2f107cf2006-09-14 06:01:41 +0000163
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000164#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
Nate Begeman48405152008-04-12 00:47:46 +0000165 // Disable crash reporting on Mac OS X 10.0-10.4
166
167 // get information about the original set of exception ports for the task
168 mach_msg_type_number_t Count = 0;
169 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
170 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
171 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
172 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
Michael J. Spencer447762d2010-11-29 18:16:10 +0000173 kern_return_t err =
Nate Begeman48405152008-04-12 00:47:46 +0000174 task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
175 &Count, OriginalPorts, OriginalBehaviors,
176 OriginalFlavors);
177 if (err == KERN_SUCCESS) {
178 // replace each with MACH_PORT_NULL.
179 for (unsigned i = 0; i != Count; ++i)
Michael J. Spencer447762d2010-11-29 18:16:10 +0000180 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
Nate Begeman48405152008-04-12 00:47:46 +0000181 MACH_PORT_NULL, OriginalBehaviors[i],
182 OriginalFlavors[i]);
183 }
184
185 // Disable crash reporting on Mac OS X 10.5
Nate Begemanf8be3832008-03-31 22:19:25 +0000186 signal(SIGABRT, _exit);
187 signal(SIGILL, _exit);
188 signal(SIGFPE, _exit);
189 signal(SIGSEGV, _exit);
190 signal(SIGBUS, _exit);
Chris Lattner2f107cf2006-09-14 06:01:41 +0000191#endif
Reid Spencercf15b872004-12-27 06:17:27 +0000192}
Reid Spencerac38f3a2004-12-20 00:59:28 +0000193
Rui Ueyama471d0c52013-09-10 19:45:51 +0000194Optional<std::string> Process::GetEnv(StringRef Name) {
195 std::string NameStr = Name.str();
196 const char *Val = ::getenv(NameStr.c_str());
197 if (!Val)
198 return None;
199 return std::string(Val);
200}
201
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000202std::error_code
203Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
204 ArrayRef<const char *> ArgsIn,
205 SpecificBumpPtrAllocator<char> &) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000206 ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
207
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000208 return std::error_code();
David Majnemer61eae2e2013-10-07 01:00:07 +0000209}
210
David Majnemer121a1742014-10-06 23:16:18 +0000211namespace {
212class FDCloser {
213public:
214 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
215 void keepOpen() { KeepOpen = true; }
216 ~FDCloser() {
217 if (!KeepOpen && FD >= 0)
218 ::close(FD);
219 }
220
221private:
222 FDCloser(const FDCloser &) LLVM_DELETED_FUNCTION;
223 void operator=(const FDCloser &) LLVM_DELETED_FUNCTION;
224
225 int &FD;
226 bool KeepOpen;
227};
228}
229
230std::error_code Process::FixupStandardFileDescriptors() {
231 int NullFD = -1;
232 FDCloser FDC(NullFD);
233 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
234 for (int StandardFD : StandardFDs) {
235 struct stat st;
236 errno = 0;
237 while (fstat(StandardFD, &st) < 0) {
238 assert(errno && "expected errno to be set if fstat failed!");
239 // fstat should return EBADF if the file descriptor is closed.
240 if (errno == EBADF)
241 break;
242 // retry fstat if we got EINTR, otherwise bubble up the failure.
243 if (errno != EINTR)
244 return std::error_code(errno, std::generic_category());
245 }
246 // if fstat succeeds, move on to the next FD.
247 if (!errno)
248 continue;
249 assert(errno == EBADF && "expected errno to have EBADF at this point!");
250
251 if (NullFD < 0) {
252 while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
253 if (errno == EINTR)
254 continue;
255 return std::error_code(errno, std::generic_category());
256 }
257 }
258
259 if (NullFD == StandardFD)
260 FDC.keepOpen();
261 else if (dup2(NullFD, StandardFD) < 0)
262 return std::error_code(errno, std::generic_category());
263 }
264 return std::error_code();
265}
266
David Majnemer51c2afc2014-10-07 05:48:40 +0000267std::error_code Process::SafelyCloseFileDescriptor(int FD) {
268 // Create a signal set filled with *all* signals.
269 sigset_t FullSet;
270 if (sigfillset(&FullSet) < 0)
271 return std::error_code(errno, std::generic_category());
272 // Atomically swap our current signal mask with a full mask.
273 sigset_t SavedSet;
David Majnemerecc17772014-10-08 08:48:43 +0000274#if LLVM_ENABLE_THREADS
David Majnemer51c2afc2014-10-07 05:48:40 +0000275 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
276 return std::error_code(EC, std::generic_category());
David Majnemerecc17772014-10-08 08:48:43 +0000277#else
278 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
279 return std::error_code(errno, std::generic_category());
280#endif
David Majnemer51c2afc2014-10-07 05:48:40 +0000281 // Attempt to close the file descriptor.
282 // We need to save the error, if one occurs, because our subsequent call to
283 // pthread_sigmask might tamper with errno.
284 int ErrnoFromClose = 0;
285 if (::close(FD) < 0)
286 ErrnoFromClose = errno;
287 // Restore the signal mask back to what we saved earlier.
David Majnemerecc17772014-10-08 08:48:43 +0000288 int EC = 0;
289#if LLVM_ENABLE_THREADS
290 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
291#else
292 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
293 EC = errno;
294#endif
David Majnemer51c2afc2014-10-07 05:48:40 +0000295 // The error code from close takes precedence over the one from
296 // pthread_sigmask.
297 if (ErrnoFromClose)
298 return std::error_code(ErrnoFromClose, std::generic_category());
299 return std::error_code(EC, std::generic_category());
300}
301
Reid Spencer6f802ba2005-01-01 22:29:26 +0000302bool Process::StandardInIsUserInput() {
Dan Gohmane5929232009-09-11 20:46:33 +0000303 return FileDescriptorIsDisplayed(STDIN_FILENO);
Reid Spencer6f802ba2005-01-01 22:29:26 +0000304}
305
306bool Process::StandardOutIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000307 return FileDescriptorIsDisplayed(STDOUT_FILENO);
Reid Spencer6f802ba2005-01-01 22:29:26 +0000308}
309
310bool Process::StandardErrIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000311 return FileDescriptorIsDisplayed(STDERR_FILENO);
312}
313
314bool Process::FileDescriptorIsDisplayed(int fd) {
Reid Spencer6f802ba2005-01-01 22:29:26 +0000315#if HAVE_ISATTY
Dan Gohmane5929232009-09-11 20:46:33 +0000316 return isatty(fd);
Duncan Sands44d423a2009-09-06 10:53:22 +0000317#else
Reid Spencer6f802ba2005-01-01 22:29:26 +0000318 // If we don't have isatty, just return false.
319 return false;
Duncan Sands44d423a2009-09-06 10:53:22 +0000320#endif
Reid Spencer6f802ba2005-01-01 22:29:26 +0000321}
Douglas Gregor15436612009-05-11 18:05:52 +0000322
323static unsigned getColumns(int FileID) {
324 // If COLUMNS is defined in the environment, wrap to that many columns.
325 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
326 int Columns = std::atoi(ColumnsStr);
327 if (Columns > 0)
328 return Columns;
329 }
330
331 unsigned Columns = 0;
332
Douglas Gregorb81294d2009-05-18 17:21:34 +0000333#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
Douglas Gregor15436612009-05-11 18:05:52 +0000334 // Try to determine the width of the terminal.
335 struct winsize ws;
336 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
337 Columns = ws.ws_col;
338#endif
339
340 return Columns;
341}
342
343unsigned Process::StandardOutColumns() {
344 if (!StandardOutIsDisplayed())
345 return 0;
346
347 return getColumns(1);
348}
349
350unsigned Process::StandardErrColumns() {
351 if (!StandardErrIsDisplayed())
352 return 0;
353
354 return getColumns(2);
355}
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000356
Chandler Carruth91219852013-08-12 10:40:11 +0000357#ifdef HAVE_TERMINFO
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000358// We manually declare these extern functions because finding the correct
Chandler Carruth91219852013-08-12 10:40:11 +0000359// headers from various terminfo, curses, or other sources is harder than
360// writing their specs down.
361extern "C" int setupterm(char *term, int filedes, int *errret);
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000362extern "C" struct term *set_curterm(struct term *termp);
363extern "C" int del_curterm(struct term *termp);
Chandler Carruth91219852013-08-12 10:40:11 +0000364extern "C" int tigetnum(char *capname);
365#endif
366
Chris Bieneman78272172014-09-24 18:35:58 +0000367#ifdef HAVE_TERMINFO
Chris Bienemanfa35e112014-09-22 22:39:20 +0000368static ManagedStatic<sys::Mutex> TermColorMutex;
Chris Bieneman78272172014-09-24 18:35:58 +0000369#endif
Chris Bienemanfa35e112014-09-22 22:39:20 +0000370
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000371static bool terminalHasColors(int fd) {
Chandler Carruthf11f1e42013-08-12 09:49:17 +0000372#ifdef HAVE_TERMINFO
373 // First, acquire a global lock because these C routines are thread hostile.
Chris Bienemanfa35e112014-09-22 22:39:20 +0000374 MutexGuard G(*TermColorMutex);
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000375
376 int errret = 0;
Craig Toppere73658d2014-04-28 04:05:08 +0000377 if (setupterm((char *)nullptr, fd, &errret) != 0)
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000378 // Regardless of why, if we can't get terminfo, we shouldn't try to print
379 // colors.
380 return false;
381
Chandler Carruthf11f1e42013-08-12 09:49:17 +0000382 // Test whether the terminal as set up supports color output. How to do this
383 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
384 // would be nice to avoid a dependency on curses proper when we can make do
385 // with a minimal terminfo parsing library. Also, we don't really care whether
386 // the terminal supports the curses-specific color changing routines, merely
387 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
388 // strategy here is just to query the baseline colors capability and if it
389 // supports colors at all to assume it will translate the escape codes into
390 // whatever range of colors it does support. We can add more detailed tests
391 // here if users report them as necessary.
392 //
393 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
394 // the terminfo says that no colors are supported.
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000395 bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
396
397 // Now extract the structure allocated by setupterm and free its memory
398 // through a really silly dance.
Craig Toppere73658d2014-04-28 04:05:08 +0000399 struct term *termp = set_curterm((struct term *)nullptr);
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000400 (void)del_curterm(termp); // Drop any errors here.
401
402 // Return true if we found a color capabilities for the current terminal.
403 if (HasColors)
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000404 return true;
405#endif
406
407 // Otherwise, be conservative.
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000408 return false;
409}
410
Daniel Dunbar712de822012-07-20 18:29:38 +0000411bool Process::FileDescriptorHasColors(int fd) {
412 // A file descriptor has colors if it is displayed and the terminal has
413 // colors.
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000414 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
Daniel Dunbar712de822012-07-20 18:29:38 +0000415}
416
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000417bool Process::StandardOutHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000418 return FileDescriptorHasColors(STDOUT_FILENO);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000419}
420
421bool Process::StandardErrHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000422 return FileDescriptorHasColors(STDERR_FILENO);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000423}
424
Nico Rieck92d649a2013-09-11 00:36:48 +0000425void Process::UseANSIEscapeCodes(bool /*enable*/) {
426 // No effect.
427}
428
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000429bool Process::ColorNeedsFlush() {
430 // No, we use ANSI escape sequences.
431 return false;
432}
433
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000434const char *Process::OutputColor(char code, bool bold, bool bg) {
435 return colorcodes[bg?1:0][bold?1:0][code&7];
436}
437
438const char *Process::OutputBold(bool bg) {
439 return "\033[1m";
440}
441
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000442const char *Process::OutputReverse() {
443 return "\033[7m";
444}
445
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000446const char *Process::ResetColor() {
447 return "\033[0m";
448}
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000449
Todd Fiala4ccfe392014-02-05 05:04:36 +0000450#if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000451static unsigned GetRandomNumberSeed() {
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000452 // Attempt to get the initial seed from /dev/urandom, if possible.
453 if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
454 unsigned seed;
455 int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000456 ::fclose(RandomSource);
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000457
458 // Return the seed if the read was successful.
459 if (count == 1)
460 return seed;
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000461 }
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000462
463 // Otherwise, swizzle the current time and the process ID to form a reasonable
464 // seed.
Chandler Carruth5473dfb2012-12-31 11:45:20 +0000465 TimeValue Now = TimeValue::now();
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000466 return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000467}
468#endif
469
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000470unsigned llvm::sys::Process::GetRandomNumber() {
Todd Fiala4ccfe392014-02-05 05:04:36 +0000471#if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000472 return arc4random();
473#else
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000474 static int x = (::srand(GetRandomNumberSeed()), 0);
475 (void)x;
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000476 return ::rand();
477#endif
478}