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