1 //===- llvm/Support/Unix/Program.inc ----------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the Unix specific portion of the Program class.
11 //===----------------------------------------------------------------------===//
13 //===----------------------------------------------------------------------===//
14 //=== WARNING: Implementation here must contain only generic UNIX
15 //=== code that is guaranteed to work on *all* UNIX variants.
16 //===----------------------------------------------------------------------===//
18 #include "llvm/Support/Program.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/Config/config.h"
23 #include "llvm/Support/AutoConvert.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/Errc.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Path.h"
28 #include "llvm/Support/StringSaver.h"
29 #include "llvm/Support/SystemZ/zOSSupport.h"
30 #include "llvm/Support/raw_ostream.h"
34 #if HAVE_SYS_RESOURCE_H
35 #include <sys/resource.h>
46 #ifdef HAVE_POSIX_SPAWN
49 #if defined(__APPLE__)
50 #include <TargetConditionals.h>
53 #if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
54 #define USE_NSGETENVIRON 1
56 #define USE_NSGETENVIRON 0
60 extern char **environ;
62 #include <crt_externs.h> // _NSGetEnviron
69 ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
71 ErrorOr<std::string> sys::findProgramByName(StringRef Name,
72 ArrayRef<StringRef> Paths) {
73 assert(!Name.empty() && "Must have a name!");
74 // Use the given path verbatim if it contains any slashes; this matches
75 // the behavior of sh(1) and friends.
76 if (Name.contains('/'))
77 return std::string(Name);
79 SmallVector<StringRef, 16> EnvironmentPaths;
81 if (const char *PathEnv = std::getenv("PATH")) {
82 SplitString(PathEnv, EnvironmentPaths, ":");
83 Paths = EnvironmentPaths;
86 for (auto Path : Paths) {
90 // Check to see if this first directory contains the executable...
91 SmallString<128> FilePath(Path);
92 sys::path::append(FilePath, Name);
93 if (sys::fs::can_execute(FilePath.c_str()))
94 return std::string(FilePath); // Found the executable!
96 return errc::no_such_file_or_directory;
99 static bool RedirectIO(std::optional<StringRef> Path, int FD, std::string *ErrMsg) {
104 // Redirect empty paths to /dev/null
107 File = std::string(*Path);
110 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666);
112 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for " +
113 (FD == 0 ? "input" : "output"));
117 // Install it as the requested FD
118 if (dup2(InFD, FD) == -1) {
119 MakeErrMsg(ErrMsg, "Cannot dup2");
123 close(InFD); // Close the original FD
127 #ifdef HAVE_POSIX_SPAWN
128 static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
129 posix_spawn_file_actions_t *FileActions) {
134 // Redirect empty paths to /dev/null
137 File = Path->c_str();
139 if (int Err = posix_spawn_file_actions_addopen(
140 FileActions, FD, File, FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
141 return MakeErrMsg(ErrMsg, "Cannot posix_spawn_file_actions_addopen", Err);
146 static void TimeOutHandler(int Sig) {}
148 static void SetMemoryLimits(unsigned size) {
149 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
151 __typeof__(r.rlim_cur) limit = (__typeof__(r.rlim_cur))(size)*1048576;
154 getrlimit(RLIMIT_DATA, &r);
156 setrlimit(RLIMIT_DATA, &r);
158 // Resident set size.
159 getrlimit(RLIMIT_RSS, &r);
161 setrlimit(RLIMIT_RSS, &r);
166 static std::vector<const char *>
167 toNullTerminatedCStringArray(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);
175 static bool Execute(ProcessInfo &PI, StringRef Program,
176 ArrayRef<StringRef> Args,
177 std::optional<ArrayRef<StringRef>> Env,
178 ArrayRef<std::optional<StringRef>> Redirects,
179 unsigned MemoryLimit, std::string *ErrMsg,
180 BitVector *AffinityMask, bool DetachProcess) {
181 if (!llvm::sys::fs::exists(Program)) {
183 *ErrMsg = std::string("Executable \"") + Program.str() +
184 std::string("\" doesn't exist!");
188 assert(!AffinityMask && "Starting a process with an affinity mask is "
189 "currently not supported on Unix!");
191 BumpPtrAllocator Allocator;
192 StringSaver Saver(Allocator);
193 std::vector<const char *> ArgVector, EnvVector;
194 const char **Argv = nullptr;
195 const char **Envp = nullptr;
196 ArgVector = toNullTerminatedCStringArray(Args, Saver);
197 Argv = ArgVector.data();
199 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
200 Envp = EnvVector.data();
203 // If this OS has posix_spawn and there is no memory limit being implied, use
204 // posix_spawn. It is more efficient than fork/exec.
205 #ifdef HAVE_POSIX_SPAWN
206 // Cannot use posix_spawn if you would like to detach the process
207 if (MemoryLimit == 0 && !DetachProcess) {
208 posix_spawn_file_actions_t FileActionsStore;
209 posix_spawn_file_actions_t *FileActions = nullptr;
211 // If we call posix_spawn_file_actions_addopen we have to make sure the
212 // c strings we pass to it stay alive until the call to posix_spawn,
213 // so we copy any StringRefs into this variable.
214 std::string RedirectsStorage[3];
216 if (!Redirects.empty()) {
217 assert(Redirects.size() == 3);
218 std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
219 for (int I = 0; I < 3; ++I) {
221 RedirectsStorage[I] = std::string(*Redirects[I]);
222 RedirectsStr[I] = &RedirectsStorage[I];
226 FileActions = &FileActionsStore;
227 posix_spawn_file_actions_init(FileActions);
229 // Redirect stdin/stdout.
230 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
231 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
233 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
234 // Just redirect stderr
235 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
238 // If stdout and stderr should go to the same place, redirect stderr
239 // to the FD already open for stdout.
240 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
241 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
246 #if !USE_NSGETENVIRON
247 Envp = const_cast<const char **>(environ);
249 // environ is missing in dylibs.
250 Envp = const_cast<const char **>(*_NSGetEnviron());
253 constexpr int maxRetries = 8;
258 PID = 0; // Make Valgrind happy.
259 Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
260 /*attrp*/ nullptr, const_cast<char **>(Argv),
261 const_cast<char **>(Envp));
262 } while (Err == EINTR && ++retries < maxRetries);
265 posix_spawn_file_actions_destroy(FileActions);
268 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
275 #endif // HAVE_POSIX_SPAWN
277 // Create a child process.
280 // An error occurred: Return to the caller.
282 MakeErrMsg(ErrMsg, "Couldn't fork");
285 // Child process: Execute the program.
287 // Redirect file descriptors...
288 if (!Redirects.empty()) {
290 if (RedirectIO(Redirects[0], 0, ErrMsg)) {
294 if (RedirectIO(Redirects[1], 1, ErrMsg)) {
297 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
298 // If stdout and stderr should go to the same place, redirect stderr
299 // to the FD already open for stdout.
300 if (-1 == dup2(1, 2)) {
301 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
305 // Just redirect stderr
306 if (RedirectIO(Redirects[2], 2, ErrMsg)) {
313 // Detach from controlling terminal
314 if (::setsid() == -1) {
315 MakeErrMsg(ErrMsg, "Could not detach process, ::setsid failed");
321 if (MemoryLimit != 0) {
322 SetMemoryLimits(MemoryLimit);
326 std::string PathStr = std::string(Program);
328 execve(PathStr.c_str(), const_cast<char **>(Argv),
329 const_cast<char **>(Envp));
331 execv(PathStr.c_str(), const_cast<char **>(Argv));
332 // If the execve() failed, we should exit. Follow Unix protocol and
333 // return 127 if the executable was not found, and 126 otherwise.
334 // Use _exit rather than exit so that atexit functions and static
335 // object destructors cloned from the parent process aren't
336 // redundantly run, and so that any data buffered in stdio buffers
337 // cloned from the parent aren't redundantly written out.
338 _exit(errno == ENOENT ? 127 : 126);
341 // Parent process: Break out of the switch to do our processing.
356 static pid_t(wait4)(pid_t pid, int *status, int options, struct rusage *usage);
357 #elif !defined(__Fuchsia__)
366 extern "C" pid_t(wait4)(pid_t pid, int *status, int options,
367 struct rusage *usage);
369 pid_t(llvm::sys::wait4)(pid_t pid, int *status, int options,
370 struct rusage *usage) {
371 assert(pid > 0 && "Only expecting to handle actual PID values!");
372 assert((options & ~WNOHANG) == 0 && "Expecting WNOHANG at most!");
373 assert(usage && "Expecting usage collection!");
375 // AIX wait4 does not work well with WNOHANG.
376 if (!(options & WNOHANG))
377 return ::wait4(pid, status, options, usage);
379 // For WNOHANG, we use waitid (which supports WNOWAIT) until the child process
381 siginfo_t WaitIdInfo;
382 WaitIdInfo.si_pid = 0;
384 waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
386 if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
389 assert(WaitIdInfo.si_pid == pid);
391 // The child has already terminated, so a blocking wait on it is okay in the
392 // absence of indiscriminate `wait` calls from the current process (which
393 // would cause the call here to fail with ECHILD).
394 return ::wait4(pid, status, options & ~WNOHANG, usage);
398 ProcessInfo llvm::sys::Wait(const ProcessInfo &PI,
399 std::optional<unsigned> SecondsToWait,
401 std::optional<ProcessStatistics> *ProcStat,
403 struct sigaction Act, Old;
404 assert(PI.Pid && "invalid pid to wait on, process not started?");
406 int WaitPidOptions = 0;
407 pid_t ChildPid = PI.Pid;
408 bool WaitUntilTerminates = false;
409 if (!SecondsToWait) {
410 WaitUntilTerminates = true;
412 if (*SecondsToWait == 0)
413 WaitPidOptions = WNOHANG;
415 // Install a timeout handler. The handler itself does nothing, but the
416 // simple fact of having a handler at all causes the wait below to return
417 // with EINTR, unlike if we used SIG_IGN.
418 memset(&Act, 0, sizeof(Act));
419 Act.sa_handler = TimeOutHandler;
420 sigemptyset(&Act.sa_mask);
421 sigaction(SIGALRM, &Act, &Old);
422 // FIXME The alarm signal may be delivered to another thread.
423 alarm(*SecondsToWait);
426 // Parent process: Wait for the child process to terminate.
428 ProcessInfo WaitResult;
435 WaitResult.Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &Info);
436 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
439 if (WaitResult.Pid != PI.Pid) {
440 if (WaitResult.Pid == 0) {
441 // Non-blocking wait.
444 if (SecondsToWait && errno == EINTR && !Polling) {
446 kill(PI.Pid, SIGKILL);
448 // Turn off the alarm and restore the signal handler
450 sigaction(SIGALRM, &Old, nullptr);
452 // Wait for child to die
453 // FIXME This could grab some other child process out from another
454 // waiting thread and then leave a zombie anyway.
455 if (wait(&status) != ChildPid)
456 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
458 MakeErrMsg(ErrMsg, "Child timed out", 0);
460 WaitResult.ReturnCode = -2; // Timeout detected
462 } else if (errno != EINTR) {
463 MakeErrMsg(ErrMsg, "Error waiting for child process");
464 WaitResult.ReturnCode = -1;
470 // We exited normally without timeout, so turn off the timer.
471 if (SecondsToWait && !WaitUntilTerminates) {
473 sigaction(SIGALRM, &Old, nullptr);
478 std::chrono::microseconds UserT = toDuration(Info.ru_utime);
479 std::chrono::microseconds KernelT = toDuration(Info.ru_stime);
480 uint64_t PeakMemory = 0;
481 #if !defined(__HAIKU__) && !defined(__MVS__)
482 PeakMemory = static_cast<uint64_t>(Info.ru_maxrss);
484 *ProcStat = ProcessStatistics{UserT + KernelT, UserT, PeakMemory};
488 // Return the proper exit status. Detect error conditions
489 // so we can return -1 for them and set ErrMsg informatively.
491 if (WIFEXITED(status)) {
492 result = WEXITSTATUS(status);
493 WaitResult.ReturnCode = result;
497 *ErrMsg = llvm::sys::StrError(ENOENT);
498 WaitResult.ReturnCode = -1;
503 *ErrMsg = "Program could not be executed";
504 WaitResult.ReturnCode = -1;
507 } else if (WIFSIGNALED(status)) {
509 *ErrMsg = strsignal(WTERMSIG(status));
511 if (WCOREDUMP(status))
512 *ErrMsg += " (core dumped)";
515 // Return a special value to indicate that the process received an unhandled
516 // signal during execution as opposed to failing to execute.
517 WaitResult.ReturnCode = -2;
522 std::error_code llvm::sys::ChangeStdinMode(fs::OpenFlags Flags) {
523 if (!(Flags & fs::OF_Text))
524 return ChangeStdinToBinary();
525 return std::error_code();
528 std::error_code llvm::sys::ChangeStdoutMode(fs::OpenFlags Flags) {
529 if (!(Flags & fs::OF_Text))
530 return ChangeStdoutToBinary();
531 return std::error_code();
534 std::error_code llvm::sys::ChangeStdinToBinary() {
536 return disablezOSAutoConversion(STDIN_FILENO);
538 // Do nothing, as Unix doesn't differentiate between text and binary.
539 return std::error_code();
543 std::error_code llvm::sys::ChangeStdoutToBinary() {
544 // Do nothing, as Unix doesn't differentiate between text and binary.
545 return std::error_code();
549 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
550 WindowsEncodingMethod Encoding /*unused*/) {
552 llvm::raw_fd_ostream OS(FileName, EC,
553 llvm::sys::fs::OpenFlags::OF_TextWithCRLF);
561 return make_error_code(errc::io_error);
566 bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program,
567 ArrayRef<StringRef> Args) {
568 static long ArgMax = sysconf(_SC_ARG_MAX);
569 // POSIX requires that _POSIX_ARG_MAX is 4096, which is the lowest possible
570 // value for ARG_MAX on a POSIX compliant system.
571 static long ArgMin = _POSIX_ARG_MAX;
573 // This the same baseline used by xargs.
574 long EffectiveArgMax = 128 * 1024;
576 if (EffectiveArgMax > ArgMax)
577 EffectiveArgMax = ArgMax;
578 else if (EffectiveArgMax < ArgMin)
579 EffectiveArgMax = ArgMin;
581 // System says no practical limit.
585 // Conservatively account for space required by environment variables.
586 long HalfArgMax = EffectiveArgMax / 2;
588 size_t ArgLength = Program.size() + 1;
589 for (StringRef Arg : Args) {
590 // Ensure that we do not exceed the MAX_ARG_STRLEN constant on Linux, which
591 // does not have a constant unlike what the man pages would have you
592 // believe. Since this limit is pretty high, perform the check
593 // unconditionally rather than trying to be aggressive and limiting it to
595 if (Arg.size() >= (32 * 4096))
598 ArgLength += Arg.size() + 1;
599 if (ArgLength > size_t(HalfArgMax)) {