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