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/Support/Compiler.h"
21 #include "llvm/Support/FileSystem.h"
22 #include <llvm/Config/config.h>
26 #if HAVE_SYS_RESOURCE_H
27 #include <sys/resource.h>
38 #ifdef HAVE_POSIX_SPAWN
40 #if !defined(__APPLE__)
41 extern char **environ;
43 #include <crt_externs.h> // _NSGetEnviron
50 Program::Program() : Data_(0) {}
52 Program::~Program() {}
54 // This function just uses the PATH environment variable to find the program.
56 Program::FindProgramByName(const std::string& progName) {
58 // Check some degenerate cases
59 if (progName.length() == 0) // no program
62 if (!temp.set(progName)) // invalid name
64 // Use the given path verbatim if it contains any slashes; this matches
65 // the behavior of sh(1) and friends.
66 if (progName.find('/') != std::string::npos)
69 // At this point, the file name is valid and does not contain slashes. Search
70 // for it through the directories specified in the PATH environment variable.
72 // Get the path. If its empty, we can't do anything to find it.
73 const char *PathStr = getenv("PATH");
77 // Now we have a colon separated list of directories to search; try them.
78 size_t PathLen = strlen(PathStr);
80 // Find the first colon...
81 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
83 // Check to see if this first directory contains the executable...
85 if (FilePath.set(std::string(PathStr,Colon))) {
86 FilePath.appendComponent(progName);
87 if (FilePath.canExecute())
88 return FilePath; // Found the executable!
91 // Nope it wasn't in this directory, check the next path in the list!
92 PathLen -= Colon-PathStr;
95 // Advance past duplicate colons
96 while (*PathStr == ':') {
104 static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
105 if (Path == 0) // Noop
109 // Redirect empty paths to /dev/null
112 File = Path->c_str();
115 int InFD = open(File, FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
117 MakeErrMsg(ErrMsg, "Cannot open file '" + std::string(File) + "' for "
118 + (FD == 0 ? "input" : "output"));
122 // Install it as the requested FD
123 if (dup2(InFD, FD) == -1) {
124 MakeErrMsg(ErrMsg, "Cannot dup2");
128 close(InFD); // Close the original FD
132 #ifdef HAVE_POSIX_SPAWN
133 static bool RedirectIO_PS(const Path *Path, int FD, std::string *ErrMsg,
134 posix_spawn_file_actions_t *FileActions) {
135 if (Path == 0) // Noop
139 // Redirect empty paths to /dev/null
142 File = Path->c_str();
144 if (int Err = posix_spawn_file_actions_addopen(FileActions, FD,
145 File, FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666))
146 return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
151 static void TimeOutHandler(int Sig) {
154 static void SetMemoryLimits (unsigned size)
156 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
158 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
161 getrlimit (RLIMIT_DATA, &r);
163 setrlimit (RLIMIT_DATA, &r);
165 // Resident set size.
166 getrlimit (RLIMIT_RSS, &r);
168 setrlimit (RLIMIT_RSS, &r);
170 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
171 // Don't set virtual memory limit if built with any Sanitizer. They need 80Tb
172 // of virtual memory for shadow memory mapping.
173 #if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD
175 getrlimit (RLIMIT_AS, &r);
177 setrlimit (RLIMIT_AS, &r);
184 Program::Execute(const Path &path, const char **args, const char **envp,
185 const Path **redirects, unsigned memoryLimit,
186 std::string *ErrMsg) {
187 // If this OS has posix_spawn and there is no memory limit being implied, use
188 // posix_spawn. It is more efficient than fork/exec.
189 #ifdef HAVE_POSIX_SPAWN
190 if (memoryLimit == 0) {
191 posix_spawn_file_actions_t FileActionsStore;
192 posix_spawn_file_actions_t *FileActions = 0;
195 FileActions = &FileActionsStore;
196 posix_spawn_file_actions_init(FileActions);
198 // Redirect stdin/stdout.
199 if (RedirectIO_PS(redirects[0], 0, ErrMsg, FileActions) ||
200 RedirectIO_PS(redirects[1], 1, ErrMsg, FileActions))
202 if (redirects[1] == 0 || redirects[2] == 0 ||
203 *redirects[1] != *redirects[2]) {
204 // Just redirect stderr
205 if (RedirectIO_PS(redirects[2], 2, ErrMsg, FileActions)) return false;
207 // If stdout and stderr should go to the same place, redirect stderr
208 // to the FD already open for stdout.
209 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
210 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
215 #if !defined(__APPLE__)
216 envp = const_cast<const char **>(environ);
218 // environ is missing in dylibs.
219 envp = const_cast<const char **>(*_NSGetEnviron());
222 // Explicitly initialized to prevent what appears to be a valgrind false
225 int Err = posix_spawn(&PID, path.c_str(), FileActions, /*attrp*/0,
226 const_cast<char **>(args), const_cast<char **>(envp));
229 posix_spawn_file_actions_destroy(FileActions);
232 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
234 Data_ = reinterpret_cast<void*>(PID);
239 // Create a child process.
242 // An error occurred: Return to the caller.
244 MakeErrMsg(ErrMsg, "Couldn't fork");
247 // Child process: Execute the program.
249 // Redirect file descriptors...
252 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
254 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
255 if (redirects[1] && redirects[2] &&
256 *(redirects[1]) == *(redirects[2])) {
257 // If stdout and stderr should go to the same place, redirect stderr
258 // to the FD already open for stdout.
259 if (-1 == dup2(1,2)) {
260 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
264 // Just redirect stderr
265 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
270 if (memoryLimit!=0) {
271 SetMemoryLimits(memoryLimit);
277 const_cast<char **>(args),
278 const_cast<char **>(envp));
281 const_cast<char **>(args));
282 // If the execve() failed, we should exit. Follow Unix protocol and
283 // return 127 if the executable was not found, and 126 otherwise.
284 // Use _exit rather than exit so that atexit functions and static
285 // object destructors cloned from the parent process aren't
286 // redundantly run, and so that any data buffered in stdio buffers
287 // cloned from the parent aren't redundantly written out.
288 _exit(errno == ENOENT ? 127 : 126);
291 // Parent process: Break out of the switch to do our processing.
296 Data_ = reinterpret_cast<void*>(child);
302 Program::Wait(const sys::Path &path,
303 unsigned secondsToWait,
306 #ifdef HAVE_SYS_WAIT_H
307 struct sigaction Act, Old;
310 MakeErrMsg(ErrMsg, "Process not started!");
314 // Install a timeout handler. The handler itself does nothing, but the simple
315 // fact of having a handler at all causes the wait below to return with EINTR,
316 // unlike if we used SIG_IGN.
318 memset(&Act, 0, sizeof(Act));
319 Act.sa_handler = TimeOutHandler;
320 sigemptyset(&Act.sa_mask);
321 sigaction(SIGALRM, &Act, &Old);
322 alarm(secondsToWait);
325 // Parent process: Wait for the child process to terminate.
327 uint64_t pid = reinterpret_cast<uint64_t>(Data_);
328 pid_t child = static_cast<pid_t>(pid);
329 while (waitpid(pid, &status, 0) != child)
330 if (secondsToWait && errno == EINTR) {
332 kill(child, SIGKILL);
334 // Turn off the alarm and restore the signal handler
336 sigaction(SIGALRM, &Old, 0);
338 // Wait for child to die
339 if (wait(&status) != child)
340 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
342 MakeErrMsg(ErrMsg, "Child timed out", 0);
344 return -2; // Timeout detected
345 } else if (errno != EINTR) {
346 MakeErrMsg(ErrMsg, "Error waiting for child process");
350 // We exited normally without timeout, so turn off the timer.
353 sigaction(SIGALRM, &Old, 0);
356 // Return the proper exit status. Detect error conditions
357 // so we can return -1 for them and set ErrMsg informatively.
359 if (WIFEXITED(status)) {
360 result = WEXITSTATUS(status);
361 #ifdef HAVE_POSIX_SPAWN
362 // The posix_spawn child process returns 127 on any kind of error.
363 // Following the POSIX convention for command-line tools (which posix_spawn
364 // itself apparently does not), check to see if the failure was due to some
365 // reason other than the file not existing, and return 126 in this case.
367 if (result == 127 && !llvm::sys::fs::exists(path.str(), Exists) && Exists)
372 *ErrMsg = llvm::sys::StrError(ENOENT);
377 *ErrMsg = "Program could not be executed";
380 } else if (WIFSIGNALED(status)) {
382 *ErrMsg = strsignal(WTERMSIG(status));
384 if (WCOREDUMP(status))
385 *ErrMsg += " (core dumped)";
388 // Return a special value to indicate that the process received an unhandled
389 // signal during execution as opposed to failing to execute.
395 *ErrMsg = "Program::Wait is not implemented on this platform yet!";
400 error_code Program::ChangeStdinToBinary(){
401 // Do nothing, as Unix doesn't differentiate between text and binary.
402 return make_error_code(errc::success);
405 error_code Program::ChangeStdoutToBinary(){
406 // Do nothing, as Unix doesn't differentiate between text and binary.
407 return make_error_code(errc::success);
410 error_code Program::ChangeStderrToBinary(){
411 // Do nothing, as Unix doesn't differentiate between text and binary.
412 return make_error_code(errc::success);
415 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
416 static long ArgMax = sysconf(_SC_ARG_MAX);
418 // System says no practical limit.
422 // Conservatively account for space required by environment variables.
425 size_t ArgLength = 0;
426 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
428 ArgLength += strlen(*I) + 1;
429 if (ArgLength > size_t(ArgMax)) {