blob: df13bd2217390b46c859872aa88b7db2a9f1949f [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
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
Chandler Carruthef7f9682013-01-04 23:19:55 +000063static std::pair<TimeValue, TimeValue> getRUsageTimes() {
64#if defined(HAVE_GETRUSAGE)
65 struct rusage RU;
66 ::getrusage(RUSAGE_SELF, &RU);
67 return std::make_pair(
68 TimeValue(
69 static_cast<TimeValue::SecondsType>(RU.ru_utime.tv_sec),
70 static_cast<TimeValue::NanoSecondsType>(
71 RU.ru_utime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)),
72 TimeValue(
73 static_cast<TimeValue::SecondsType>(RU.ru_stime.tv_sec),
74 static_cast<TimeValue::NanoSecondsType>(
75 RU.ru_stime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)));
76#else
77#warning Cannot get usage times on this platform
78 return std::make_pair(TimeValue(), TimeValue());
79#endif
80}
81
NAKAMURA Takumi7a042342013-09-04 14:12:26 +000082// On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
83// offset in mmap(3) should be aligned to the AllocationGranularity.
Rafael Espindolac0610bf2014-12-04 16:59:36 +000084unsigned Process::getPageSize() {
NAKAMURA Takumi3bbbe2e2013-08-21 13:47:12 +000085#if defined(HAVE_GETPAGESIZE)
Rafael Espindolac0610bf2014-12-04 16:59:36 +000086 static const int page_size = ::getpagesize();
Reid Spencerac38f3a2004-12-20 00:59:28 +000087#elif defined(HAVE_SYSCONF)
Rafael Espindolac0610bf2014-12-04 16:59:36 +000088 static long page_size = ::sysconf(_SC_PAGE_SIZE);
Reid Spencerac38f3a2004-12-20 00:59:28 +000089#else
90#warning Cannot get the page size on this machine
91#endif
Reid Spencer33b9d772004-09-11 04:56:56 +000092 return static_cast<unsigned>(page_size);
93}
94
Chris Lattner698fa762005-11-14 07:00:29 +000095size_t Process::GetMallocUsage() {
Reid Spencer1cf74ce2004-12-20 16:06:44 +000096#if defined(HAVE_MALLINFO)
Reid Spencerac38f3a2004-12-20 00:59:28 +000097 struct mallinfo mi;
98 mi = ::mallinfo();
99 return mi.uordblks;
Chris Lattner16cbc6a2005-11-14 07:27:56 +0000100#elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
101 malloc_statistics_t Stats;
102 malloc_zone_statistics(malloc_default_zone(), &Stats);
103 return Stats.size_in_use; // darwin
Davide Italianofaafae32015-02-19 07:27:14 +0000104#elif defined(HAVE_MALLCTL)
105 size_t alloc, sz;
106 sz = sizeof(size_t);
107 if (mallctl("stats.allocated", &alloc, &sz, NULL, 0) == 0)
108 return alloc;
Davide Italiano8d981962015-02-21 02:36:54 +0000109 return 0;
Reid Spencer1cf74ce2004-12-20 16:06:44 +0000110#elif defined(HAVE_SBRK)
Reid Spencerac38f3a2004-12-20 00:59:28 +0000111 // Note this is only an approximation and more closely resembles
112 // the value returned by mallinfo in the arena field.
Chris Lattner698fa762005-11-14 07:00:29 +0000113 static char *StartOfMemory = reinterpret_cast<char*>(::sbrk(0));
114 char *EndOfMemory = (char*)sbrk(0);
115 if (EndOfMemory != ((char*)-1) && StartOfMemory != ((char*)-1))
116 return EndOfMemory - StartOfMemory;
Davide Italiano8d981962015-02-21 02:36:54 +0000117 return 0;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000118#else
119#warning Cannot get malloc info on this platform
120 return 0;
121#endif
122}
123
Chandler Carruthef7f9682013-01-04 23:19:55 +0000124void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
125 TimeValue &sys_time) {
Reid Spencerac38f3a2004-12-20 00:59:28 +0000126 elapsed = TimeValue::now();
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000127 std::tie(user_time, sys_time) = getRUsageTimes();
Reid Spencerac38f3a2004-12-20 00:59:28 +0000128}
129
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000130#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
Nate Begeman48405152008-04-12 00:47:46 +0000131#include <mach/mach.h>
132#endif
133
Reid Spencercf15b872004-12-27 06:17:27 +0000134// Some LLVM programs such as bugpoint produce core files as a normal part of
135// their operation. To prevent the disk from filling up, this function
136// does what's necessary to prevent their generation.
137void Process::PreventCoreFiles() {
138#if HAVE_SETRLIMIT
139 struct rlimit rlim;
140 rlim.rlim_cur = rlim.rlim_max = 0;
Chris Lattnerf64397b2006-05-14 18:53:09 +0000141 setrlimit(RLIMIT_CORE, &rlim);
Reid Spencercf15b872004-12-27 06:17:27 +0000142#endif
Chris Lattner2f107cf2006-09-14 06:01:41 +0000143
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000144#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
Nate Begeman48405152008-04-12 00:47:46 +0000145 // Disable crash reporting on Mac OS X 10.0-10.4
146
147 // get information about the original set of exception ports for the task
148 mach_msg_type_number_t Count = 0;
149 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
150 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
151 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
152 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
Michael J. Spencer447762d2010-11-29 18:16:10 +0000153 kern_return_t err =
Nate Begeman48405152008-04-12 00:47:46 +0000154 task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
155 &Count, OriginalPorts, OriginalBehaviors,
156 OriginalFlavors);
157 if (err == KERN_SUCCESS) {
158 // replace each with MACH_PORT_NULL.
159 for (unsigned i = 0; i != Count; ++i)
Michael J. Spencer447762d2010-11-29 18:16:10 +0000160 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
Nate Begeman48405152008-04-12 00:47:46 +0000161 MACH_PORT_NULL, OriginalBehaviors[i],
162 OriginalFlavors[i]);
163 }
164
165 // Disable crash reporting on Mac OS X 10.5
Nate Begemanf8be3832008-03-31 22:19:25 +0000166 signal(SIGABRT, _exit);
167 signal(SIGILL, _exit);
168 signal(SIGFPE, _exit);
169 signal(SIGSEGV, _exit);
170 signal(SIGBUS, _exit);
Chris Lattner2f107cf2006-09-14 06:01:41 +0000171#endif
Reid Spencercf15b872004-12-27 06:17:27 +0000172}
Reid Spencerac38f3a2004-12-20 00:59:28 +0000173
Rui Ueyama471d0c52013-09-10 19:45:51 +0000174Optional<std::string> Process::GetEnv(StringRef Name) {
175 std::string NameStr = Name.str();
176 const char *Val = ::getenv(NameStr.c_str());
177 if (!Val)
178 return None;
179 return std::string(Val);
180}
181
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000182std::error_code
183Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
184 ArrayRef<const char *> ArgsIn,
185 SpecificBumpPtrAllocator<char> &) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000186 ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
187
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000188 return std::error_code();
David Majnemer61eae2e2013-10-07 01:00:07 +0000189}
190
David Majnemer121a1742014-10-06 23:16:18 +0000191namespace {
192class FDCloser {
193public:
194 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
195 void keepOpen() { KeepOpen = true; }
196 ~FDCloser() {
197 if (!KeepOpen && FD >= 0)
198 ::close(FD);
199 }
200
201private:
Aaron Ballmanf9a18972015-02-15 22:54:22 +0000202 FDCloser(const FDCloser &) = delete;
203 void operator=(const FDCloser &) = delete;
David Majnemer121a1742014-10-06 23:16:18 +0000204
205 int &FD;
206 bool KeepOpen;
207};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000208}
David Majnemer121a1742014-10-06 23:16:18 +0000209
210std::error_code Process::FixupStandardFileDescriptors() {
211 int NullFD = -1;
212 FDCloser FDC(NullFD);
213 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
214 for (int StandardFD : StandardFDs) {
215 struct stat st;
216 errno = 0;
217 while (fstat(StandardFD, &st) < 0) {
218 assert(errno && "expected errno to be set if fstat failed!");
219 // fstat should return EBADF if the file descriptor is closed.
220 if (errno == EBADF)
221 break;
222 // retry fstat if we got EINTR, otherwise bubble up the failure.
223 if (errno != EINTR)
224 return std::error_code(errno, std::generic_category());
225 }
226 // if fstat succeeds, move on to the next FD.
227 if (!errno)
228 continue;
229 assert(errno == EBADF && "expected errno to have EBADF at this point!");
230
231 if (NullFD < 0) {
232 while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
233 if (errno == EINTR)
234 continue;
235 return std::error_code(errno, std::generic_category());
236 }
237 }
238
239 if (NullFD == StandardFD)
240 FDC.keepOpen();
241 else if (dup2(NullFD, StandardFD) < 0)
242 return std::error_code(errno, std::generic_category());
243 }
244 return std::error_code();
245}
246
David Majnemer51c2afc2014-10-07 05:48:40 +0000247std::error_code Process::SafelyCloseFileDescriptor(int FD) {
248 // Create a signal set filled with *all* signals.
249 sigset_t FullSet;
250 if (sigfillset(&FullSet) < 0)
251 return std::error_code(errno, std::generic_category());
252 // Atomically swap our current signal mask with a full mask.
253 sigset_t SavedSet;
David Majnemerecc17772014-10-08 08:48:43 +0000254#if LLVM_ENABLE_THREADS
David Majnemer51c2afc2014-10-07 05:48:40 +0000255 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
256 return std::error_code(EC, std::generic_category());
David Majnemerecc17772014-10-08 08:48:43 +0000257#else
258 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
259 return std::error_code(errno, std::generic_category());
260#endif
David Majnemer51c2afc2014-10-07 05:48:40 +0000261 // Attempt to close the file descriptor.
262 // We need to save the error, if one occurs, because our subsequent call to
263 // pthread_sigmask might tamper with errno.
264 int ErrnoFromClose = 0;
265 if (::close(FD) < 0)
266 ErrnoFromClose = errno;
267 // Restore the signal mask back to what we saved earlier.
David Majnemerecc17772014-10-08 08:48:43 +0000268 int EC = 0;
269#if LLVM_ENABLE_THREADS
270 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
271#else
272 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
273 EC = errno;
274#endif
David Majnemer51c2afc2014-10-07 05:48:40 +0000275 // The error code from close takes precedence over the one from
276 // pthread_sigmask.
277 if (ErrnoFromClose)
278 return std::error_code(ErrnoFromClose, std::generic_category());
279 return std::error_code(EC, std::generic_category());
280}
281
Reid Spencer6f802ba2005-01-01 22:29:26 +0000282bool Process::StandardInIsUserInput() {
Dan Gohmane5929232009-09-11 20:46:33 +0000283 return FileDescriptorIsDisplayed(STDIN_FILENO);
Reid Spencer6f802ba2005-01-01 22:29:26 +0000284}
285
286bool Process::StandardOutIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000287 return FileDescriptorIsDisplayed(STDOUT_FILENO);
Reid Spencer6f802ba2005-01-01 22:29:26 +0000288}
289
290bool Process::StandardErrIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000291 return FileDescriptorIsDisplayed(STDERR_FILENO);
292}
293
294bool Process::FileDescriptorIsDisplayed(int fd) {
Reid Spencer6f802ba2005-01-01 22:29:26 +0000295#if HAVE_ISATTY
Dan Gohmane5929232009-09-11 20:46:33 +0000296 return isatty(fd);
Duncan Sands44d423a2009-09-06 10:53:22 +0000297#else
Reid Spencer6f802ba2005-01-01 22:29:26 +0000298 // If we don't have isatty, just return false.
299 return false;
Duncan Sands44d423a2009-09-06 10:53:22 +0000300#endif
Reid Spencer6f802ba2005-01-01 22:29:26 +0000301}
Douglas Gregor15436612009-05-11 18:05:52 +0000302
303static unsigned getColumns(int FileID) {
304 // If COLUMNS is defined in the environment, wrap to that many columns.
305 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
306 int Columns = std::atoi(ColumnsStr);
307 if (Columns > 0)
308 return Columns;
309 }
310
311 unsigned Columns = 0;
312
Douglas Gregorb81294d2009-05-18 17:21:34 +0000313#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
Douglas Gregor15436612009-05-11 18:05:52 +0000314 // Try to determine the width of the terminal.
315 struct winsize ws;
316 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
317 Columns = ws.ws_col;
318#endif
319
320 return Columns;
321}
322
323unsigned Process::StandardOutColumns() {
324 if (!StandardOutIsDisplayed())
325 return 0;
326
327 return getColumns(1);
328}
329
330unsigned Process::StandardErrColumns() {
331 if (!StandardErrIsDisplayed())
332 return 0;
333
334 return getColumns(2);
335}
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000336
Chandler Carruth91219852013-08-12 10:40:11 +0000337#ifdef HAVE_TERMINFO
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000338// We manually declare these extern functions because finding the correct
Chandler Carruth91219852013-08-12 10:40:11 +0000339// headers from various terminfo, curses, or other sources is harder than
340// writing their specs down.
341extern "C" int setupterm(char *term, int filedes, int *errret);
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000342extern "C" struct term *set_curterm(struct term *termp);
343extern "C" int del_curterm(struct term *termp);
Chandler Carruth91219852013-08-12 10:40:11 +0000344extern "C" int tigetnum(char *capname);
345#endif
346
Chris Bieneman78272172014-09-24 18:35:58 +0000347#ifdef HAVE_TERMINFO
Chris Bienemanfa35e112014-09-22 22:39:20 +0000348static ManagedStatic<sys::Mutex> TermColorMutex;
Chris Bieneman78272172014-09-24 18:35:58 +0000349#endif
Chris Bienemanfa35e112014-09-22 22:39:20 +0000350
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000351static bool terminalHasColors(int fd) {
Chandler Carruthf11f1e42013-08-12 09:49:17 +0000352#ifdef HAVE_TERMINFO
353 // First, acquire a global lock because these C routines are thread hostile.
Chris Bienemanfa35e112014-09-22 22:39:20 +0000354 MutexGuard G(*TermColorMutex);
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000355
356 int errret = 0;
Craig Toppere73658d2014-04-28 04:05:08 +0000357 if (setupterm((char *)nullptr, fd, &errret) != 0)
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000358 // Regardless of why, if we can't get terminfo, we shouldn't try to print
359 // colors.
360 return false;
361
Chandler Carruthf11f1e42013-08-12 09:49:17 +0000362 // Test whether the terminal as set up supports color output. How to do this
363 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
364 // would be nice to avoid a dependency on curses proper when we can make do
365 // with a minimal terminfo parsing library. Also, we don't really care whether
366 // the terminal supports the curses-specific color changing routines, merely
367 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
368 // strategy here is just to query the baseline colors capability and if it
369 // supports colors at all to assume it will translate the escape codes into
370 // whatever range of colors it does support. We can add more detailed tests
371 // here if users report them as necessary.
372 //
373 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
374 // the terminfo says that no colors are supported.
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000375 bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
376
377 // Now extract the structure allocated by setupterm and free its memory
378 // through a really silly dance.
Craig Toppere73658d2014-04-28 04:05:08 +0000379 struct term *termp = set_curterm((struct term *)nullptr);
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000380 (void)del_curterm(termp); // Drop any errors here.
381
382 // Return true if we found a color capabilities for the current terminal.
383 if (HasColors)
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000384 return true;
385#endif
386
387 // Otherwise, be conservative.
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000388 return false;
389}
390
Daniel Dunbar712de822012-07-20 18:29:38 +0000391bool Process::FileDescriptorHasColors(int fd) {
392 // A file descriptor has colors if it is displayed and the terminal has
393 // colors.
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000394 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
Daniel Dunbar712de822012-07-20 18:29:38 +0000395}
396
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000397bool Process::StandardOutHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000398 return FileDescriptorHasColors(STDOUT_FILENO);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000399}
400
401bool Process::StandardErrHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000402 return FileDescriptorHasColors(STDERR_FILENO);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000403}
404
Nico Rieck92d649a2013-09-11 00:36:48 +0000405void Process::UseANSIEscapeCodes(bool /*enable*/) {
406 // No effect.
407}
408
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000409bool Process::ColorNeedsFlush() {
410 // No, we use ANSI escape sequences.
411 return false;
412}
413
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000414const char *Process::OutputColor(char code, bool bold, bool bg) {
415 return colorcodes[bg?1:0][bold?1:0][code&7];
416}
417
418const char *Process::OutputBold(bool bg) {
419 return "\033[1m";
420}
421
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000422const char *Process::OutputReverse() {
423 return "\033[7m";
424}
425
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000426const char *Process::ResetColor() {
427 return "\033[0m";
428}
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000429
Todd Fiala4ccfe392014-02-05 05:04:36 +0000430#if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000431static unsigned GetRandomNumberSeed() {
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000432 // Attempt to get the initial seed from /dev/urandom, if possible.
433 if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
434 unsigned seed;
435 int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000436 ::fclose(RandomSource);
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000437
438 // Return the seed if the read was successful.
439 if (count == 1)
440 return seed;
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000441 }
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000442
443 // Otherwise, swizzle the current time and the process ID to form a reasonable
444 // seed.
Chandler Carruth5473dfb2012-12-31 11:45:20 +0000445 TimeValue Now = TimeValue::now();
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000446 return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000447}
448#endif
449
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000450unsigned llvm::sys::Process::GetRandomNumber() {
Todd Fiala4ccfe392014-02-05 05:04:36 +0000451#if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000452 return arc4random();
453#else
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000454 static int x = (::srand(GetRandomNumberSeed()), 0);
455 (void)x;
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000456 return ::rand();
457#endif
458}