LLVM 17.0.0git
Process.inc
Go to the documentation of this file.
1//===- Unix/Process.cpp - Unix Process Implementation --------- -*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides the generic Unix implementation of the Process class.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Unix.h"
14#include "llvm/ADT/Hashing.h"
15#include "llvm/ADT/StringRef.h"
16#include "llvm/Config/config.h"
17#include <mutex>
18#include <optional>
19#if HAVE_FCNTL_H
20#include <fcntl.h>
21#endif
22#ifdef HAVE_SYS_TIME_H
23#include <sys/time.h>
24#endif
25#ifdef HAVE_SYS_RESOURCE_H
26#include <sys/resource.h>
27#endif
28#ifdef HAVE_SYS_STAT_H
29#include <sys/stat.h>
30#endif
31#if HAVE_SIGNAL_H
32#include <signal.h>
33#endif
34#if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
35#include <malloc.h>
36#endif
37#if defined(HAVE_MALLCTL)
38#include <malloc_np.h>
39#endif
40#ifdef HAVE_MALLOC_MALLOC_H
41#include <malloc/malloc.h>
42#endif
43#ifdef HAVE_SYS_IOCTL_H
44#include <sys/ioctl.h>
45#endif
46#ifdef HAVE_TERMIOS_H
47#include <termios.h>
48#endif
49
50//===----------------------------------------------------------------------===//
51//=== WARNING: Implementation here must contain only generic UNIX code that
52//=== is guaranteed to work on *all* UNIX variants.
53//===----------------------------------------------------------------------===//
54
55using namespace llvm;
56using namespace sys;
57
58static std::pair<std::chrono::microseconds, std::chrono::microseconds>
59getRUsageTimes() {
60#if defined(HAVE_GETRUSAGE)
61 struct rusage RU;
62 ::getrusage(RUSAGE_SELF, &RU);
63 return {toDuration(RU.ru_utime), toDuration(RU.ru_stime)};
64#else
65#warning Cannot get usage times on this platform
66 return {std::chrono::microseconds::zero(), std::chrono::microseconds::zero()};
67#endif
68}
69
70Process::Pid Process::getProcessId() {
71 static_assert(sizeof(Pid) >= sizeof(pid_t),
72 "Process::Pid should be big enough to store pid_t");
73 return Pid(::getpid());
74}
75
76// On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
77// offset in mmap(3) should be aligned to the AllocationGranularity.
78Expected<unsigned> Process::getPageSize() {
79#if defined(HAVE_GETPAGESIZE)
80 static const int page_size = ::getpagesize();
81#elif defined(HAVE_SYSCONF)
82 static long page_size = ::sysconf(_SC_PAGE_SIZE);
83#else
84#error Cannot get the page size on this machine
85#endif
86 if (page_size == -1)
87 return errorCodeToError(std::error_code(errno, std::generic_category()));
88
89 return static_cast<unsigned>(page_size);
90}
91
92size_t Process::GetMallocUsage() {
93#if defined(HAVE_MALLINFO2)
94 struct mallinfo2 mi;
95 mi = ::mallinfo2();
96 return mi.uordblks;
97#elif defined(HAVE_MALLINFO)
98 struct mallinfo mi;
99 mi = ::mallinfo();
100 return mi.uordblks;
101#elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
102 malloc_statistics_t Stats;
103 malloc_zone_statistics(malloc_default_zone(), &Stats);
104 return Stats.size_in_use; // darwin
105#elif defined(HAVE_MALLCTL)
106 size_t alloc, sz;
107 sz = sizeof(size_t);
108 if (mallctl("stats.allocated", &alloc, &sz, NULL, 0) == 0)
109 return alloc;
110 return 0;
111#elif defined(HAVE_SBRK)
112 // Note this is only an approximation and more closely resembles
113 // the value returned by mallinfo in the arena field.
114 static char *StartOfMemory = reinterpret_cast<char *>(::sbrk(0));
115 char *EndOfMemory = (char *)sbrk(0);
116 if (EndOfMemory != ((char *)-1) && StartOfMemory != ((char *)-1))
117 return EndOfMemory - StartOfMemory;
118 return 0;
119#else
120#warning Cannot get malloc info on this platform
121 return 0;
122#endif
123}
124
125void Process::GetTimeUsage(TimePoint<> &elapsed,
126 std::chrono::nanoseconds &user_time,
127 std::chrono::nanoseconds &sys_time) {
128 elapsed = std::chrono::system_clock::now();
129 std::tie(user_time, sys_time) = getRUsageTimes();
130}
131
132#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
133#include <mach/mach.h>
134#endif
135
136// Some LLVM programs such as bugpoint produce core files as a normal part of
137// their operation. To prevent the disk from filling up, this function
138// does what's necessary to prevent their generation.
139void Process::PreventCoreFiles() {
140#if HAVE_SETRLIMIT
141 struct rlimit rlim;
142 rlim.rlim_cur = rlim.rlim_max = 0;
143 setrlimit(RLIMIT_CORE, &rlim);
144#endif
145
146#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
147 // Disable crash reporting on Mac OS X 10.0-10.4
148
149 // get information about the original set of exception ports for the task
150 mach_msg_type_number_t Count = 0;
151 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
152 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
153 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
154 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
155 kern_return_t err = task_get_exception_ports(
156 mach_task_self(), EXC_MASK_ALL, OriginalMasks, &Count, OriginalPorts,
157 OriginalBehaviors, OriginalFlavors);
158 if (err == KERN_SUCCESS) {
159 // replace each with MACH_PORT_NULL.
160 for (unsigned i = 0; i != Count; ++i)
161 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
162 MACH_PORT_NULL, OriginalBehaviors[i],
163 OriginalFlavors[i]);
164 }
165
166 // Disable crash reporting on Mac OS X 10.5
167 signal(SIGABRT, _exit);
168 signal(SIGILL, _exit);
169 signal(SIGFPE, _exit);
170 signal(SIGSEGV, _exit);
171 signal(SIGBUS, _exit);
172#endif
173
174 coreFilesPrevented = true;
175}
176
177std::optional<std::string> Process::GetEnv(StringRef Name) {
178 std::string NameStr = Name.str();
179 const char *Val = ::getenv(NameStr.c_str());
180 if (!Val)
181 return std::nullopt;
182 return std::string(Val);
183}
184
185namespace {
186class FDCloser {
187public:
188 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
189 void keepOpen() { KeepOpen = true; }
190 ~FDCloser() {
191 if (!KeepOpen && FD >= 0)
192 ::close(FD);
193 }
194
195private:
196 FDCloser(const FDCloser &) = delete;
197 void operator=(const FDCloser &) = delete;
198
199 int &FD;
200 bool KeepOpen;
201};
202} // namespace
203
204std::error_code Process::FixupStandardFileDescriptors() {
205 int NullFD = -1;
206 FDCloser FDC(NullFD);
207 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
208 for (int StandardFD : StandardFDs) {
209 struct stat st;
210 errno = 0;
211 if (RetryAfterSignal(-1, ::fstat, StandardFD, &st) < 0) {
212 assert(errno && "expected errno to be set if fstat failed!");
213 // fstat should return EBADF if the file descriptor is closed.
214 if (errno != EBADF)
215 return std::error_code(errno, std::generic_category());
216 }
217 // if fstat succeeds, move on to the next FD.
218 if (!errno)
219 continue;
220 assert(errno == EBADF && "expected errno to have EBADF at this point!");
221
222 if (NullFD < 0) {
223 // Call ::open in a lambda to avoid overload resolution in
224 // RetryAfterSignal when open is overloaded, such as in Bionic.
225 auto Open = [&]() { return ::open("/dev/null", O_RDWR); };
226 if ((NullFD = RetryAfterSignal(-1, Open)) < 0)
227 return std::error_code(errno, std::generic_category());
228 }
229
230 if (NullFD == StandardFD)
231 FDC.keepOpen();
232 else if (dup2(NullFD, StandardFD) < 0)
233 return std::error_code(errno, std::generic_category());
234 }
235 return std::error_code();
236}
237
238std::error_code Process::SafelyCloseFileDescriptor(int FD) {
239 // Create a signal set filled with *all* signals.
240 sigset_t FullSet, SavedSet;
241 if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
242 return std::error_code(errno, std::generic_category());
243
244 // Atomically swap our current signal mask with a full mask.
245#if LLVM_ENABLE_THREADS
246 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
247 return std::error_code(EC, std::generic_category());
248#else
249 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
250 return std::error_code(errno, std::generic_category());
251#endif
252 // Attempt to close the file descriptor.
253 // We need to save the error, if one occurs, because our subsequent call to
254 // pthread_sigmask might tamper with errno.
255 int ErrnoFromClose = 0;
256 if (::close(FD) < 0)
257 ErrnoFromClose = errno;
258 // Restore the signal mask back to what we saved earlier.
259 int EC = 0;
260#if LLVM_ENABLE_THREADS
261 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
262#else
263 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
264 EC = errno;
265#endif
266 // The error code from close takes precedence over the one from
267 // pthread_sigmask.
268 if (ErrnoFromClose)
269 return std::error_code(ErrnoFromClose, std::generic_category());
270 return std::error_code(EC, std::generic_category());
271}
272
273bool Process::StandardInIsUserInput() {
274 return FileDescriptorIsDisplayed(STDIN_FILENO);
275}
276
277bool Process::StandardOutIsDisplayed() {
278 return FileDescriptorIsDisplayed(STDOUT_FILENO);
279}
280
281bool Process::StandardErrIsDisplayed() {
282 return FileDescriptorIsDisplayed(STDERR_FILENO);
283}
284
285bool Process::FileDescriptorIsDisplayed(int fd) {
286#if HAVE_ISATTY
287 return isatty(fd);
288#else
289 // If we don't have isatty, just return false.
290 return false;
291#endif
292}
293
294static unsigned getColumns() {
295 // If COLUMNS is defined in the environment, wrap to that many columns.
296 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
297 int Columns = std::atoi(ColumnsStr);
298 if (Columns > 0)
299 return Columns;
300 }
301
302 // We used to call ioctl TIOCGWINSZ to determine the width. It is considered
303 // unuseful.
304 return 0;
305}
306
307unsigned Process::StandardOutColumns() {
308 if (!StandardOutIsDisplayed())
309 return 0;
310
311 return getColumns();
312}
313
314unsigned Process::StandardErrColumns() {
315 if (!StandardErrIsDisplayed())
316 return 0;
317
318 return getColumns();
319}
320
321#ifdef LLVM_ENABLE_TERMINFO
322// We manually declare these extern functions because finding the correct
323// headers from various terminfo, curses, or other sources is harder than
324// writing their specs down.
325extern "C" int setupterm(char *term, int filedes, int *errret);
326extern "C" struct term *set_curterm(struct term *termp);
327extern "C" int del_curterm(struct term *termp);
328extern "C" int tigetnum(char *capname);
329#endif
330
331bool checkTerminalEnvironmentForColors() {
332 if (const char *TermStr = std::getenv("TERM")) {
333 return StringSwitch<bool>(TermStr)
334 .Case("ansi", true)
335 .Case("cygwin", true)
336 .Case("linux", true)
337 .StartsWith("screen", true)
338 .StartsWith("xterm", true)
339 .StartsWith("vt100", true)
340 .StartsWith("rxvt", true)
341 .EndsWith("color", true)
342 .Default(false);
343 }
344
345 return false;
346}
347
348static bool terminalHasColors(int fd) {
349#ifdef LLVM_ENABLE_TERMINFO
350 // First, acquire a global lock because these C routines are thread hostile.
351 static std::mutex TermColorMutex;
352 std::lock_guard<std::mutex> G(TermColorMutex);
353
354 struct term *previous_term = set_curterm(nullptr);
355 int errret = 0;
356 if (setupterm(nullptr, fd, &errret) != 0)
357 // Regardless of why, if we can't get terminfo, we shouldn't try to print
358 // colors.
359 return false;
360
361 // Test whether the terminal as set up supports color output. How to do this
362 // isn't entirely obvious. We can use the curses routine 'has_colors' but it
363 // would be nice to avoid a dependency on curses proper when we can make do
364 // with a minimal terminfo parsing library. Also, we don't really care whether
365 // the terminal supports the curses-specific color changing routines, merely
366 // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
367 // strategy here is just to query the baseline colors capability and if it
368 // supports colors at all to assume it will translate the escape codes into
369 // whatever range of colors it does support. We can add more detailed tests
370 // here if users report them as necessary.
371 //
372 // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
373 // the terminfo says that no colors are supported.
374 int colors_ti = tigetnum(const_cast<char *>("colors"));
375 bool HasColors =
376 colors_ti >= 0 ? colors_ti : checkTerminalEnvironmentForColors();
377
378 // Now extract the structure allocated by setupterm and free its memory
379 // through a really silly dance.
380 struct term *termp = set_curterm(previous_term);
381 (void)del_curterm(termp); // Drop any errors here.
382
383 // Return true if we found a color capabilities for the current terminal.
384 return HasColors;
385#else
386 // When the terminfo database is not available, check if the current terminal
387 // is one of terminals that are known to support ANSI color escape codes.
388 return checkTerminalEnvironmentForColors();
389#endif
390}
391
392bool Process::FileDescriptorHasColors(int fd) {
393 // A file descriptor has colors if it is displayed and the terminal has
394 // colors.
395 return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
396}
397
398bool Process::StandardOutHasColors() {
399 return FileDescriptorHasColors(STDOUT_FILENO);
400}
401
402bool Process::StandardErrHasColors() {
403 return FileDescriptorHasColors(STDERR_FILENO);
404}
405
406void Process::UseANSIEscapeCodes(bool /*enable*/) {
407 // No effect.
408}
409
410bool Process::ColorNeedsFlush() {
411 // No, we use ANSI escape sequences.
412 return false;
413}
414
415const char *Process::OutputColor(char code, bool bold, bool bg) {
416 return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 7];
417}
418
419const char *Process::OutputBold(bool bg) { return "\033[1m"; }
420
421const char *Process::OutputReverse() { return "\033[7m"; }
422
423const char *Process::ResetColor() { return "\033[0m"; }
424
425#if !HAVE_DECL_ARC4RANDOM
426static unsigned GetRandomNumberSeed() {
427 // Attempt to get the initial seed from /dev/urandom, if possible.
428 int urandomFD = open("/dev/urandom", O_RDONLY);
429
430 if (urandomFD != -1) {
431 unsigned seed;
432 // Don't use a buffered read to avoid reading more data
433 // from /dev/urandom than we need.
434 int count = read(urandomFD, (void *)&seed, sizeof(seed));
435
436 close(urandomFD);
437
438 // Return the seed if the read was successful.
439 if (count == sizeof(seed))
440 return seed;
441 }
442
443 // Otherwise, swizzle the current time and the process ID to form a reasonable
444 // seed.
445 const auto Now = std::chrono::high_resolution_clock::now();
446 return hash_combine(Now.time_since_epoch().count(), ::getpid());
447}
448#endif
449
451#if HAVE_DECL_ARC4RANDOM
452 return arc4random();
453#else
454 static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0);
455 (void)x;
456 return ::rand();
457#endif
458}
459
460[[noreturn]] void Process::ExitNoCleanup(int RetCode) { _Exit(RetCode); }
std::string Name
#define G(x, y, z)
Definition: MD5.cpp:56
block placement Basic Block Placement Stats
static const char colorcodes[2][2][8][10]
Definition: Process.cpp:84
static bool coreFilesPrevented
Definition: Process.cpp:91
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Tagged union holding either a T or a Error.
Definition: Error.h:470
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
StringSwitch & StartsWith(StringLiteral S, T Value)
Definition: StringSwitch.h:83
StringSwitch & EndsWith(StringLiteral S, T Value)
Definition: StringSwitch.h:76
static unsigned GetRandomNumber()
Get the result of a process wide random number generator.
value_type read(const void *memory, endianness endian)
Read a value of a particular endianness from memory.
Definition: Endian.h:63
decltype(auto) RetryAfterSignal(const FailT &Fail, const Fun &F, const Args &... As)
Definition: Errno.h:32
std::chrono::nanoseconds toDuration(FILETIME Time)
std::chrono::time_point< std::chrono::system_clock, D > TimePoint
A time point on the system clock.
Definition: Chrono.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:2011
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:92
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition: Hashing.h:613