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#ifndef __MVS__ // Exclude for MVS in case -pedantic is used
66#warning Cannot get usage times on this platform
67#endif
68  return {std::chrono::microseconds::zero(), std::chrono::microseconds::zero()};
69#endif
70}
71
72Process::Pid Process::getProcessId() {
73  static_assert(sizeof(Pid) >= sizeof(pid_t),
74                "Process::Pid should be big enough to store pid_t");
75  return Pid(::getpid());
76}
77
78// On Cygwin, getpagesize() returns 64k(AllocationGranularity) and
79// offset in mmap(3) should be aligned to the AllocationGranularity.
80Expected<unsigned> Process::getPageSize() {
81#if defined(HAVE_GETPAGESIZE)
82  static const int page_size = ::getpagesize();
83#elif defined(HAVE_SYSCONF)
84  static long page_size = ::sysconf(_SC_PAGE_SIZE);
85#else
86#error Cannot get the page size on this machine
87#endif
88  if (page_size == -1)
89    return errorCodeToError(std::error_code(errno, std::generic_category()));
90
91  return static_cast<unsigned>(page_size);
92}
93
94size_t Process::GetMallocUsage() {
95#if defined(HAVE_MALLINFO2)
96  struct mallinfo2 mi;
97  mi = ::mallinfo2();
98  return mi.uordblks;
99#elif defined(HAVE_MALLINFO)
100  struct mallinfo mi;
101  mi = ::mallinfo();
102  return mi.uordblks;
103#elif defined(HAVE_MALLOC_ZONE_STATISTICS) && defined(HAVE_MALLOC_MALLOC_H)
104  malloc_statistics_t Stats;
105  malloc_zone_statistics(malloc_default_zone(), &Stats);
106  return Stats.size_in_use; // darwin
107#elif defined(HAVE_MALLCTL)
108  size_t alloc, sz;
109  sz = sizeof(size_t);
110  if (mallctl("stats.allocated", &alloc, &sz, NULL, 0) == 0)
111    return alloc;
112  return 0;
113#elif defined(HAVE_SBRK)
114  // Note this is only an approximation and more closely resembles
115  // the value returned by mallinfo in the arena field.
116  static char *StartOfMemory = reinterpret_cast<char *>(::sbrk(0));
117  char *EndOfMemory = (char *)sbrk(0);
118  if (EndOfMemory != ((char *)-1) && StartOfMemory != ((char *)-1))
119    return EndOfMemory - StartOfMemory;
120  return 0;
121#else
122#ifndef __MVS__ // Exclude for MVS in case -pedantic is used
123#warning Cannot get malloc info on this platform
124#endif
125  return 0;
126#endif
127}
128
129void Process::GetTimeUsage(TimePoint<> &elapsed,
130                           std::chrono::nanoseconds &user_time,
131                           std::chrono::nanoseconds &sys_time) {
132  elapsed = std::chrono::system_clock::now();
133  std::tie(user_time, sys_time) = getRUsageTimes();
134}
135
136#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
137#include <mach/mach.h>
138#endif
139
140// Some LLVM programs such as bugpoint produce core files as a normal part of
141// their operation. To prevent the disk from filling up, this function
142// does what's necessary to prevent their generation.
143void Process::PreventCoreFiles() {
144#if HAVE_SETRLIMIT
145  struct rlimit rlim;
146  rlim.rlim_cur = rlim.rlim_max = 0;
147  setrlimit(RLIMIT_CORE, &rlim);
148#endif
149
150#if defined(HAVE_MACH_MACH_H) && !defined(__GNU__)
151  // Disable crash reporting on Mac OS X 10.0-10.4
152
153  // get information about the original set of exception ports for the task
154  mach_msg_type_number_t Count = 0;
155  exception_mask_t OriginalMasks[EXC_TYPES_COUNT];
156  exception_port_t OriginalPorts[EXC_TYPES_COUNT];
157  exception_behavior_t OriginalBehaviors[EXC_TYPES_COUNT];
158  thread_state_flavor_t OriginalFlavors[EXC_TYPES_COUNT];
159  kern_return_t err = task_get_exception_ports(
160      mach_task_self(), EXC_MASK_ALL, OriginalMasks, &Count, OriginalPorts,
161      OriginalBehaviors, OriginalFlavors);
162  if (err == KERN_SUCCESS) {
163    // replace each with MACH_PORT_NULL.
164    for (unsigned i = 0; i != Count; ++i)
165      task_set_exception_ports(mach_task_self(), OriginalMasks[i],
166                               MACH_PORT_NULL, OriginalBehaviors[i],
167                               OriginalFlavors[i]);
168  }
169
170  // Disable crash reporting on Mac OS X 10.5
171  signal(SIGABRT, _exit);
172  signal(SIGILL, _exit);
173  signal(SIGFPE, _exit);
174  signal(SIGSEGV, _exit);
175  signal(SIGBUS, _exit);
176#endif
177
178  coreFilesPrevented = true;
179}
180
181std::optional<std::string> Process::GetEnv(StringRef Name) {
182  std::string NameStr = Name.str();
183  const char *Val = ::getenv(NameStr.c_str());
184  if (!Val)
185    return std::nullopt;
186  return std::string(Val);
187}
188
189namespace {
190class FDCloser {
191public:
192  FDCloser(int &FD) : FD(FD), KeepOpen(false) {}
193  void keepOpen() { KeepOpen = true; }
194  ~FDCloser() {
195    if (!KeepOpen && FD >= 0)
196      ::close(FD);
197  }
198
199private:
200  FDCloser(const FDCloser &) = delete;
201  void operator=(const FDCloser &) = delete;
202
203  int &FD;
204  bool KeepOpen;
205};
206} // namespace
207
208std::error_code Process::FixupStandardFileDescriptors() {
209  int NullFD = -1;
210  FDCloser FDC(NullFD);
211  const int StandardFDs[] = {STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO};
212  for (int StandardFD : StandardFDs) {
213    struct stat st;
214    errno = 0;
215    if (RetryAfterSignal(-1, ::fstat, StandardFD, &st) < 0) {
216      assert(errno && "expected errno to be set if fstat failed!");
217      // fstat should return EBADF if the file descriptor is closed.
218      if (errno != EBADF)
219        return std::error_code(errno, std::generic_category());
220    }
221    // if fstat succeeds, move on to the next FD.
222    if (!errno)
223      continue;
224    assert(errno == EBADF && "expected errno to have EBADF at this point!");
225
226    if (NullFD < 0) {
227      // Call ::open in a lambda to avoid overload resolution in
228      // RetryAfterSignal when open is overloaded, such as in Bionic.
229      auto Open = [&]() { return ::open("/dev/null", O_RDWR); };
230      if ((NullFD = RetryAfterSignal(-1, Open)) < 0)
231        return std::error_code(errno, std::generic_category());
232    }
233
234    if (NullFD == StandardFD)
235      FDC.keepOpen();
236    else if (dup2(NullFD, StandardFD) < 0)
237      return std::error_code(errno, std::generic_category());
238  }
239  return std::error_code();
240}
241
242// Close a file descriptor while being mindful of EINTR.
243//
244// On Unix systems closing a file descriptor usually starts with removing it
245// from the fd table (or an equivalent structure). This means any error
246// generated past that point will still result in the entry being cleared.
247//
248// Make sure to not bubble up EINTR as there is nothing to do in that case.
249// XXX what about other errors?
250#if defined(__linux__) || defined(__DragonFly__) || defined(__FreeBSD__) || \
251    defined(__NetBSD__) || defined(__OpenBSD__)
252std::error_code Process::SafelyCloseFileDescriptor(int FD) {
253  int EC = 0;
254  if (::close(FD) < 0) {
255    if (errno != EINTR)
256      EC = errno;
257  }
258  return std::error_code(EC, std::generic_category());
259}
260#else
261std::error_code Process::SafelyCloseFileDescriptor(int FD) {
262  // Create a signal set filled with *all* signals.
263  sigset_t FullSet, SavedSet;
264  if (sigfillset(&FullSet) < 0 || sigfillset(&SavedSet) < 0)
265    return std::error_code(errno, std::generic_category());
266
267    // Atomically swap our current signal mask with a full mask.
268#if LLVM_ENABLE_THREADS
269  if (int EC = pthread_sigmask(SIG_SETMASK, &FullSet, &SavedSet))
270    return std::error_code(EC, std::generic_category());
271#else
272  if (sigprocmask(SIG_SETMASK, &FullSet, &SavedSet) < 0)
273    return std::error_code(errno, std::generic_category());
274#endif
275  // Attempt to close the file descriptor.
276  // We need to save the error, if one occurs, because our subsequent call to
277  // pthread_sigmask might tamper with errno.
278  int ErrnoFromClose = 0;
279  if (::close(FD) < 0)
280    ErrnoFromClose = errno;
281  // Restore the signal mask back to what we saved earlier.
282  int EC = 0;
283#if LLVM_ENABLE_THREADS
284  EC = pthread_sigmask(SIG_SETMASK, &SavedSet, nullptr);
285#else
286  if (sigprocmask(SIG_SETMASK, &SavedSet, nullptr) < 0)
287    EC = errno;
288#endif
289  // The error code from close takes precedence over the one from
290  // pthread_sigmask.
291  if (ErrnoFromClose)
292    return std::error_code(ErrnoFromClose, std::generic_category());
293  return std::error_code(EC, std::generic_category());
294}
295#endif
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
345#ifdef LLVM_ENABLE_TERMINFO
346// We manually declare these extern functions because finding the correct
347// headers from various terminfo, curses, or other sources is harder than
348// writing their specs down.
349extern "C" int setupterm(char *term, int filedes, int *errret);
350extern "C" struct term *set_curterm(struct term *termp);
351extern "C" int del_curterm(struct term *termp);
352extern "C" int tigetnum(char *capname);
353#endif
354
355bool checkTerminalEnvironmentForColors() {
356  if (const char *TermStr = std::getenv("TERM")) {
357    return StringSwitch<bool>(TermStr)
358        .Case("ansi", true)
359        .Case("cygwin", true)
360        .Case("linux", true)
361        .StartsWith("screen", true)
362        .StartsWith("xterm", true)
363        .StartsWith("vt100", true)
364        .StartsWith("rxvt", true)
365        .EndsWith("color", true)
366        .Default(false);
367  }
368
369  return false;
370}
371
372static bool terminalHasColors(int fd) {
373#ifdef LLVM_ENABLE_TERMINFO
374  // First, acquire a global lock because these C routines are thread hostile.
375  static std::mutex TermColorMutex;
376  std::lock_guard<std::mutex> G(TermColorMutex);
377
378  struct term *previous_term = set_curterm(nullptr);
379  int errret = 0;
380  if (setupterm(nullptr, fd, &errret) != 0)
381    // Regardless of why, if we can't get terminfo, we shouldn't try to print
382    // colors.
383    return false;
384
385  // Test whether the terminal as set up supports color output. How to do this
386  // isn't entirely obvious. We can use the curses routine 'has_colors' but it
387  // would be nice to avoid a dependency on curses proper when we can make do
388  // with a minimal terminfo parsing library. Also, we don't really care whether
389  // the terminal supports the curses-specific color changing routines, merely
390  // if it will interpret ANSI color escape codes in a reasonable way. Thus, the
391  // strategy here is just to query the baseline colors capability and if it
392  // supports colors at all to assume it will translate the escape codes into
393  // whatever range of colors it does support. We can add more detailed tests
394  // here if users report them as necessary.
395  //
396  // The 'tigetnum' routine returns -2 or -1 on errors, and might return 0 if
397  // the terminfo says that no colors are supported.
398  int colors_ti = tigetnum(const_cast<char *>("colors"));
399  bool HasColors =
400      colors_ti >= 0 ? colors_ti : checkTerminalEnvironmentForColors();
401
402  // Now extract the structure allocated by setupterm and free its memory
403  // through a really silly dance.
404  struct term *termp = set_curterm(previous_term);
405  (void)del_curterm(termp); // Drop any errors here.
406
407  // Return true if we found a color capabilities for the current terminal.
408  return HasColors;
409#else
410  // When the terminfo database is not available, check if the current terminal
411  // is one of terminals that are known to support ANSI color escape codes.
412  return checkTerminalEnvironmentForColors();
413#endif
414}
415
416bool Process::FileDescriptorHasColors(int fd) {
417  // A file descriptor has colors if it is displayed and the terminal has
418  // colors.
419  return FileDescriptorIsDisplayed(fd) && terminalHasColors(fd);
420}
421
422bool Process::StandardOutHasColors() {
423  return FileDescriptorHasColors(STDOUT_FILENO);
424}
425
426bool Process::StandardErrHasColors() {
427  return FileDescriptorHasColors(STDERR_FILENO);
428}
429
430void Process::UseANSIEscapeCodes(bool /*enable*/) {
431  // No effect.
432}
433
434bool Process::ColorNeedsFlush() {
435  // No, we use ANSI escape sequences.
436  return false;
437}
438
439const char *Process::OutputColor(char code, bool bold, bool bg) {
440  return colorcodes[bg ? 1 : 0][bold ? 1 : 0][code & 7];
441}
442
443const char *Process::OutputBold(bool bg) { return "\033[1m"; }
444
445const char *Process::OutputReverse() { return "\033[7m"; }
446
447const char *Process::ResetColor() { return "\033[0m"; }
448
449#if !HAVE_DECL_ARC4RANDOM
450static unsigned GetRandomNumberSeed() {
451  // Attempt to get the initial seed from /dev/urandom, if possible.
452  int urandomFD = open("/dev/urandom", O_RDONLY);
453
454  if (urandomFD != -1) {
455    unsigned seed;
456    // Don't use a buffered read to avoid reading more data
457    // from /dev/urandom than we need.
458    int count = read(urandomFD, (void *)&seed, sizeof(seed));
459
460    close(urandomFD);
461
462    // Return the seed if the read was successful.
463    if (count == sizeof(seed))
464      return seed;
465  }
466
467  // Otherwise, swizzle the current time and the process ID to form a reasonable
468  // seed.
469  const auto Now = std::chrono::high_resolution_clock::now();
470  return hash_combine(Now.time_since_epoch().count(), ::getpid());
471}
472#endif
473
474unsigned llvm::sys::Process::GetRandomNumber() {
475#if HAVE_DECL_ARC4RANDOM
476  return arc4random();
477#else
478  static int x = (static_cast<void>(::srand(GetRandomNumberSeed())), 0);
479  (void)x;
480  return ::rand();
481#endif
482}
483
484[[noreturn]] void Process::ExitNoCleanup(int RetCode) { _Exit(RetCode); }
485