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/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"
32 #if HAVE_SYS_RESOURCE_H
33 #include <sys/resource.h>
44 #ifdef HAVE_POSIX_SPAWN
47 #if defined(__APPLE__)
48 #include <TargetConditionals.h>
51 #if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
52 #define USE_NSGETENVIRON 1
54 #define USE_NSGETENVIRON 0
58 extern char **environ;
60 #include <crt_externs.h> // _NSGetEnviron
67 ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
69 ErrorOr<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);
77 SmallVector<StringRef, 16> EnvironmentPaths;
79 if (const char *PathEnv = std::getenv("PATH")) {
80 SplitString(PathEnv, EnvironmentPaths, ":");
81 Paths = EnvironmentPaths;
84 for (auto Path : Paths) {
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!
94 return errc::no_such_file_or_directory;
97 static bool RedirectIO(std::optional<StringRef> Path, int FD, std::string *ErrMsg) {
102 // Redirect empty paths to /dev/null
105 File = std::string(*Path);
108 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666);
110 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for " +
111 (FD == 0 ? "input" : "output"));
115 // Install it as the requested FD
116 if (dup2(InFD, FD) == -1) {
117 MakeErrMsg(ErrMsg, "Cannot dup2");
121 close(InFD); // Close the original FD
125 #ifdef HAVE_POSIX_SPAWN
126 static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
127 posix_spawn_file_actions_t *FileActions) {
132 // Redirect empty paths to /dev/null
135 File = Path->c_str();
137 if (int Err = posix_spawn_file_actions_addopen(
138 FileActions, FD, File, FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
139 return MakeErrMsg(ErrMsg, "Cannot posix_spawn_file_actions_addopen", Err);
144 static void TimeOutHandler(int Sig) {}
146 static void SetMemoryLimits(unsigned size) {
147 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
149 __typeof__(r.rlim_cur) limit = (__typeof__(r.rlim_cur))(size)*1048576;
152 getrlimit(RLIMIT_DATA, &r);
154 setrlimit(RLIMIT_DATA, &r);
156 // Resident set size.
157 getrlimit(RLIMIT_RSS, &r);
159 setrlimit(RLIMIT_RSS, &r);
164 static std::vector<const char *>
165 toNullTerminatedCStringArray(ArrayRef<StringRef> Strings, StringSaver &Saver) {
166 std::vector<const char *> Result;
167 for (StringRef S : Strings)
168 Result.push_back(Saver.save(S).data());
169 Result.push_back(nullptr);
173 static bool Execute(ProcessInfo &PI, StringRef Program,
174 ArrayRef<StringRef> Args, std::optional<ArrayRef<StringRef>> Env,
175 ArrayRef<std::optional<StringRef>> Redirects,
176 unsigned MemoryLimit, std::string *ErrMsg,
177 BitVector *AffinityMask) {
178 if (!llvm::sys::fs::exists(Program)) {
180 *ErrMsg = std::string("Executable \"") + Program.str() +
181 std::string("\" doesn't exist!");
185 assert(!AffinityMask && "Starting a process with an affinity mask is "
186 "currently not supported on Unix!");
188 BumpPtrAllocator Allocator;
189 StringSaver Saver(Allocator);
190 std::vector<const char *> ArgVector, EnvVector;
191 const char **Argv = nullptr;
192 const char **Envp = nullptr;
193 ArgVector = toNullTerminatedCStringArray(Args, Saver);
194 Argv = ArgVector.data();
196 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
197 Envp = EnvVector.data();
200 // If this OS has posix_spawn and there is no memory limit being implied, use
201 // posix_spawn. It is more efficient than fork/exec.
202 #ifdef HAVE_POSIX_SPAWN
203 if (MemoryLimit == 0) {
204 posix_spawn_file_actions_t FileActionsStore;
205 posix_spawn_file_actions_t *FileActions = nullptr;
207 // If we call posix_spawn_file_actions_addopen we have to make sure the
208 // c strings we pass to it stay alive until the call to posix_spawn,
209 // so we copy any StringRefs into this variable.
210 std::string RedirectsStorage[3];
212 if (!Redirects.empty()) {
213 assert(Redirects.size() == 3);
214 std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
215 for (int I = 0; I < 3; ++I) {
217 RedirectsStorage[I] = std::string(*Redirects[I]);
218 RedirectsStr[I] = &RedirectsStorage[I];
222 FileActions = &FileActionsStore;
223 posix_spawn_file_actions_init(FileActions);
225 // Redirect stdin/stdout.
226 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
227 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
229 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
230 // Just redirect stderr
231 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
234 // If stdout and stderr should go to the same place, redirect stderr
235 // to the FD already open for stdout.
236 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
237 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
242 #if !USE_NSGETENVIRON
243 Envp = const_cast<const char **>(environ);
245 // environ is missing in dylibs.
246 Envp = const_cast<const char **>(*_NSGetEnviron());
249 constexpr int maxRetries = 8;
254 PID = 0; // Make Valgrind happy.
255 Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
256 /*attrp*/ nullptr, const_cast<char **>(Argv),
257 const_cast<char **>(Envp));
258 } while (Err == EINTR && ++retries < maxRetries);
261 posix_spawn_file_actions_destroy(FileActions);
264 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
273 // Create a child process.
276 // An error occurred: Return to the caller.
278 MakeErrMsg(ErrMsg, "Couldn't fork");
281 // Child process: Execute the program.
283 // Redirect file descriptors...
284 if (!Redirects.empty()) {
286 if (RedirectIO(Redirects[0], 0, ErrMsg)) {
290 if (RedirectIO(Redirects[1], 1, ErrMsg)) {
293 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
294 // If stdout and stderr should go to the same place, redirect stderr
295 // to the FD already open for stdout.
296 if (-1 == dup2(1, 2)) {
297 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
301 // Just redirect stderr
302 if (RedirectIO(Redirects[2], 2, ErrMsg)) {
309 if (MemoryLimit != 0) {
310 SetMemoryLimits(MemoryLimit);
314 std::string PathStr = std::string(Program);
316 execve(PathStr.c_str(), const_cast<char **>(Argv),
317 const_cast<char **>(Envp));
319 execv(PathStr.c_str(), const_cast<char **>(Argv));
320 // If the execve() failed, we should exit. Follow Unix protocol and
321 // return 127 if the executable was not found, and 126 otherwise.
322 // Use _exit rather than exit so that atexit functions and static
323 // object destructors cloned from the parent process aren't
324 // redundantly run, and so that any data buffered in stdio buffers
325 // cloned from the parent aren't redundantly written out.
326 _exit(errno == ENOENT ? 127 : 126);
329 // Parent process: Break out of the switch to do our processing.
344 static pid_t(wait4)(pid_t pid, int *status, int options, struct rusage *usage);
345 #elif !defined(__Fuchsia__)
354 extern "C" pid_t(wait4)(pid_t pid, int *status, int options,
355 struct rusage *usage);
357 pid_t(llvm::sys::wait4)(pid_t pid, int *status, int options,
358 struct rusage *usage) {
359 assert(pid > 0 && "Only expecting to handle actual PID values!");
360 assert((options & ~WNOHANG) == 0 && "Expecting WNOHANG at most!");
361 assert(usage && "Expecting usage collection!");
363 // AIX wait4 does not work well with WNOHANG.
364 if (!(options & WNOHANG))
365 return ::wait4(pid, status, options, usage);
367 // For WNOHANG, we use waitid (which supports WNOWAIT) until the child process
369 siginfo_t WaitIdInfo;
370 WaitIdInfo.si_pid = 0;
372 waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
374 if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
377 assert(WaitIdInfo.si_pid == pid);
379 // The child has already terminated, so a blocking wait on it is okay in the
380 // absence of indiscriminate `wait` calls from the current process (which
381 // would cause the call here to fail with ECHILD).
382 return ::wait4(pid, status, options & ~WNOHANG, usage);
386 ProcessInfo llvm::sys::Wait(const ProcessInfo &PI,
387 std::optional<unsigned> SecondsToWait,
389 std::optional<ProcessStatistics> *ProcStat,
391 struct sigaction Act, Old;
392 assert(PI.Pid && "invalid pid to wait on, process not started?");
394 int WaitPidOptions = 0;
395 pid_t ChildPid = PI.Pid;
396 bool WaitUntilTerminates = false;
397 if (!SecondsToWait) {
398 WaitUntilTerminates = true;
400 if (*SecondsToWait == 0)
401 WaitPidOptions = WNOHANG;
403 // Install a timeout handler. The handler itself does nothing, but the
404 // simple fact of having a handler at all causes the wait below to return
405 // with EINTR, unlike if we used SIG_IGN.
406 memset(&Act, 0, sizeof(Act));
407 Act.sa_handler = TimeOutHandler;
408 sigemptyset(&Act.sa_mask);
409 sigaction(SIGALRM, &Act, &Old);
410 // FIXME The alarm signal may be delivered to another thread.
411 alarm(*SecondsToWait);
414 // Parent process: Wait for the child process to terminate.
416 ProcessInfo WaitResult;
423 WaitResult.Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &Info);
424 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
427 if (WaitResult.Pid != PI.Pid) {
428 if (WaitResult.Pid == 0) {
429 // Non-blocking wait.
432 if (SecondsToWait && errno == EINTR && !Polling) {
434 kill(PI.Pid, SIGKILL);
436 // Turn off the alarm and restore the signal handler
438 sigaction(SIGALRM, &Old, nullptr);
440 // Wait for child to die
441 // FIXME This could grab some other child process out from another
442 // waiting thread and then leave a zombie anyway.
443 if (wait(&status) != ChildPid)
444 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
446 MakeErrMsg(ErrMsg, "Child timed out", 0);
448 WaitResult.ReturnCode = -2; // Timeout detected
450 } else if (errno != EINTR) {
451 MakeErrMsg(ErrMsg, "Error waiting for child process");
452 WaitResult.ReturnCode = -1;
458 // We exited normally without timeout, so turn off the timer.
459 if (SecondsToWait && !WaitUntilTerminates) {
461 sigaction(SIGALRM, &Old, nullptr);
466 std::chrono::microseconds UserT = toDuration(Info.ru_utime);
467 std::chrono::microseconds KernelT = toDuration(Info.ru_stime);
468 uint64_t PeakMemory = 0;
470 PeakMemory = static_cast<uint64_t>(Info.ru_maxrss);
472 *ProcStat = ProcessStatistics{UserT + KernelT, UserT, PeakMemory};
476 // Return the proper exit status. Detect error conditions
477 // so we can return -1 for them and set ErrMsg informatively.
479 if (WIFEXITED(status)) {
480 result = WEXITSTATUS(status);
481 WaitResult.ReturnCode = result;
485 *ErrMsg = llvm::sys::StrError(ENOENT);
486 WaitResult.ReturnCode = -1;
491 *ErrMsg = "Program could not be executed";
492 WaitResult.ReturnCode = -1;
495 } else if (WIFSIGNALED(status)) {
497 *ErrMsg = strsignal(WTERMSIG(status));
499 if (WCOREDUMP(status))
500 *ErrMsg += " (core dumped)";
503 // Return a special value to indicate that the process received an unhandled
504 // signal during execution as opposed to failing to execute.
505 WaitResult.ReturnCode = -2;
510 std::error_code llvm::sys::ChangeStdinMode(fs::OpenFlags Flags) {
511 if (!(Flags & fs::OF_Text))
512 return ChangeStdinToBinary();
513 return std::error_code();
516 std::error_code llvm::sys::ChangeStdoutMode(fs::OpenFlags Flags) {
517 if (!(Flags & fs::OF_Text))
518 return ChangeStdoutToBinary();
519 return std::error_code();
522 std::error_code llvm::sys::ChangeStdinToBinary() {
523 // Do nothing, as Unix doesn't differentiate between text and binary.
524 return std::error_code();
527 std::error_code llvm::sys::ChangeStdoutToBinary() {
528 // Do nothing, as Unix doesn't differentiate between text and binary.
529 return std::error_code();
533 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
534 WindowsEncodingMethod Encoding /*unused*/) {
536 llvm::raw_fd_ostream OS(FileName, EC,
537 llvm::sys::fs::OpenFlags::OF_TextWithCRLF);
545 return make_error_code(errc::io_error);
550 bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program,
551 ArrayRef<StringRef> Args) {
552 static long ArgMax = sysconf(_SC_ARG_MAX);
553 // POSIX requires that _POSIX_ARG_MAX is 4096, which is the lowest possible
554 // value for ARG_MAX on a POSIX compliant system.
555 static long ArgMin = _POSIX_ARG_MAX;
557 // This the same baseline used by xargs.
558 long EffectiveArgMax = 128 * 1024;
560 if (EffectiveArgMax > ArgMax)
561 EffectiveArgMax = ArgMax;
562 else if (EffectiveArgMax < ArgMin)
563 EffectiveArgMax = ArgMin;
565 // System says no practical limit.
569 // Conservatively account for space required by environment variables.
570 long HalfArgMax = EffectiveArgMax / 2;
572 size_t ArgLength = Program.size() + 1;
573 for (StringRef Arg : Args) {
574 // Ensure that we do not exceed the MAX_ARG_STRLEN constant on Linux, which
575 // does not have a constant unlike what the man pages would have you
576 // believe. Since this limit is pretty high, perform the check
577 // unconditionally rather than trying to be aggressive and limiting it to
579 if (Arg.size() >= (32 * 4096))
582 ArgLength += Arg.size() + 1;
583 if (ArgLength > size_t(HalfArgMax)) {