xref: /freebsd/contrib/llvm-project/llvm/lib/Support/Unix/Program.inc (revision 271171e0d97b88ba2a7c3bf750c9672b484c1c13)
1//===- llvm/Support/Unix/Program.cpp -----------------------------*- 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 implements the Unix specific portion of the Program class.
10//
11//===----------------------------------------------------------------------===//
12
13//===----------------------------------------------------------------------===//
14//=== WARNING: Implementation here must contain only generic UNIX code that
15//===          is guaranteed to work on *all* UNIX variants.
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Support/Program.h"
19
20#include "Unix.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/Config/config.h"
23#include "llvm/Support/Compiler.h"
24#include "llvm/Support/Errc.h"
25#include "llvm/Support/FileSystem.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/StringSaver.h"
28#include "llvm/Support/raw_ostream.h"
29#if HAVE_SYS_STAT_H
30#include <sys/stat.h>
31#endif
32#if HAVE_SYS_RESOURCE_H
33#include <sys/resource.h>
34#endif
35#if HAVE_SIGNAL_H
36#include <signal.h>
37#endif
38#if HAVE_FCNTL_H
39#include <fcntl.h>
40#endif
41#if HAVE_UNISTD_H
42#include <unistd.h>
43#endif
44#ifdef HAVE_POSIX_SPAWN
45#include <spawn.h>
46
47#if defined(__APPLE__)
48#include <TargetConditionals.h>
49#endif
50
51#if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
52#define USE_NSGETENVIRON 1
53#else
54#define USE_NSGETENVIRON 0
55#endif
56
57#if !USE_NSGETENVIRON
58  extern char **environ;
59#else
60#include <crt_externs.h> // _NSGetEnviron
61#endif
62#endif
63
64using namespace llvm;
65using namespace sys;
66
67ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
68
69ErrorOr<std::string> sys::findProgramByName(StringRef Name,
70                                            ArrayRef<StringRef> Paths) {
71  assert(!Name.empty() && "Must have a name!");
72  // Use the given path verbatim if it contains any slashes; this matches
73  // the behavior of sh(1) and friends.
74  if (Name.contains('/'))
75    return std::string(Name);
76
77  SmallVector<StringRef, 16> EnvironmentPaths;
78  if (Paths.empty())
79    if (const char *PathEnv = std::getenv("PATH")) {
80      SplitString(PathEnv, EnvironmentPaths, ":");
81      Paths = EnvironmentPaths;
82    }
83
84  for (auto Path : Paths) {
85    if (Path.empty())
86      continue;
87
88    // Check to see if this first directory contains the executable...
89    SmallString<128> FilePath(Path);
90    sys::path::append(FilePath, Name);
91    if (sys::fs::can_execute(FilePath.c_str()))
92      return std::string(FilePath.str());  // Found the executable!
93  }
94  return errc::no_such_file_or_directory;
95}
96
97static bool RedirectIO(Optional<StringRef> Path, int FD, std::string* ErrMsg) {
98  if (!Path) // Noop
99    return false;
100  std::string File;
101  if (Path->empty())
102    // Redirect empty paths to /dev/null
103    File = "/dev/null";
104  else
105    File = std::string(*Path);
106
107  // Open the file
108  int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
109  if (InFD == -1) {
110    MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
111              + (FD == 0 ? "input" : "output"));
112    return true;
113  }
114
115  // Install it as the requested FD
116  if (dup2(InFD, FD) == -1) {
117    MakeErrMsg(ErrMsg, "Cannot dup2");
118    close(InFD);
119    return true;
120  }
121  close(InFD);      // Close the original FD
122  return false;
123}
124
125#ifdef HAVE_POSIX_SPAWN
126static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
127                          posix_spawn_file_actions_t *FileActions) {
128  if (!Path) // Noop
129    return false;
130  const char *File;
131  if (Path->empty())
132    // Redirect empty paths to /dev/null
133    File = "/dev/null";
134  else
135    File = Path->c_str();
136
137  if (int Err = posix_spawn_file_actions_addopen(
138          FileActions, FD, File,
139          FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
140    return MakeErrMsg(ErrMsg, "Cannot posix_spawn_file_actions_addopen", Err);
141  return false;
142}
143#endif
144
145static void TimeOutHandler(int Sig) {
146}
147
148static void SetMemoryLimits(unsigned size) {
149#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
150  struct rlimit r;
151  __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
152
153  // Heap size
154  getrlimit (RLIMIT_DATA, &r);
155  r.rlim_cur = limit;
156  setrlimit (RLIMIT_DATA, &r);
157#ifdef RLIMIT_RSS
158  // Resident set size.
159  getrlimit (RLIMIT_RSS, &r);
160  r.rlim_cur = limit;
161  setrlimit (RLIMIT_RSS, &r);
162#endif
163#endif
164}
165
166static std::vector<const char *>
167toNullTerminatedCStringArray(ArrayRef<StringRef> Strings, StringSaver &Saver) {
168  std::vector<const char *> Result;
169  for (StringRef S : Strings)
170    Result.push_back(Saver.save(S).data());
171  Result.push_back(nullptr);
172  return Result;
173}
174
175static bool Execute(ProcessInfo &PI, StringRef Program,
176                    ArrayRef<StringRef> Args, Optional<ArrayRef<StringRef>> Env,
177                    ArrayRef<Optional<StringRef>> Redirects,
178                    unsigned MemoryLimit, std::string *ErrMsg,
179                    BitVector *AffinityMask) {
180  if (!llvm::sys::fs::exists(Program)) {
181    if (ErrMsg)
182      *ErrMsg = std::string("Executable \"") + Program.str() +
183                std::string("\" doesn't exist!");
184    return false;
185  }
186
187  assert(!AffinityMask && "Starting a process with an affinity mask is "
188                          "currently not supported on Unix!");
189
190  BumpPtrAllocator Allocator;
191  StringSaver Saver(Allocator);
192  std::vector<const char *> ArgVector, EnvVector;
193  const char **Argv = nullptr;
194  const char **Envp = nullptr;
195  ArgVector = toNullTerminatedCStringArray(Args, Saver);
196  Argv = ArgVector.data();
197  if (Env) {
198    EnvVector = toNullTerminatedCStringArray(*Env, Saver);
199    Envp = EnvVector.data();
200  }
201
202  // If this OS has posix_spawn and there is no memory limit being implied, use
203  // posix_spawn.  It is more efficient than fork/exec.
204#ifdef HAVE_POSIX_SPAWN
205  if (MemoryLimit == 0) {
206    posix_spawn_file_actions_t FileActionsStore;
207    posix_spawn_file_actions_t *FileActions = nullptr;
208
209    // If we call posix_spawn_file_actions_addopen we have to make sure the
210    // c strings we pass to it stay alive until the call to posix_spawn,
211    // so we copy any StringRefs into this variable.
212    std::string RedirectsStorage[3];
213
214    if (!Redirects.empty()) {
215      assert(Redirects.size() == 3);
216      std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
217      for (int I = 0; I < 3; ++I) {
218        if (Redirects[I]) {
219          RedirectsStorage[I] = std::string(*Redirects[I]);
220          RedirectsStr[I] = &RedirectsStorage[I];
221        }
222      }
223
224      FileActions = &FileActionsStore;
225      posix_spawn_file_actions_init(FileActions);
226
227      // Redirect stdin/stdout.
228      if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
229          RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
230        return false;
231      if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
232        // Just redirect stderr
233        if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
234          return false;
235      } else {
236        // If stdout and stderr should go to the same place, redirect stderr
237        // to the FD already open for stdout.
238        if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
239          return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
240      }
241    }
242
243    if (!Envp)
244#if !USE_NSGETENVIRON
245      Envp = const_cast<const char **>(environ);
246#else
247      // environ is missing in dylibs.
248      Envp = const_cast<const char **>(*_NSGetEnviron());
249#endif
250
251    constexpr int maxRetries = 8;
252    int retries = 0;
253    pid_t PID;
254    int Err;
255    do {
256      PID = 0; // Make Valgrind happy.
257      Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
258                        /*attrp*/ nullptr, const_cast<char **>(Argv),
259                        const_cast<char **>(Envp));
260    } while (Err == EINTR && ++retries < maxRetries);
261
262    if (FileActions)
263      posix_spawn_file_actions_destroy(FileActions);
264
265    if (Err)
266     return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
267
268    PI.Pid = PID;
269    PI.Process = PID;
270
271    return true;
272  }
273#endif
274
275  // Create a child process.
276  int child = fork();
277  switch (child) {
278    // An error occurred:  Return to the caller.
279    case -1:
280      MakeErrMsg(ErrMsg, "Couldn't fork");
281      return false;
282
283    // Child process: Execute the program.
284    case 0: {
285      // Redirect file descriptors...
286      if (!Redirects.empty()) {
287        // Redirect stdin
288        if (RedirectIO(Redirects[0], 0, ErrMsg)) { return false; }
289        // Redirect stdout
290        if (RedirectIO(Redirects[1], 1, ErrMsg)) { return false; }
291        if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
292          // If stdout and stderr should go to the same place, redirect stderr
293          // to the FD already open for stdout.
294          if (-1 == dup2(1,2)) {
295            MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
296            return false;
297          }
298        } else {
299          // Just redirect stderr
300          if (RedirectIO(Redirects[2], 2, ErrMsg)) { return false; }
301        }
302      }
303
304      // Set memory limits
305      if (MemoryLimit!=0) {
306        SetMemoryLimits(MemoryLimit);
307      }
308
309      // Execute!
310      std::string PathStr = std::string(Program);
311      if (Envp != nullptr)
312        execve(PathStr.c_str(), const_cast<char **>(Argv),
313               const_cast<char **>(Envp));
314      else
315        execv(PathStr.c_str(), const_cast<char **>(Argv));
316      // If the execve() failed, we should exit. Follow Unix protocol and
317      // return 127 if the executable was not found, and 126 otherwise.
318      // Use _exit rather than exit so that atexit functions and static
319      // object destructors cloned from the parent process aren't
320      // redundantly run, and so that any data buffered in stdio buffers
321      // cloned from the parent aren't redundantly written out.
322      _exit(errno == ENOENT ? 127 : 126);
323    }
324
325    // Parent process: Break out of the switch to do our processing.
326    default:
327      break;
328  }
329
330  PI.Pid = child;
331  PI.Process = child;
332
333  return true;
334}
335
336namespace llvm {
337namespace sys {
338
339#ifndef _AIX
340using ::wait4;
341#else
342static pid_t (wait4)(pid_t pid, int *status, int options, struct rusage *usage);
343#endif
344
345} // namespace sys
346} // namespace llvm
347
348#ifdef _AIX
349#ifndef _ALL_SOURCE
350extern "C" pid_t (wait4)(pid_t pid, int *status, int options,
351                         struct rusage *usage);
352#endif
353pid_t (llvm::sys::wait4)(pid_t pid, int *status, int options,
354                         struct rusage *usage) {
355  assert(pid > 0 && "Only expecting to handle actual PID values!");
356  assert((options & ~WNOHANG) == 0 && "Expecting WNOHANG at most!");
357  assert(usage && "Expecting usage collection!");
358
359  // AIX wait4 does not work well with WNOHANG.
360  if (!(options & WNOHANG))
361    return ::wait4(pid, status, options, usage);
362
363  // For WNOHANG, we use waitid (which supports WNOWAIT) until the child process
364  // has terminated.
365  siginfo_t WaitIdInfo;
366  WaitIdInfo.si_pid = 0;
367  int WaitIdRetVal =
368      waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
369
370  if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
371    return WaitIdRetVal;
372
373  assert(WaitIdInfo.si_pid == pid);
374
375  // The child has already terminated, so a blocking wait on it is okay in the
376  // absence of indiscriminate `wait` calls from the current process (which
377  // would cause the call here to fail with ECHILD).
378  return ::wait4(pid, status, options & ~WNOHANG, usage);
379}
380#endif
381
382ProcessInfo llvm::sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
383                            bool WaitUntilTerminates, std::string *ErrMsg,
384                            Optional<ProcessStatistics> *ProcStat) {
385  struct sigaction Act, Old;
386  assert(PI.Pid && "invalid pid to wait on, process not started?");
387
388  int WaitPidOptions = 0;
389  pid_t ChildPid = PI.Pid;
390  if (WaitUntilTerminates) {
391    SecondsToWait = 0;
392  } else if (SecondsToWait) {
393    // Install a timeout handler.  The handler itself does nothing, but the
394    // simple fact of having a handler at all causes the wait below to return
395    // with EINTR, unlike if we used SIG_IGN.
396    memset(&Act, 0, sizeof(Act));
397    Act.sa_handler = TimeOutHandler;
398    sigemptyset(&Act.sa_mask);
399    sigaction(SIGALRM, &Act, &Old);
400    // FIXME The alarm signal may be delivered to another thread.
401    alarm(SecondsToWait);
402  } else if (SecondsToWait == 0)
403    WaitPidOptions = WNOHANG;
404
405  // Parent process: Wait for the child process to terminate.
406  int status;
407  ProcessInfo WaitResult;
408  rusage Info;
409  if (ProcStat)
410    ProcStat->reset();
411
412  do {
413    WaitResult.Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &Info);
414  } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
415
416  if (WaitResult.Pid != PI.Pid) {
417    if (WaitResult.Pid == 0) {
418      // Non-blocking wait.
419      return WaitResult;
420    } else {
421      if (SecondsToWait && errno == EINTR) {
422        // Kill the child.
423        kill(PI.Pid, SIGKILL);
424
425        // Turn off the alarm and restore the signal handler
426        alarm(0);
427        sigaction(SIGALRM, &Old, nullptr);
428
429        // Wait for child to die
430        // FIXME This could grab some other child process out from another
431        // waiting thread and then leave a zombie anyway.
432        if (wait(&status) != ChildPid)
433          MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
434        else
435          MakeErrMsg(ErrMsg, "Child timed out", 0);
436
437        WaitResult.ReturnCode = -2; // Timeout detected
438        return WaitResult;
439      } else if (errno != EINTR) {
440        MakeErrMsg(ErrMsg, "Error waiting for child process");
441        WaitResult.ReturnCode = -1;
442        return WaitResult;
443      }
444    }
445  }
446
447  // We exited normally without timeout, so turn off the timer.
448  if (SecondsToWait && !WaitUntilTerminates) {
449    alarm(0);
450    sigaction(SIGALRM, &Old, nullptr);
451  }
452
453  if (ProcStat) {
454    std::chrono::microseconds UserT = toDuration(Info.ru_utime);
455    std::chrono::microseconds KernelT = toDuration(Info.ru_stime);
456    uint64_t PeakMemory = 0;
457#ifndef __HAIKU__
458    PeakMemory = static_cast<uint64_t>(Info.ru_maxrss);
459#endif
460    *ProcStat = ProcessStatistics{UserT + KernelT, UserT, PeakMemory};
461  }
462
463  // Return the proper exit status. Detect error conditions
464  // so we can return -1 for them and set ErrMsg informatively.
465  int result = 0;
466  if (WIFEXITED(status)) {
467    result = WEXITSTATUS(status);
468    WaitResult.ReturnCode = result;
469
470    if (result == 127) {
471      if (ErrMsg)
472        *ErrMsg = llvm::sys::StrError(ENOENT);
473      WaitResult.ReturnCode = -1;
474      return WaitResult;
475    }
476    if (result == 126) {
477      if (ErrMsg)
478        *ErrMsg = "Program could not be executed";
479      WaitResult.ReturnCode = -1;
480      return WaitResult;
481    }
482  } else if (WIFSIGNALED(status)) {
483    if (ErrMsg) {
484      *ErrMsg = strsignal(WTERMSIG(status));
485#ifdef WCOREDUMP
486      if (WCOREDUMP(status))
487        *ErrMsg += " (core dumped)";
488#endif
489    }
490    // Return a special value to indicate that the process received an unhandled
491    // signal during execution as opposed to failing to execute.
492    WaitResult.ReturnCode = -2;
493  }
494  return WaitResult;
495}
496
497std::error_code llvm::sys::ChangeStdinMode(fs::OpenFlags Flags){
498  if (!(Flags & fs::OF_Text))
499    return ChangeStdinToBinary();
500  return std::error_code();
501}
502
503std::error_code llvm::sys::ChangeStdoutMode(fs::OpenFlags Flags){
504  if (!(Flags & fs::OF_Text))
505    return ChangeStdoutToBinary();
506  return std::error_code();
507}
508
509std::error_code llvm::sys::ChangeStdinToBinary() {
510  // Do nothing, as Unix doesn't differentiate between text and binary.
511  return std::error_code();
512}
513
514std::error_code llvm::sys::ChangeStdoutToBinary() {
515  // Do nothing, as Unix doesn't differentiate between text and binary.
516  return std::error_code();
517}
518
519std::error_code
520llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
521                                 WindowsEncodingMethod Encoding /*unused*/) {
522  std::error_code EC;
523  llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::OF_TextWithCRLF);
524
525  if (EC)
526    return EC;
527
528  OS << Contents;
529
530  if (OS.has_error())
531    return make_error_code(errc::io_error);
532
533  return EC;
534}
535
536bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program,
537                                                  ArrayRef<StringRef> Args) {
538  static long ArgMax = sysconf(_SC_ARG_MAX);
539  // POSIX requires that _POSIX_ARG_MAX is 4096, which is the lowest possible
540  // value for ARG_MAX on a POSIX compliant system.
541  static long ArgMin = _POSIX_ARG_MAX;
542
543  // This the same baseline used by xargs.
544  long EffectiveArgMax = 128 * 1024;
545
546  if (EffectiveArgMax > ArgMax)
547    EffectiveArgMax = ArgMax;
548  else if (EffectiveArgMax < ArgMin)
549    EffectiveArgMax = ArgMin;
550
551  // System says no practical limit.
552  if (ArgMax == -1)
553    return true;
554
555  // Conservatively account for space required by environment variables.
556  long HalfArgMax = EffectiveArgMax / 2;
557
558  size_t ArgLength = Program.size() + 1;
559  for (StringRef Arg : Args) {
560    // Ensure that we do not exceed the MAX_ARG_STRLEN constant on Linux, which
561    // does not have a constant unlike what the man pages would have you
562    // believe. Since this limit is pretty high, perform the check
563    // unconditionally rather than trying to be aggressive and limiting it to
564    // Linux only.
565    if (Arg.size() >= (32 * 4096))
566      return false;
567
568    ArgLength += Arg.size() + 1;
569    if (ArgLength > size_t(HalfArgMax)) {
570      return false;
571    }
572  }
573
574  return true;
575}
576