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