LLVM 20.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 "llvm/Config/llvm-config.h" // for LLVM_ENABLE_THREADS
18#include <mutex>
19#include <optional>
20#include <fcntl.h>
21#ifdef HAVE_SYS_TIME_H
22#include <sys/time.h>
23#endif
24#ifdef HAVE_SYS_RESOURCE_H
25#include <sys/resource.h>
26#endif
27#include <sys/stat.h>
28#if HAVE_SIGNAL_H
29#include <signal.h>
30#endif
31#if defined(HAVE_MALLINFO) || defined(HAVE_MALLINFO2)
32#include <malloc.h>
33#endif
34#if defined(HAVE_MALLCTL)
35#include <malloc_np.h>
36#endif
37#ifdef HAVE_MALLOC_MALLOC_H
38#include <malloc/malloc.h>
39#endif
40#ifdef HAVE_SYS_IOCTL_H
41#include <sys/ioctl.h>
42#endif
43#ifdef HAVE_TERMIOS_H
44#include <termios.h>
45#endif
46
47//===----------------------------------------------------------------------===//
48//=== WARNING: Implementation here must contain only generic UNIX code that
49//=== is guaranteed to work on *all* UNIX variants.
50//===----------------------------------------------------------------------===//
51
52using namespace llvm;
53using namespace sys;
54
55static std::pair<std::chrono::microseconds, std::chrono::microseconds>
56getRUsageTimes() {
57#if defined(HAVE_GETRUSAGE)
58 struct rusage RU;
59 ::getrusage(RUSAGE_SELF, &RU);
60 return {toDuration(RU.ru_utime), toDuration(RU.ru_stime)};
61#else
62#ifndef __MVS__ // Exclude for MVS in case -pedantic is used
63#warning Cannot get usage times on this platform
64#endif
65 return {std::chrono::microseconds::zero(), std::chrono::microseconds::zero()};
66#endif
67}
68
69Process::Pid Process::getProcessId() {
70 static_assert(sizeof(Pid) >= sizeof(pid_t),
71 "Process::Pid should be big enough to store pid_t");
72 return Pid(::getpid());
73}
74
75// On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
76// offset in mmap(3) should be aligned to the AllocationGranularity.
77Expected<unsigned> Process::getPageSize() {
78#if defined(HAVE_GETPAGESIZE)
79 static const int page_size = ::getpagesize();
80#elif defined(HAVE_SYSCONF)
81 static long page_size = ::sysconf(_SC_PAGE_SIZE);
82#else
83#error Cannot get the page size on this machine
84#endif
85 if (page_size == -1)
87
88 return static_cast<unsigned>(page_size);
89}
90
91size_t Process::GetMallocUsage() {
92#if defined(HAVE_MALLINFO2)
93 struct mallinfo2 mi;
94 mi = ::mallinfo2();
95 return mi.uordblks;
96#elif defined(HAVE_MALLINFO)
97 struct mallinfo mi;
98 mi = ::mallinfo();
99 return mi.uordblks;
100#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
104#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;
109 return 0;
110#elif defined(HAVE_SBRK)
111 // Note this is only an approximation and more closely resembles
112 // the value returned by mallinfo in the arena field.
113 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;
117 return 0;
118#else
119#ifndef __MVS__ // Exclude for MVS in case -pedantic is used
120#warning Cannot get malloc info on this platform
121#endif
122 return 0;
123#endif
124}
125
126void Process::GetTimeUsage(TimePoint<> &elapsed,
127 std::chrono::nanoseconds &user_time,
128 std::chrono::nanoseconds &sys_time) {
129 elapsed = std::chrono::system_clock::now();
130 std::tie(user_time, sys_time) = getRUsageTimes();
131}
132
133#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
134#include <mach/mach.h>
135#endif
136
137// Some LLVM programs such as bugpoint produce core files as a normal part of
138// their operation. To prevent the disk from filling up, this function
139// does what's necessary to prevent their generation.
140void Process::PreventCoreFiles() {
141#if HAVE_SETRLIMIT
142 struct rlimit rlim;
143 getrlimit(RLIMIT_CORE, &rlim);
144#ifdef __linux__
145 // On Linux, if the kernel.core_pattern sysctl starts with a '|' (i.e. it
146 // is being piped to a coredump handler such as systemd-coredumpd), the
147 // kernel ignores RLIMIT_CORE (since we aren't creating a file in the file
148 // system) except for the magic value of 1, which disables coredumps when
149 // piping. 1 byte is too small for any kind of valid core dump, so it
150 // also disables coredumps if kernel.core_pattern creates files directly.
151 // While most piped coredump handlers do respect the crashing processes'
152 // RLIMIT_CORE, this is notable not the case for Debian's systemd-coredump
153 // due to a local patch that changes sysctl.d/50-coredump.conf to ignore
154 // the specified limit and instead use RLIM_INFINITY.
155 //
156 // The alternative to using RLIMIT_CORE=1 would be to use prctl() with the
157 // PR_SET_DUMPABLE flag, however that also prevents ptrace(), so makes it
158 // impossible to attach a debugger.
159 rlim.rlim_cur = std::min<rlim_t>(1, rlim.rlim_max);
160#else
161 rlim.rlim_cur = 0;
162#endif
163 setrlimit(RLIMIT_CORE, &rlim);
164#endif
165
166#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
167 // Disable crash reporting on Mac OS X 10.0-10.4
168
169 // get information about the original set of exception ports for the task
170 mach_msg_type_number_t Count = 0;
171 exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
172 exception_port_t OriginalPorts[EXC_TYPES_COUNT];
173 exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
174 thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
175 kern_return_t err = task_get_exception_ports(
176 mach_task_self(), EXC_MASK_ALL, OriginalMasks, &Count, OriginalPorts,
177 OriginalBehaviors, OriginalFlavors);
178 if (err == KERN_SUCCESS) {
179 // replace each with MACH_PORT_NULL.
180 for (unsigned i = 0; i != Count; ++i)
181 task_set_exception_ports(mach_task_self(), OriginalMasks[i],
182 MACH_PORT_NULL, OriginalBehaviors[i],
183 OriginalFlavors[i]);
184 }
185
186 // Disable crash reporting on Mac OS X 10.5
187 signal(SIGABRT, _exit);
188 signal(SIGILL, _exit);
189 signal(SIGFPE, _exit);
190 signal(SIGSEGV, _exit);
191 signal(SIGBUS, _exit);
192#endif
193
194 coreFilesPrevented = true;
195}
196
197std::optional<std::string> Process::GetEnv(StringRef Name) {
198 std::string NameStr = Name.str();
199 const char *Val = ::getenv(NameStr.c_str());
200 if (!Val)
201 return std::nullopt;
202 return std::string(Val);
203}
204
205namespace {
206class FDCloser {
207public:
208 FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
209 void keepOpen() { KeepOpen = true; }
210 ~FDCloser() {
211 if (!KeepOpen && FD >= 0)
212 ::close(FD);
213 }
214
215private:
216 FDCloser(const FDCloser &) = delete;
217 void operator=(const FDCloser &) = delete;
218
219 int &FD;
220 bool KeepOpen;
221};
222} // namespace
223
224std::error_code Process::FixupStandardFileDescriptors() {
225 int NullFD = -1;
226 FDCloser FDC(NullFD);
227 const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
228 for (int StandardFD : StandardFDs) {
229 struct stat st;
230 errno = 0;
231 if (RetryAfterSignal(-1, ::fstat, StandardFD, &st) < 0) {
232 assert(errno && "expected errno to be set if fstat failed!");
233 // fstat should return EBADF if the file descriptor is closed.
234 if (errno != EBADF)
235 return errnoAsErrorCode();
236 }
237 // if fstat succeeds, move on to the next FD.
238 if (!errno)
239 continue;
240 assert(errno == EBADF && "expected errno to have EBADF at this point!");
241
242 if (NullFD < 0) {
243 // Call ::open in a lambda to avoid overload resolution in
244 // RetryAfterSignal when open is overloaded, such as in Bionic.
245 auto Open = [&]() { return ::open("/dev/null", O_RDWR); };
246 if ((NullFD = RetryAfterSignal(-1, Open)) < 0)
247 return errnoAsErrorCode();
248 }
249
250 if (NullFD == StandardFD)
251 FDC.keepOpen();
252 else if (dup2(NullFD, StandardFD) < 0)
253 return errnoAsErrorCode();
254 }
255 return std::error_code();
256}
257
258std::error_code Process::SafelyCloseFileDescriptor(int FD) {
259 // Create a signal set filled with *all* signals.
260 sigset_t FullSet, SavedSet;
261 if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
262 return errnoAsErrorCode();
263
264 // Atomically swap our current signal mask with a full mask.
265#if LLVM_ENABLE_THREADS
266 if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
267 return std::error_code(EC, std::generic_category());
268#else
269 if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
270 return errnoAsErrorCode();
271#endif
272 // Attempt to close the file descriptor.
273 // We need to save the error, if one occurs, because our subsequent call to
274 // pthread_sigmask might tamper with errno.
275 int ErrnoFromClose = 0;
276 if (::close(FD) < 0)
277 ErrnoFromClose = errno;
278 // Restore the signal mask back to what we saved earlier.
279 int EC = 0;
280#if LLVM_ENABLE_THREADS
281 EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
282#else
283 if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
284 EC = errno;
285#endif
286 // The error code from close takes precedence over the one from
287 // pthread_sigmask.
288 if (ErrnoFromClose)
289 return std::error_code(ErrnoFromClose, std::generic_category());
290 return std::error_code(EC, std::generic_category());
291}
292
293bool Process::StandardInIsUserInput() {
294 return FileDescriptorIsDisplayed(STDIN_FILENO);
295}
296
297bool Process::StandardOutIsDisplayed() {
298 return FileDescriptorIsDisplayed(STDOUT_FILENO);
299}
300
301bool Process::StandardErrIsDisplayed() {
302 return FileDescriptorIsDisplayed(STDERR_FILENO);
303}
304
305bool Process::FileDescriptorIsDisplayed(int fd) {
306#if HAVE_ISATTY
307 return isatty(fd);
308#else
309 // If we don't have isatty, just return false.
310 return false;
311#endif
312}
313
314static unsigned getColumns() {
315 // If COLUMNS is defined in the environment, wrap to that many columns.
316 if (const char *ColumnsStr = std::getenv("COLUMNS")) {
317 int Columns = std::atoi(ColumnsStr);
318 if (Columns > 0)
319 return Columns;
320 }
321
322 // We used to call ioctl TIOCGWINSZ to determine the width. It is considered
323 // unuseful.
324 return 0;
325}
326
327unsigned Process::StandardOutColumns() {
328 if (!StandardOutIsDisplayed())
329 return 0;
330
331 return getColumns();
332}
333
334unsigned Process::StandardErrColumns() {
335 if (!StandardErrIsDisplayed())
336 return 0;
337
338 return getColumns();
339}
340
341static bool terminalHasColors() {
342 // Check if the current terminal is one of terminals that are known to support
343 // ANSI color escape codes.
344 if (const char *TermStr = std::getenv("TERM")) {
345 return StringSwitch<bool>(TermStr)
346 .Case("ansi", true)
347 .Case("cygwin", true)
348 .Case("linux", true)
349 .StartsWith("screen", true)
350 .StartsWith("xterm", true)
351 .StartsWith("vt100", true)
352 .StartsWith("rxvt", true)
353 .EndsWith("color", true)
354 .Default(false);
355 }
356
357 return false;
358}
359
360bool Process::FileDescriptorHasColors(int fd) {
361 // A file descriptor has colors if it is displayed and the terminal has
362 // colors.
363 return FileDescriptorIsDisplayed(fd) && terminalHasColors();
364}
365
366bool Process::StandardOutHasColors() {
367 return FileDescriptorHasColors(STDOUT_FILENO);
368}
369
370bool Process::StandardErrHasColors() {
371 return FileDescriptorHasColors(STDERR_FILENO);
372}
373
374void Process::UseANSIEscapeCodes(bool /*enable*/) {
375 // No effect.
376}
377
378bool Process::ColorNeedsFlush() {
379 // No, we use ANSI escape sequences.
380 return false;
381}
382
383const char *Process::OutputColor(char code, bool bold, bool bg) {
384 return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 15];
385}
386
387const char *Process::OutputBold(bool bg) { return "\033[1m"; }
388
389const char *Process::OutputReverse() { return "\033[7m"; }
390
391const char *Process::ResetColor() { return "\033[0m"; }
392
393#if !HAVE_DECL_ARC4RANDOM
394static unsigned GetRandomNumberSeed() {
395 // Attempt to get the initial seed from /dev/urandom, if possible.
396 int urandomFD = open("/dev/urandom", O_RDONLY);
397
398 if (urandomFD != -1) {
399 unsigned seed;
400 // Don't use a buffered read to avoid reading more data
401 // from /dev/urandom than we need.
402 int count = read(urandomFD, (void *)&seed, sizeof(seed));
403
404 close(urandomFD);
405
406 // Return the seed if the read was successful.
407 if (count == sizeof(seed))
408 return seed;
409 }
410
411 // Otherwise, swizzle the current time and the process ID to form a reasonable
412 // seed.
413 const auto Now = std::chrono::high_resolution_clock::now();
414 return hash_combine(Now.time_since_epoch().count(), ::getpid());
415}
416#endif
417
419#if HAVE_DECL_ARC4RANDOM
420 return arc4random();
421#else
422 static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0);
423 (void)x;
424 return ::rand();
425#endif
426}
427
428[[noreturn]] void Process::ExitNoCleanup(int RetCode) { _Exit(RetCode); }
std::string Name
block placement Basic Block Placement Stats
static bool coreFilesPrevented
Definition: Process.cpp:106
static const char colorcodes[2][2][16][11]
Definition: Process.cpp:98
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Tagged union holding either a T or a Error.
Definition: Error.h:481
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
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:58
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:1938
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition: Hashing.h:590
std::error_code errnoAsErrorCode()
Helper to get errno as an std::error_code.
Definition: Error.h:1226