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/Support/raw_ostream.h"
23 #include <llvm/Config/config.h>
27 #if HAVE_SYS_RESOURCE_H
28 #include <sys/resource.h>
39 #ifdef HAVE_POSIX_SPAWN
41 #define _RESTRICT_KYWD
44 #if !defined(__APPLE__)
45 extern char **environ;
47 #include <crt_externs.h> // _NSGetEnviron
55 ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
57 // This function just uses the PATH environment variable to find the program.
59 sys::FindProgramByName(const std::string& progName) {
61 // Check some degenerate cases
62 if (progName.length() == 0) // no program
64 std::string temp = progName;
65 // Use the given path verbatim if it contains any slashes; this matches
66 // the behavior of sh(1) and friends.
67 if (progName.find('/') != std::string::npos)
70 // At this point, the file name is valid and does not contain slashes. Search
71 // for it through the directories specified in the PATH environment variable.
73 // Get the path. If its empty, we can't do anything to find it.
74 const char *PathStr = getenv("PATH");
78 // Now we have a colon separated list of directories to search; try them.
79 size_t PathLen = strlen(PathStr);
81 // Find the first colon...
82 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
84 // Check to see if this first directory contains the executable...
85 SmallString<128> FilePath(PathStr,Colon);
86 sys::path::append(FilePath, progName);
87 if (sys::fs::can_execute(Twine(FilePath)))
88 return FilePath.str(); // Found the executable!
90 // Nope it wasn't in this directory, check the next path in the list!
91 PathLen -= Colon-PathStr;
94 // Advance past duplicate colons
95 while (*PathStr == ':') {
103 static bool RedirectIO(const StringRef *Path, int FD, std::string* ErrMsg) {
108 // Redirect empty paths to /dev/null
114 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
116 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
117 + (FD == 0 ? "input" : "output"));
121 // Install it as the requested FD
122 if (dup2(InFD, FD) == -1) {
123 MakeErrMsg(ErrMsg, "Cannot dup2");
127 close(InFD); // Close the original FD
131 #ifdef HAVE_POSIX_SPAWN
132 static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
133 posix_spawn_file_actions_t *FileActions) {
138 // Redirect empty paths to /dev/null
141 File = Path->c_str();
143 if (int Err = posix_spawn_file_actions_addopen(
144 FileActions, FD, File,
145 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);
185 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
186 const char **envp, const StringRef **redirects,
187 unsigned memoryLimit, std::string *ErrMsg) {
188 if (!llvm::sys::fs::exists(Program)) {
190 *ErrMsg = std::string("Executable \"") + Program.str() +
191 std::string("\" doesn't exist!");
195 // If this OS has posix_spawn and there is no memory limit being implied, use
196 // posix_spawn. It is more efficient than fork/exec.
197 #ifdef HAVE_POSIX_SPAWN
198 if (memoryLimit == 0) {
199 posix_spawn_file_actions_t FileActionsStore;
200 posix_spawn_file_actions_t *FileActions = nullptr;
202 // If we call posix_spawn_file_actions_addopen we have to make sure the
203 // c strings we pass to it stay alive until the call to posix_spawn,
204 // so we copy any StringRefs into this variable.
205 std::string RedirectsStorage[3];
208 std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
209 for (int I = 0; I < 3; ++I) {
211 RedirectsStorage[I] = *redirects[I];
212 RedirectsStr[I] = &RedirectsStorage[I];
216 FileActions = &FileActionsStore;
217 posix_spawn_file_actions_init(FileActions);
219 // Redirect stdin/stdout.
220 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
221 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
223 if (redirects[1] == nullptr || redirects[2] == nullptr ||
224 *redirects[1] != *redirects[2]) {
225 // Just redirect stderr
226 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
229 // If stdout and stderr should go to the same place, redirect stderr
230 // to the FD already open for stdout.
231 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
232 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
237 #if !defined(__APPLE__)
238 envp = const_cast<const char **>(environ);
240 // environ is missing in dylibs.
241 envp = const_cast<const char **>(*_NSGetEnviron());
244 // Explicitly initialized to prevent what appears to be a valgrind false
247 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
248 /*attrp*/nullptr, const_cast<char **>(args),
249 const_cast<char **>(envp));
252 posix_spawn_file_actions_destroy(FileActions);
255 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
263 // Create a child process.
266 // An error occurred: Return to the caller.
268 MakeErrMsg(ErrMsg, "Couldn't fork");
271 // Child process: Execute the program.
273 // Redirect file descriptors...
276 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
278 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
279 if (redirects[1] && redirects[2] &&
280 *(redirects[1]) == *(redirects[2])) {
281 // If stdout and stderr should go to the same place, redirect stderr
282 // to the FD already open for stdout.
283 if (-1 == dup2(1,2)) {
284 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
288 // Just redirect stderr
289 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
294 if (memoryLimit!=0) {
295 SetMemoryLimits(memoryLimit);
299 std::string PathStr = Program;
301 execve(PathStr.c_str(),
302 const_cast<char **>(args),
303 const_cast<char **>(envp));
305 execv(PathStr.c_str(),
306 const_cast<char **>(args));
307 // If the execve() failed, we should exit. Follow Unix protocol and
308 // return 127 if the executable was not found, and 126 otherwise.
309 // Use _exit rather than exit so that atexit functions and static
310 // object destructors cloned from the parent process aren't
311 // redundantly run, and so that any data buffered in stdio buffers
312 // cloned from the parent aren't redundantly written out.
313 _exit(errno == ENOENT ? 127 : 126);
316 // Parent process: Break out of the switch to do our processing.
328 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
329 bool WaitUntilTerminates, std::string *ErrMsg) {
330 #ifdef HAVE_SYS_WAIT_H
331 struct sigaction Act, Old;
332 assert(PI.Pid && "invalid pid to wait on, process not started?");
334 int WaitPidOptions = 0;
335 pid_t ChildPid = PI.Pid;
336 if (WaitUntilTerminates) {
338 ChildPid = -1; // mimic a wait() using waitpid()
339 } else if (SecondsToWait) {
340 // Install a timeout handler. The handler itself does nothing, but the
341 // simple fact of having a handler at all causes the wait below to return
342 // with EINTR, unlike if we used SIG_IGN.
343 memset(&Act, 0, sizeof(Act));
344 Act.sa_handler = TimeOutHandler;
345 sigemptyset(&Act.sa_mask);
346 sigaction(SIGALRM, &Act, &Old);
347 alarm(SecondsToWait);
348 } else if (SecondsToWait == 0)
349 WaitPidOptions = WNOHANG;
351 // Parent process: Wait for the child process to terminate.
353 ProcessInfo WaitResult;
356 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
357 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
359 if (WaitResult.Pid != PI.Pid) {
360 if (WaitResult.Pid == 0) {
361 // Non-blocking wait.
364 if (SecondsToWait && errno == EINTR) {
366 kill(PI.Pid, SIGKILL);
368 // Turn off the alarm and restore the signal handler
370 sigaction(SIGALRM, &Old, nullptr);
372 // Wait for child to die
373 if (wait(&status) != ChildPid)
374 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
376 MakeErrMsg(ErrMsg, "Child timed out", 0);
378 WaitResult.ReturnCode = -2; // Timeout detected
380 } else if (errno != EINTR) {
381 MakeErrMsg(ErrMsg, "Error waiting for child process");
382 WaitResult.ReturnCode = -1;
388 // We exited normally without timeout, so turn off the timer.
389 if (SecondsToWait && !WaitUntilTerminates) {
391 sigaction(SIGALRM, &Old, nullptr);
394 // Return the proper exit status. Detect error conditions
395 // so we can return -1 for them and set ErrMsg informatively.
397 if (WIFEXITED(status)) {
398 result = WEXITSTATUS(status);
399 WaitResult.ReturnCode = result;
403 *ErrMsg = llvm::sys::StrError(ENOENT);
404 WaitResult.ReturnCode = -1;
409 *ErrMsg = "Program could not be executed";
410 WaitResult.ReturnCode = -1;
413 } else if (WIFSIGNALED(status)) {
415 *ErrMsg = strsignal(WTERMSIG(status));
417 if (WCOREDUMP(status))
418 *ErrMsg += " (core dumped)";
421 // Return a special value to indicate that the process received an unhandled
422 // signal during execution as opposed to failing to execute.
423 WaitResult.ReturnCode = -2;
427 *ErrMsg = "Program::Wait is not implemented on this platform yet!";
428 ProcessInfo WaitResult;
429 WaitResult.ReturnCode = -2;
434 std::error_code sys::ChangeStdinToBinary(){
435 // Do nothing, as Unix doesn't differentiate between text and binary.
436 return std::error_code();
439 std::error_code sys::ChangeStdoutToBinary(){
440 // Do nothing, as Unix doesn't differentiate between text and binary.
441 return std::error_code();
445 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
446 WindowsEncodingMethod Encoding /*unused*/) {
448 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
456 return std::make_error_code(std::errc::io_error);
461 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
462 static long ArgMax = sysconf(_SC_ARG_MAX);
464 // System says no practical limit.
468 // Conservatively account for space required by environment variables.
469 long HalfArgMax = ArgMax / 2;
471 size_t ArgLength = 0;
472 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
474 ArgLength += strlen(*I) + 1;
475 if (ArgLength > size_t(HalfArgMax)) {