1 //===- llvm/Support/Unix/Program.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Unix specific portion of the Program class.
12 //===----------------------------------------------------------------------===//
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //=== is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/raw_ostream.h"
30 #if HAVE_SYS_RESOURCE_H
31 #include <sys/resource.h>
42 #ifdef HAVE_POSIX_SPAWN
44 #define _RESTRICT_KYWD
48 #if defined(__APPLE__)
49 #include <TargetConditionals.h>
52 #if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
53 #define USE_NSGETENVIRON 1
55 #define USE_NSGETENVIRON 0
59 extern char **environ;
61 #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.find('/') != StringRef::npos)
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.str()); // Found the executable!
96 return errc::no_such_file_or_directory;
99 static bool RedirectIO(const StringRef *Path, int FD, std::string* ErrMsg) {
104 // Redirect empty paths to /dev/null
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,
141 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
142 return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
147 static void TimeOutHandler(int Sig) {
150 static void SetMemoryLimits (unsigned size)
152 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
154 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
157 getrlimit (RLIMIT_DATA, &r);
159 setrlimit (RLIMIT_DATA, &r);
161 // Resident set size.
162 getrlimit (RLIMIT_RSS, &r);
164 setrlimit (RLIMIT_RSS, &r);
166 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
167 // Don't set virtual memory limit if built with any Sanitizer. They need 80Tb
168 // of virtual memory for shadow memory mapping.
169 #if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD
171 getrlimit (RLIMIT_AS, &r);
173 setrlimit (RLIMIT_AS, &r);
181 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
182 const char **envp, const StringRef **redirects,
183 unsigned memoryLimit, std::string *ErrMsg) {
184 if (!llvm::sys::fs::exists(Program)) {
186 *ErrMsg = std::string("Executable \"") + Program.str() +
187 std::string("\" doesn't exist!");
191 // If this OS has posix_spawn and there is no memory limit being implied, use
192 // posix_spawn. It is more efficient than fork/exec.
193 #ifdef HAVE_POSIX_SPAWN
194 if (memoryLimit == 0) {
195 posix_spawn_file_actions_t FileActionsStore;
196 posix_spawn_file_actions_t *FileActions = nullptr;
198 // If we call posix_spawn_file_actions_addopen we have to make sure the
199 // c strings we pass to it stay alive until the call to posix_spawn,
200 // so we copy any StringRefs into this variable.
201 std::string RedirectsStorage[3];
204 std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
205 for (int I = 0; I < 3; ++I) {
207 RedirectsStorage[I] = *redirects[I];
208 RedirectsStr[I] = &RedirectsStorage[I];
212 FileActions = &FileActionsStore;
213 posix_spawn_file_actions_init(FileActions);
215 // Redirect stdin/stdout.
216 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
217 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
219 if (redirects[1] == nullptr || redirects[2] == nullptr ||
220 *redirects[1] != *redirects[2]) {
221 // Just redirect stderr
222 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
225 // If stdout and stderr should go to the same place, redirect stderr
226 // to the FD already open for stdout.
227 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
228 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
233 #if !USE_NSGETENVIRON
234 envp = const_cast<const char **>(environ);
236 // environ is missing in dylibs.
237 envp = const_cast<const char **>(*_NSGetEnviron());
240 // Explicitly initialized to prevent what appears to be a valgrind false
243 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
244 /*attrp*/nullptr, const_cast<char **>(args),
245 const_cast<char **>(envp));
248 posix_spawn_file_actions_destroy(FileActions);
251 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
259 // Create a child process.
262 // An error occurred: Return to the caller.
264 MakeErrMsg(ErrMsg, "Couldn't fork");
267 // Child process: Execute the program.
269 // Redirect file descriptors...
272 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
274 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
275 if (redirects[1] && redirects[2] &&
276 *(redirects[1]) == *(redirects[2])) {
277 // If stdout and stderr should go to the same place, redirect stderr
278 // to the FD already open for stdout.
279 if (-1 == dup2(1,2)) {
280 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
284 // Just redirect stderr
285 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
290 if (memoryLimit!=0) {
291 SetMemoryLimits(memoryLimit);
295 std::string PathStr = Program;
297 execve(PathStr.c_str(),
298 const_cast<char **>(args),
299 const_cast<char **>(envp));
301 execv(PathStr.c_str(),
302 const_cast<char **>(args));
303 // If the execve() failed, we should exit. Follow Unix protocol and
304 // return 127 if the executable was not found, and 126 otherwise.
305 // Use _exit rather than exit so that atexit functions and static
306 // object destructors cloned from the parent process aren't
307 // redundantly run, and so that any data buffered in stdio buffers
308 // cloned from the parent aren't redundantly written out.
309 _exit(errno == ENOENT ? 127 : 126);
312 // Parent process: Break out of the switch to do our processing.
324 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
325 bool WaitUntilTerminates, std::string *ErrMsg) {
326 struct sigaction Act, Old;
327 assert(PI.Pid && "invalid pid to wait on, process not started?");
329 int WaitPidOptions = 0;
330 pid_t ChildPid = PI.Pid;
331 if (WaitUntilTerminates) {
333 } else if (SecondsToWait) {
334 // Install a timeout handler. The handler itself does nothing, but the
335 // simple fact of having a handler at all causes the wait below to return
336 // with EINTR, unlike if we used SIG_IGN.
337 memset(&Act, 0, sizeof(Act));
338 Act.sa_handler = TimeOutHandler;
339 sigemptyset(&Act.sa_mask);
340 sigaction(SIGALRM, &Act, &Old);
341 alarm(SecondsToWait);
342 } else if (SecondsToWait == 0)
343 WaitPidOptions = WNOHANG;
345 // Parent process: Wait for the child process to terminate.
347 ProcessInfo WaitResult;
350 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
351 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
353 if (WaitResult.Pid != PI.Pid) {
354 if (WaitResult.Pid == 0) {
355 // Non-blocking wait.
358 if (SecondsToWait && errno == EINTR) {
360 kill(PI.Pid, SIGKILL);
362 // Turn off the alarm and restore the signal handler
364 sigaction(SIGALRM, &Old, nullptr);
366 // Wait for child to die
367 if (wait(&status) != ChildPid)
368 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
370 MakeErrMsg(ErrMsg, "Child timed out", 0);
372 WaitResult.ReturnCode = -2; // Timeout detected
374 } else if (errno != EINTR) {
375 MakeErrMsg(ErrMsg, "Error waiting for child process");
376 WaitResult.ReturnCode = -1;
382 // We exited normally without timeout, so turn off the timer.
383 if (SecondsToWait && !WaitUntilTerminates) {
385 sigaction(SIGALRM, &Old, nullptr);
388 // Return the proper exit status. Detect error conditions
389 // so we can return -1 for them and set ErrMsg informatively.
391 if (WIFEXITED(status)) {
392 result = WEXITSTATUS(status);
393 WaitResult.ReturnCode = result;
397 *ErrMsg = llvm::sys::StrError(ENOENT);
398 WaitResult.ReturnCode = -1;
403 *ErrMsg = "Program could not be executed";
404 WaitResult.ReturnCode = -1;
407 } else if (WIFSIGNALED(status)) {
409 *ErrMsg = strsignal(WTERMSIG(status));
411 if (WCOREDUMP(status))
412 *ErrMsg += " (core dumped)";
415 // Return a special value to indicate that the process received an unhandled
416 // signal during execution as opposed to failing to execute.
417 WaitResult.ReturnCode = -2;
422 std::error_code sys::ChangeStdinToBinary(){
423 // Do nothing, as Unix doesn't differentiate between text and binary.
424 return std::error_code();
427 std::error_code sys::ChangeStdoutToBinary(){
428 // Do nothing, as Unix doesn't differentiate between text and binary.
429 return std::error_code();
433 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
434 WindowsEncodingMethod Encoding /*unused*/) {
436 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
444 return make_error_code(errc::io_error);
449 bool llvm::sys::commandLineFitsWithinSystemLimits(StringRef Program, ArrayRef<const char*> Args) {
450 static long ArgMax = sysconf(_SC_ARG_MAX);
452 // System says no practical limit.
456 // Conservatively account for space required by environment variables.
457 long HalfArgMax = ArgMax / 2;
459 size_t ArgLength = Program.size() + 1;
460 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
462 ArgLength += strlen(*I) + 1;
463 if (ArgLength > size_t(HalfArgMax)) {