1 //===- llvm/Support/Unix/Program.cpp -----------------------------*- 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 code that
15 //=== is guaranteed to work on *all* UNIX variants.
16 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Errc.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/StringSaver.h"
26 #include "llvm/Support/raw_ostream.h"
30 #if HAVE_SYS_RESOURCE_H
31 #include <sys/resource.h>
42 #ifdef HAVE_POSIX_SPAWN
45 #if defined(__APPLE__)
46 #include <TargetConditionals.h>
49 #if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
50 #define USE_NSGETENVIRON 1
52 #define USE_NSGETENVIRON 0
56 extern char **environ;
58 #include <crt_externs.h> // _NSGetEnviron
66 ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
68 ErrorOr<std::string> sys::findProgramByName(StringRef Name,
69 ArrayRef<StringRef> Paths) {
70 assert(!Name.empty() && "Must have a name!");
71 // Use the given path verbatim if it contains any slashes; this matches
72 // the behavior of sh(1) and friends.
73 if (Name.find('/') != StringRef::npos)
74 return std::string(Name);
76 SmallVector<StringRef, 16> EnvironmentPaths;
78 if (const char *PathEnv = std::getenv("PATH")) {
79 SplitString(PathEnv, EnvironmentPaths, ":");
80 Paths = EnvironmentPaths;
83 for (auto Path : Paths) {
87 // Check to see if this first directory contains the executable...
88 SmallString<128> FilePath(Path);
89 sys::path::append(FilePath, Name);
90 if (sys::fs::can_execute(FilePath.c_str()))
91 return std::string(FilePath.str()); // Found the executable!
93 return errc::no_such_file_or_directory;
96 static bool RedirectIO(Optional<StringRef> Path, int FD, std::string* ErrMsg) {
101 // Redirect empty paths to /dev/null
107 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
109 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
110 + (FD == 0 ? "input" : "output"));
114 // Install it as the requested FD
115 if (dup2(InFD, FD) == -1) {
116 MakeErrMsg(ErrMsg, "Cannot dup2");
120 close(InFD); // Close the original FD
124 #ifdef HAVE_POSIX_SPAWN
125 static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
126 posix_spawn_file_actions_t *FileActions) {
131 // Redirect empty paths to /dev/null
134 File = Path->c_str();
136 if (int Err = posix_spawn_file_actions_addopen(
137 FileActions, FD, File,
138 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
139 return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
144 static void TimeOutHandler(int Sig) {
147 static void SetMemoryLimits(unsigned size) {
148 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
150 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
153 getrlimit (RLIMIT_DATA, &r);
155 setrlimit (RLIMIT_DATA, &r);
157 // Resident set size.
158 getrlimit (RLIMIT_RSS, &r);
160 setrlimit (RLIMIT_RSS, &r);
167 static std::vector<const char *>
168 toNullTerminatedCStringArray(ArrayRef<StringRef> Strings, StringSaver &Saver) {
169 std::vector<const char *> Result;
170 for (StringRef S : Strings)
171 Result.push_back(Saver.save(S).data());
172 Result.push_back(nullptr);
176 static bool Execute(ProcessInfo &PI, StringRef Program,
177 ArrayRef<StringRef> Args, Optional<ArrayRef<StringRef>> Env,
178 ArrayRef<Optional<StringRef>> Redirects,
179 unsigned MemoryLimit, std::string *ErrMsg) {
180 if (!llvm::sys::fs::exists(Program)) {
182 *ErrMsg = std::string("Executable \"") + Program.str() +
183 std::string("\" doesn't exist!");
187 BumpPtrAllocator Allocator;
188 StringSaver Saver(Allocator);
189 std::vector<const char *> ArgVector, EnvVector;
190 const char **Argv = nullptr;
191 const char **Envp = nullptr;
192 ArgVector = toNullTerminatedCStringArray(Args, Saver);
193 Argv = ArgVector.data();
195 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
196 Envp = EnvVector.data();
199 // If this OS has posix_spawn and there is no memory limit being implied, use
200 // posix_spawn. It is more efficient than fork/exec.
201 #ifdef HAVE_POSIX_SPAWN
202 if (MemoryLimit == 0) {
203 posix_spawn_file_actions_t FileActionsStore;
204 posix_spawn_file_actions_t *FileActions = nullptr;
206 // If we call posix_spawn_file_actions_addopen we have to make sure the
207 // c strings we pass to it stay alive until the call to posix_spawn,
208 // so we copy any StringRefs into this variable.
209 std::string RedirectsStorage[3];
211 if (!Redirects.empty()) {
212 assert(Redirects.size() == 3);
213 std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
214 for (int I = 0; I < 3; ++I) {
216 RedirectsStorage[I] = *Redirects[I];
217 RedirectsStr[I] = &RedirectsStorage[I];
221 FileActions = &FileActionsStore;
222 posix_spawn_file_actions_init(FileActions);
224 // Redirect stdin/stdout.
225 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
226 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
228 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
229 // Just redirect stderr
230 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
233 // If stdout and stderr should go to the same place, redirect stderr
234 // to the FD already open for stdout.
235 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
236 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
241 #if !USE_NSGETENVIRON
242 Envp = const_cast<const char **>(environ);
244 // environ is missing in dylibs.
245 Envp = const_cast<const char **>(*_NSGetEnviron());
248 // Explicitly initialized to prevent what appears to be a valgrind false
251 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
252 /*attrp*/ nullptr, const_cast<char **>(Argv),
253 const_cast<char **>(Envp));
256 posix_spawn_file_actions_destroy(FileActions);
259 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
268 // Create a child process.
271 // An error occurred: Return to the caller.
273 MakeErrMsg(ErrMsg, "Couldn't fork");
276 // Child process: Execute the program.
278 // Redirect file descriptors...
279 if (!Redirects.empty()) {
281 if (RedirectIO(Redirects[0], 0, ErrMsg)) { return false; }
283 if (RedirectIO(Redirects[1], 1, ErrMsg)) { return false; }
284 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
285 // If stdout and stderr should go to the same place, redirect stderr
286 // to the FD already open for stdout.
287 if (-1 == dup2(1,2)) {
288 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
292 // Just redirect stderr
293 if (RedirectIO(Redirects[2], 2, ErrMsg)) { return false; }
298 if (MemoryLimit!=0) {
299 SetMemoryLimits(MemoryLimit);
303 std::string PathStr = Program;
305 execve(PathStr.c_str(), const_cast<char **>(Argv),
306 const_cast<char **>(Envp));
308 execv(PathStr.c_str(), const_cast<char **>(Argv));
309 // If the execve() failed, we should exit. Follow Unix protocol and
310 // return 127 if the executable was not found, and 126 otherwise.
311 // Use _exit rather than exit so that atexit functions and static
312 // object destructors cloned from the parent process aren't
313 // redundantly run, and so that any data buffered in stdio buffers
314 // cloned from the parent aren't redundantly written out.
315 _exit(errno == ENOENT ? 127 : 126);
318 // Parent process: Break out of the switch to do our processing.
331 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
332 bool WaitUntilTerminates, std::string *ErrMsg) {
333 struct sigaction Act, Old;
334 assert(PI.Pid && "invalid pid to wait on, process not started?");
336 int WaitPidOptions = 0;
337 pid_t ChildPid = PI.Pid;
338 if (WaitUntilTerminates) {
340 } else if (SecondsToWait) {
341 // Install a timeout handler. The handler itself does nothing, but the
342 // simple fact of having a handler at all causes the wait below to return
343 // with EINTR, unlike if we used SIG_IGN.
344 memset(&Act, 0, sizeof(Act));
345 Act.sa_handler = TimeOutHandler;
346 sigemptyset(&Act.sa_mask);
347 sigaction(SIGALRM, &Act, &Old);
348 alarm(SecondsToWait);
349 } else if (SecondsToWait == 0)
350 WaitPidOptions = WNOHANG;
352 // Parent process: Wait for the child process to terminate.
354 ProcessInfo WaitResult;
357 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
358 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
360 if (WaitResult.Pid != PI.Pid) {
361 if (WaitResult.Pid == 0) {
362 // Non-blocking wait.
365 if (SecondsToWait && errno == EINTR) {
367 kill(PI.Pid, SIGKILL);
369 // Turn off the alarm and restore the signal handler
371 sigaction(SIGALRM, &Old, nullptr);
373 // Wait for child to die
374 if (wait(&status) != ChildPid)
375 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
377 MakeErrMsg(ErrMsg, "Child timed out", 0);
379 WaitResult.ReturnCode = -2; // Timeout detected
381 } else if (errno != EINTR) {
382 MakeErrMsg(ErrMsg, "Error waiting for child process");
383 WaitResult.ReturnCode = -1;
389 // We exited normally without timeout, so turn off the timer.
390 if (SecondsToWait && !WaitUntilTerminates) {
392 sigaction(SIGALRM, &Old, nullptr);
395 // Return the proper exit status. Detect error conditions
396 // so we can return -1 for them and set ErrMsg informatively.
398 if (WIFEXITED(status)) {
399 result = WEXITSTATUS(status);
400 WaitResult.ReturnCode = result;
404 *ErrMsg = llvm::sys::StrError(ENOENT);
405 WaitResult.ReturnCode = -1;
410 *ErrMsg = "Program could not be executed";
411 WaitResult.ReturnCode = -1;
414 } else if (WIFSIGNALED(status)) {
416 *ErrMsg = strsignal(WTERMSIG(status));
418 if (WCOREDUMP(status))
419 *ErrMsg += " (core dumped)";
422 // Return a special value to indicate that the process received an unhandled
423 // signal during execution as opposed to failing to execute.
424 WaitResult.ReturnCode = -2;
429 std::error_code sys::ChangeStdinToBinary() {
430 // Do nothing, as Unix doesn't differentiate between text and binary.
431 return std::error_code();
434 std::error_code sys::ChangeStdoutToBinary() {
435 // Do nothing, as Unix doesn't differentiate between text and binary.
436 return std::error_code();
440 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
441 WindowsEncodingMethod Encoding /*unused*/) {
443 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
451 return make_error_code(errc::io_error);
456 bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program,
457 ArrayRef<StringRef> Args) {
458 static long ArgMax = sysconf(_SC_ARG_MAX);
459 // POSIX requires that _POSIX_ARG_MAX is 4096, which is the lowest possible
460 // value for ARG_MAX on a POSIX compliant system.
461 static long ArgMin = _POSIX_ARG_MAX;
463 // This the same baseline used by xargs.
464 long EffectiveArgMax = 128 * 1024;
466 if (EffectiveArgMax > ArgMax)
467 EffectiveArgMax = ArgMax;
468 else if (EffectiveArgMax < ArgMin)
469 EffectiveArgMax = ArgMin;
471 // System says no practical limit.
475 // Conservatively account for space required by environment variables.
476 long HalfArgMax = EffectiveArgMax / 2;
478 size_t ArgLength = Program.size() + 1;
479 for (StringRef Arg : Args) {
480 // Ensure that we do not exceed the MAX_ARG_STRLEN constant on Linux, which
481 // does not have a constant unlike what the man pages would have you
482 // believe. Since this limit is pretty high, perform the check
483 // unconditionally rather than trying to be aggressive and limiting it to
485 if (Arg.size() >= (32 * 4096))
488 ArgLength += Arg.size() + 1;
489 if (ArgLength > size_t(HalfArgMax)) {