blob: 0d84bee54d31ffff6a5d49b773a791756bb0ec6f [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
David Majnemer73483222014-10-07 05:56:45 +000030#if HAVE_SIGNAL_H
31#include <signal.h>
32#endif
Eric Christopher22738d02012-08-06 20:52:18 +000033// DragonFlyBSD, OpenBSD, and Bitrig have deprecated <malloc.h> for
34// <stdlib.h> instead. Unix.h includes this for us already.
35#if defined(HAVE_MALLOC_H) && !defined(__DragonFly__) && \
36 !defined(__OpenBSD__) && !defined(__Bitrig__)
Reid Spencerac38f3a2004-12-20 00:59:28 +000037#include <malloc.h>
38#endif
Chris Lattner698fa762005-11-14 07:00:29 +000039#ifdef HAVE_MALLOC_MALLOC_H
40#include <malloc/malloc.h>
41#endif
Douglas Gregor15436612009-05-11 18:05:52 +000042#ifdef HAVE_SYS_IOCTL_H
43# include <sys/ioctl.h>
44#endif
Douglas Gregorb81294d2009-05-18 17:21:34 +000045#ifdef HAVE_TERMIOS_H
46# include <termios.h>
47#endif
Reid Spencer33b9d772004-09-11 04:56:56 +000048
49//===----------------------------------------------------------------------===//
50//=== WARNING: Implementation here must contain only generic UNIX code that
51//=== is guaranteed to work on *all* UNIX variants.
52//===----------------------------------------------------------------------===//
53
Chris Lattner2f107cf2006-09-14 06:01:41 +000054using namespace llvm;
Reid Spencer33b9d772004-09-11 04:56:56 +000055using namespace sys;
Chandler Carruth97683aa2012-12-31 11:17:50 +000056
57process::id_type self_process::get_id() {
58 return getpid();
59}
60
Chandler Carruthef7f9682013-01-04 23:19:55 +000061static std::pair<TimeValue, TimeValue> getRUsageTimes() {
62#if defined(HAVE_GETRUSAGE)
63 struct rusage RU;
64 ::getrusage(RUSAGE_SELF, &RU);
65 return std::make_pair(
66 TimeValue(
67 static_cast<TimeValue::SecondsType>(RU.ru_utime.tv_sec),
68 static_cast<TimeValue::NanoSecondsType>(
69 RU.ru_utime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)),
70 TimeValue(
71 static_cast<TimeValue::SecondsType>(RU.ru_stime.tv_sec),
72 static_cast<TimeValue::NanoSecondsType>(
73 RU.ru_stime.tv_usec * TimeValue::NANOSECONDS_PER_MICROSECOND)));
74#else
75#warning Cannot get usage times on this platform
76 return std::make_pair(TimeValue(), TimeValue());
77#endif
78}
79
80TimeValue self_process::get_user_time() const {
Chandler Carruthb5429f42013-01-05 00:42:50 +000081#if _POSIX_TIMERS > 0 && _POSIX_CPUTIME > 0
Chandler Carruthef7f9682013-01-04 23:19:55 +000082 // Try to get a high resolution CPU timer.
83 struct timespec TS;
84 if (::clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &TS) == 0)
85 return TimeValue(static_cast<TimeValue::SecondsType>(TS.tv_sec),
86 static_cast<TimeValue::NanoSecondsType>(TS.tv_nsec));
87#endif
88
89 // Otherwise fall back to rusage based timing.
90 return getRUsageTimes().first;
91}
92
93TimeValue self_process::get_system_time() const {
94 // We can only collect system time by inspecting the results of getrusage.
95 return getRUsageTimes().second;
96}
97
NAKAMURA Takumi7a042342013-09-04 14:12:26 +000098// On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
99// offset in mmap(3) should be aligned to the AllocationGranularity.
Chandler Carruth15dcad92012-12-31 23:23:35 +0000100static unsigned getPageSize() {
NAKAMURA Takumi3bbbe2e2013-08-21 13:47:12 +0000101#if defined(HAVE_GETPAGESIZE)
Owen Andersona83e8682009-08-19 21:48:34 +0000102 const int page_size = ::getpagesize();
Reid Spencerac38f3a2004-12-20 00:59:28 +0000103#elif defined(HAVE_SYSCONF)
Owen Andersona83e8682009-08-19 21:48:34 +0000104 long page_size = ::sysconf(_SC_PAGE_SIZE);
Reid Spencerac38f3a2004-12-20 00:59:28 +0000105#else
106#warning Cannot get the page size on this machine
107#endif
Reid Spencer33b9d772004-09-11 04:56:56 +0000108 return static_cast<unsigned>(page_size);
109}
110
Chandler Carruth15dcad92012-12-31 23:23:35 +0000111// This constructor guaranteed to be run exactly once on a single thread, and
112// sets up various process invariants that can be queried cheaply from then on.
113self_process::self_process() : PageSize(getPageSize()) {
114}
115
116
Chris Lattner698fa762005-11-14 07:00:29 +0000117size_t Process::GetMallocUsage() {
Reid Spencer1cf74ce2004-12-20 16:06:44 +0000118#if defined(HAVE_MALLINFO)
Reid Spencerac38f3a2004-12-20 00:59:28 +0000119 struct mallinfo mi;
120 mi = ::mallinfo();
121 return mi.uordblks;
Chris Lattner16cbc6a2005-11-14 07:27:56 +0000122#elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
123 malloc_statistics_t Stats;
124 malloc_zone_statistics(malloc_default_zone(), &Stats);
125 return Stats.size_in_use; // darwin
Reid Spencer1cf74ce2004-12-20 16:06:44 +0000126#elif defined(HAVE_SBRK)
Reid Spencerac38f3a2004-12-20 00:59:28 +0000127 // Note this is only an approximation and more closely resembles
128 // the value returned by mallinfo in the arena field.
Chris Lattner698fa762005-11-14 07:00:29 +0000129 static char *StartOfMemory = reinterpret_cast<char*>(::sbrk(0));
130 char *EndOfMemory = (char*)sbrk(0);
131 if (EndOfMemory != ((char*)-1) && StartOfMemory != ((char*)-1))
132 return EndOfMemory - StartOfMemory;
Reid Spencerac38f3a2004-12-20 00:59:28 +0000133 else
134 return 0;
135#else
136#warning Cannot get malloc info on this platform
137 return 0;
138#endif
139}
140
Chandler Carruthef7f9682013-01-04 23:19:55 +0000141void Process::GetTimeUsage(TimeValue &elapsed, TimeValue &user_time,
142 TimeValue &sys_time) {
Reid Spencerac38f3a2004-12-20 00:59:28 +0000143 elapsed = TimeValue::now();
Benjamin Kramerd6f1f842014-03-02 13:30:33 +0000144 std::tie(user_time, sys_time) = getRUsageTimes();
Reid Spencerac38f3a2004-12-20 00:59:28 +0000145}
146
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000147#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
Nate Begeman48405152008-04-12 00:47:46 +0000148#include <mach/mach.h>
149#endif
150
Reid Spencercf15b872004-12-27 06:17:27 +0000151// Some LLVM programs such as bugpoint produce core files as a normal part of
152// their operation. To prevent the disk from filling up, this function
153// does what's necessary to prevent their generation.
154void Process::PreventCoreFiles() {
155#if HAVE_SETRLIMIT
156 struct rlimit rlim;
157 rlim.rlim_cur = rlim.rlim_max = 0;
Chris Lattnerf64397b2006-05-14 18:53:09 +0000158 setrlimit(RLIMIT_CORE, &rlim);
Reid Spencercf15b872004-12-27 06:17:27 +0000159#endif
Chris Lattner2f107cf2006-09-14 06:01:41 +0000160
Sylvestre Ledru14ada942012-04-11 15:35:36 +0000161#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
Nate Begeman48405152008-04-12 00:47:46 +0000162 // Disable crash reporting on Mac OS X 10.0-10.4
163
164 // get information about the original set of exception ports for the task
165 mach_msg_type_number_t Count = 0;
166 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
167 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
168 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
169 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
Michael J. Spencer447762d2010-11-29 18:16:10 +0000170 kern_return_t err =
Nate Begeman48405152008-04-12 00:47:46 +0000171 task_get_exception_ports(mach_task_self(), EXC_MASK_ALL, OriginalMasks,
172 &Count, OriginalPorts, OriginalBehaviors,
173 OriginalFlavors);
174 if (err == KERN_SUCCESS) {
175 // replace each with MACH_PORT_NULL.
176 for (unsigned i = 0; i != Count; ++i)
Michael J. Spencer447762d2010-11-29 18:16:10 +0000177 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
Nate Begeman48405152008-04-12 00:47:46 +0000178 MACH_PORT_NULL, OriginalBehaviors[i],
179 OriginalFlavors[i]);
180 }
181
182 // Disable crash reporting on Mac OS X 10.5
Nate Begemanf8be3832008-03-31 22:19:25 +0000183 signal(SIGABRT, _exit);
184 signal(SIGILL, _exit);
185 signal(SIGFPE, _exit);
186 signal(SIGSEGV, _exit);
187 signal(SIGBUS, _exit);
Chris Lattner2f107cf2006-09-14 06:01:41 +0000188#endif
Reid Spencercf15b872004-12-27 06:17:27 +0000189}
Reid Spencerac38f3a2004-12-20 00:59:28 +0000190
Rui Ueyama471d0c52013-09-10 19:45:51 +0000191Optional<std::string> Process::GetEnv(StringRef Name) {
192 std::string NameStr = Name.str();
193 const char *Val = ::getenv(NameStr.c_str());
194 if (!Val)
195 return None;
196 return std::string(Val);
197}
198
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000199std::error_code
200Process::GetArgumentVector(SmallVectorImpl<const char *> &ArgsOut,
201 ArrayRef<const char *> ArgsIn,
202 SpecificBumpPtrAllocator<char> &) {
David Majnemer61eae2e2013-10-07 01:00:07 +0000203 ArgsOut.append(ArgsIn.begin(), ArgsIn.end());
204
Rafael Espindoladb4ed0b2014-06-13 02:24:39 +0000205 return std::error_code();
David Majnemer61eae2e2013-10-07 01:00:07 +0000206}
207
David Majnemer121a1742014-10-06 23:16:18 +0000208namespace {
209class FDCloser {
210public:
211 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
212 void keepOpen() { KeepOpen = true; }
213 ~FDCloser() {
214 if (!KeepOpen && FD >= 0)
215 ::close(FD);
216 }
217
218private:
219 FDCloser(const FDCloser &) LLVM_DELETED_FUNCTION;
220 void operator=(const FDCloser &) LLVM_DELETED_FUNCTION;
221
222 int &FD;
223 bool KeepOpen;
224};
225}
226
227std::error_code Process::FixupStandardFileDescriptors() {
228 int NullFD = -1;
229 FDCloser FDC(NullFD);
230 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
231 for (int StandardFD : StandardFDs) {
232 struct stat st;
233 errno = 0;
234 while (fstat(StandardFD, &st) < 0) {
235 assert(errno && "expected errno to be set if fstat failed!");
236 // fstat should return EBADF if the file descriptor is closed.
237 if (errno == EBADF)
238 break;
239 // retry fstat if we got EINTR, otherwise bubble up the failure.
240 if (errno != EINTR)
241 return std::error_code(errno, std::generic_category());
242 }
243 // if fstat succeeds, move on to the next FD.
244 if (!errno)
245 continue;
246 assert(errno == EBADF && "expected errno to have EBADF at this point!");
247
248 if (NullFD < 0) {
249 while ((NullFD = open("/dev/null", O_RDWR)) < 0) {
250 if (errno == EINTR)
251 continue;
252 return std::error_code(errno, std::generic_category());
253 }
254 }
255
256 if (NullFD == StandardFD)
257 FDC.keepOpen();
258 else if (dup2(NullFD, StandardFD) < 0)
259 return std::error_code(errno, std::generic_category());
260 }
261 return std::error_code();
262}
263
David Majnemer51c2afc2014-10-07 05:48:40 +0000264std::error_code Process::SafelyCloseFileDescriptor(int FD) {
265 // Create a signal set filled with *all* signals.
266 sigset_t FullSet;
267 if (sigfillset(&FullSet) < 0)
268 return std::error_code(errno, std::generic_category());
269 // Atomically swap our current signal mask with a full mask.
270 sigset_t SavedSet;
271 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
272 return std::error_code(EC, std::generic_category());
273 // Attempt to close the file descriptor.
274 // We need to save the error, if one occurs, because our subsequent call to
275 // pthread_sigmask might tamper with errno.
276 int ErrnoFromClose = 0;
277 if (::close(FD) < 0)
278 ErrnoFromClose = errno;
279 // Restore the signal mask back to what we saved earlier.
280 int EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
281 // The error code from close takes precedence over the one from
282 // pthread_sigmask.
283 if (ErrnoFromClose)
284 return std::error_code(ErrnoFromClose, std::generic_category());
285 return std::error_code(EC, std::generic_category());
286}
287
Reid Spencer6f802ba2005-01-01 22:29:26 +0000288bool Process::StandardInIsUserInput() {
Dan Gohmane5929232009-09-11 20:46:33 +0000289 return FileDescriptorIsDisplayed(STDIN_FILENO);
Reid Spencer6f802ba2005-01-01 22:29:26 +0000290}
291
292bool Process::StandardOutIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000293 return FileDescriptorIsDisplayed(STDOUT_FILENO);
Reid Spencer6f802ba2005-01-01 22:29:26 +0000294}
295
296bool Process::StandardErrIsDisplayed() {
Dan Gohmane5929232009-09-11 20:46:33 +0000297 return FileDescriptorIsDisplayed(STDERR_FILENO);
298}
299
300bool Process::FileDescriptorIsDisplayed(int fd) {
Reid Spencer6f802ba2005-01-01 22:29:26 +0000301#if HAVE_ISATTY
Dan Gohmane5929232009-09-11 20:46:33 +0000302 return isatty(fd);
Duncan Sands44d423a2009-09-06 10:53:22 +0000303#else
Reid Spencer6f802ba2005-01-01 22:29:26 +0000304 // If we don't have isatty, just return false.
305 return false;
Duncan Sands44d423a2009-09-06 10:53:22 +0000306#endif
Reid Spencer6f802ba2005-01-01 22:29:26 +0000307}
Douglas Gregor15436612009-05-11 18:05:52 +0000308
309static unsigned getColumns(int FileID) {
310 // If COLUMNS is defined in the environment, wrap to that many columns.
311 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
312 int Columns = std::atoi(ColumnsStr);
313 if (Columns > 0)
314 return Columns;
315 }
316
317 unsigned Columns = 0;
318
Douglas Gregorb81294d2009-05-18 17:21:34 +0000319#if defined(HAVE_SYS_IOCTL_H) && defined(HAVE_TERMIOS_H)
Douglas Gregor15436612009-05-11 18:05:52 +0000320 // Try to determine the width of the terminal.
321 struct winsize ws;
322 if (ioctl(FileID, TIOCGWINSZ, &ws) == 0)
323 Columns = ws.ws_col;
324#endif
325
326 return Columns;
327}
328
329unsigned Process::StandardOutColumns() {
330 if (!StandardOutIsDisplayed())
331 return 0;
332
333 return getColumns(1);
334}
335
336unsigned Process::StandardErrColumns() {
337 if (!StandardErrIsDisplayed())
338 return 0;
339
340 return getColumns(2);
341}
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000342
Chandler Carruth91219852013-08-12 10:40:11 +0000343#ifdef HAVE_TERMINFO
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000344// We manually declare these extern functions because finding the correct
Chandler Carruth91219852013-08-12 10:40:11 +0000345// headers from various terminfo, curses, or other sources is harder than
346// writing their specs down.
347extern "C" int setupterm(char *term, int filedes, int *errret);
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000348extern "C" struct term *set_curterm(struct term *termp);
349extern "C" int del_curterm(struct term *termp);
Chandler Carruth91219852013-08-12 10:40:11 +0000350extern "C" int tigetnum(char *capname);
351#endif
352
Chris Bieneman78272172014-09-24 18:35:58 +0000353#ifdef HAVE_TERMINFO
Chris Bienemanfa35e112014-09-22 22:39:20 +0000354static ManagedStatic<sys::Mutex> TermColorMutex;
Chris Bieneman78272172014-09-24 18:35:58 +0000355#endif
Chris Bienemanfa35e112014-09-22 22:39:20 +0000356
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000357static bool terminalHasColors(int fd) {
Chandler Carruthf11f1e42013-08-12 09:49:17 +0000358#ifdef HAVE_TERMINFO
359 // First, acquire a global lock because these C routines are thread hostile.
Chris Bienemanfa35e112014-09-22 22:39:20 +0000360 MutexGuard G(*TermColorMutex);
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000361
362 int errret = 0;
Craig Toppere73658d2014-04-28 04:05:08 +0000363 if (setupterm((char *)nullptr, fd, &errret) != 0)
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000364 // Regardless of why, if we can't get terminfo, we shouldn't try to print
365 // colors.
366 return false;
367
Chandler Carruthf11f1e42013-08-12 09:49:17 +0000368 // Test whether the terminal as set up supports color output. How to do this
369 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
370 // would be nice to avoid a dependency on curses proper when we can make do
371 // with a minimal terminfo parsing library. Also, we don't really care whether
372 // the terminal supports the curses-specific color changing routines, merely
373 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
374 // strategy here is just to query the baseline colors capability and if it
375 // supports colors at all to assume it will translate the escape codes into
376 // whatever range of colors it does support. We can add more detailed tests
377 // here if users report them as necessary.
378 //
379 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
380 // the terminfo says that no colors are supported.
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000381 bool HasColors = tigetnum(const_cast<char *>("colors")) > 0;
382
383 // Now extract the structure allocated by setupterm and free its memory
384 // through a really silly dance.
Craig Toppere73658d2014-04-28 04:05:08 +0000385 struct term *termp = set_curterm((struct term *)nullptr);
Chandler Carruth67ff8b72013-08-18 01:20:32 +0000386 (void)del_curterm(termp); // Drop any errors here.
387
388 // Return true if we found a color capabilities for the current terminal.
389 if (HasColors)
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000390 return true;
391#endif
392
393 // Otherwise, be conservative.
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000394 return false;
395}
396
Daniel Dunbar712de822012-07-20 18:29:38 +0000397bool Process::FileDescriptorHasColors(int fd) {
398 // A file descriptor has colors if it is displayed and the terminal has
399 // colors.
Chandler Carruthcad7e5e2013-08-07 08:47:36 +0000400 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
Daniel Dunbar712de822012-07-20 18:29:38 +0000401}
402
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000403bool Process::StandardOutHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000404 return FileDescriptorHasColors(STDOUT_FILENO);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000405}
406
407bool Process::StandardErrHasColors() {
Daniel Dunbar712de822012-07-20 18:29:38 +0000408 return FileDescriptorHasColors(STDERR_FILENO);
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000409}
410
Nico Rieck92d649a2013-09-11 00:36:48 +0000411void Process::UseANSIEscapeCodes(bool /*enable*/) {
412 // No effect.
413}
414
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000415bool Process::ColorNeedsFlush() {
416 // No, we use ANSI escape sequences.
417 return false;
418}
419
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000420const char *Process::OutputColor(char code, bool bold, bool bg) {
421 return colorcodes[bg?1:0][bold?1:0][code&7];
422}
423
424const char *Process::OutputBold(bool bg) {
425 return "\033[1m";
426}
427
Benjamin Kramer13d16f32012-04-16 08:56:50 +0000428const char *Process::OutputReverse() {
429 return "\033[7m";
430}
431
Torok Edwin9b5a47f2009-06-04 07:09:50 +0000432const char *Process::ResetColor() {
433 return "\033[0m";
434}
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000435
Todd Fiala4ccfe392014-02-05 05:04:36 +0000436#if !defined(HAVE_DECL_ARC4RANDOM) || !HAVE_DECL_ARC4RANDOM
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000437static unsigned GetRandomNumberSeed() {
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000438 // Attempt to get the initial seed from /dev/urandom, if possible.
439 if (FILE *RandomSource = ::fopen("/dev/urandom", "r")) {
440 unsigned seed;
441 int count = ::fread((void *)&seed, sizeof(seed), 1, RandomSource);
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000442 ::fclose(RandomSource);
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000443
444 // Return the seed if the read was successful.
445 if (count == 1)
446 return seed;
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000447 }
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000448
449 // Otherwise, swizzle the current time and the process ID to form a reasonable
450 // seed.
Chandler Carruth5473dfb2012-12-31 11:45:20 +0000451 TimeValue Now = TimeValue::now();
Daniel Dunbar5f1c9562012-05-08 20:38:00 +0000452 return hash_combine(Now.seconds(), Now.nanoseconds(), ::getpid());
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000453}
454#endif
455
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000456unsigned llvm::sys::Process::GetRandomNumber() {
Todd Fiala4ccfe392014-02-05 05:04:36 +0000457#if defined(HAVE_DECL_ARC4RANDOM) && HAVE_DECL_ARC4RANDOM
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000458 return arc4random();
459#else
NAKAMURA Takumi7bec7412012-05-06 08:24:24 +0000460 static int x = (::srand(GetRandomNumberSeed()), 0);
461 (void)x;
NAKAMURA Takumi54acb282012-05-06 08:24:18 +0000462 return ::rand();
463#endif
464}