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/Support/Compiler.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <llvm/Config/config.h>
28 #if HAVE_SYS_RESOURCE_H
29 #include <sys/resource.h>
40 #ifdef HAVE_POSIX_SPAWN
42 #define _RESTRICT_KYWD
45 #if !defined(__APPLE__)
46 extern char **environ;
48 #include <crt_externs.h> // _NSGetEnviron
56 ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
58 // This function just uses the PATH environment variable to find the program.
60 sys::FindProgramByName(const std::string& progName) {
62 // Check some degenerate cases
63 if (progName.length() == 0) // no program
65 std::string temp = progName;
66 // Use the given path verbatim if it contains any slashes; this matches
67 // the behavior of sh(1) and friends.
68 if (progName.find('/') != std::string::npos)
71 // At this point, the file name is valid and does not contain slashes. Search
72 // for it through the directories specified in the PATH environment variable.
74 // Get the path. If its empty, we can't do anything to find it.
75 const char *PathStr = getenv("PATH");
79 // Now we have a colon separated list of directories to search; try them.
80 size_t PathLen = strlen(PathStr);
82 // Find the first colon...
83 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
85 // Check to see if this first directory contains the executable...
86 SmallString<128> FilePath(PathStr,Colon);
87 sys::path::append(FilePath, progName);
88 if (sys::fs::can_execute(Twine(FilePath)))
89 return FilePath.str(); // 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 ErrorOr<std::string> sys::findProgramByName(StringRef Name,
105 ArrayRef<StringRef> Paths) {
106 assert(!Name.empty() && "Must have a name!");
107 // Use the given path verbatim if it contains any slashes; this matches
108 // the behavior of sh(1) and friends.
109 if (Name.find('/') != StringRef::npos)
110 return std::string(Name);
113 SmallVector<StringRef, 16> SearchPaths;
114 SplitString(std::getenv("PATH"), SearchPaths, ":");
115 return findProgramByName(Name, SearchPaths);
118 for (auto Path : Paths) {
122 // Check to see if this first directory contains the executable...
123 SmallString<128> FilePath(Path);
124 sys::path::append(FilePath, Name);
125 if (sys::fs::can_execute(FilePath.c_str()))
126 return std::string(FilePath.str()); // Found the executable!
128 return std::errc::no_such_file_or_directory;
131 static bool RedirectIO(const StringRef *Path, int FD, std::string* ErrMsg) {
136 // Redirect empty paths to /dev/null
142 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
144 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
145 + (FD == 0 ? "input" : "output"));
149 // Install it as the requested FD
150 if (dup2(InFD, FD) == -1) {
151 MakeErrMsg(ErrMsg, "Cannot dup2");
155 close(InFD); // Close the original FD
159 #ifdef HAVE_POSIX_SPAWN
160 static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
161 posix_spawn_file_actions_t *FileActions) {
166 // Redirect empty paths to /dev/null
169 File = Path->c_str();
171 if (int Err = posix_spawn_file_actions_addopen(
172 FileActions, FD, File,
173 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
174 return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
179 static void TimeOutHandler(int Sig) {
182 static void SetMemoryLimits (unsigned size)
184 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
186 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
189 getrlimit (RLIMIT_DATA, &r);
191 setrlimit (RLIMIT_DATA, &r);
193 // Resident set size.
194 getrlimit (RLIMIT_RSS, &r);
196 setrlimit (RLIMIT_RSS, &r);
198 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
199 // Don't set virtual memory limit if built with any Sanitizer. They need 80Tb
200 // of virtual memory for shadow memory mapping.
201 #if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD
203 getrlimit (RLIMIT_AS, &r);
205 setrlimit (RLIMIT_AS, &r);
213 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
214 const char **envp, const StringRef **redirects,
215 unsigned memoryLimit, std::string *ErrMsg) {
216 if (!llvm::sys::fs::exists(Program)) {
218 *ErrMsg = std::string("Executable \"") + Program.str() +
219 std::string("\" doesn't exist!");
223 // If this OS has posix_spawn and there is no memory limit being implied, use
224 // posix_spawn. It is more efficient than fork/exec.
225 #ifdef HAVE_POSIX_SPAWN
226 if (memoryLimit == 0) {
227 posix_spawn_file_actions_t FileActionsStore;
228 posix_spawn_file_actions_t *FileActions = nullptr;
230 // If we call posix_spawn_file_actions_addopen we have to make sure the
231 // c strings we pass to it stay alive until the call to posix_spawn,
232 // so we copy any StringRefs into this variable.
233 std::string RedirectsStorage[3];
236 std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
237 for (int I = 0; I < 3; ++I) {
239 RedirectsStorage[I] = *redirects[I];
240 RedirectsStr[I] = &RedirectsStorage[I];
244 FileActions = &FileActionsStore;
245 posix_spawn_file_actions_init(FileActions);
247 // Redirect stdin/stdout.
248 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
249 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
251 if (redirects[1] == nullptr || redirects[2] == nullptr ||
252 *redirects[1] != *redirects[2]) {
253 // Just redirect stderr
254 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
257 // If stdout and stderr should go to the same place, redirect stderr
258 // to the FD already open for stdout.
259 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
260 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
265 #if !defined(__APPLE__)
266 envp = const_cast<const char **>(environ);
268 // environ is missing in dylibs.
269 envp = const_cast<const char **>(*_NSGetEnviron());
272 // Explicitly initialized to prevent what appears to be a valgrind false
275 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
276 /*attrp*/nullptr, const_cast<char **>(args),
277 const_cast<char **>(envp));
280 posix_spawn_file_actions_destroy(FileActions);
283 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
291 // Create a child process.
294 // An error occurred: Return to the caller.
296 MakeErrMsg(ErrMsg, "Couldn't fork");
299 // Child process: Execute the program.
301 // Redirect file descriptors...
304 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
306 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
307 if (redirects[1] && redirects[2] &&
308 *(redirects[1]) == *(redirects[2])) {
309 // If stdout and stderr should go to the same place, redirect stderr
310 // to the FD already open for stdout.
311 if (-1 == dup2(1,2)) {
312 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
316 // Just redirect stderr
317 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
322 if (memoryLimit!=0) {
323 SetMemoryLimits(memoryLimit);
327 std::string PathStr = Program;
329 execve(PathStr.c_str(),
330 const_cast<char **>(args),
331 const_cast<char **>(envp));
333 execv(PathStr.c_str(),
334 const_cast<char **>(args));
335 // If the execve() failed, we should exit. Follow Unix protocol and
336 // return 127 if the executable was not found, and 126 otherwise.
337 // Use _exit rather than exit so that atexit functions and static
338 // object destructors cloned from the parent process aren't
339 // redundantly run, and so that any data buffered in stdio buffers
340 // cloned from the parent aren't redundantly written out.
341 _exit(errno == ENOENT ? 127 : 126);
344 // Parent process: Break out of the switch to do our processing.
356 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
357 bool WaitUntilTerminates, std::string *ErrMsg) {
358 #ifdef HAVE_SYS_WAIT_H
359 struct sigaction Act, Old;
360 assert(PI.Pid && "invalid pid to wait on, process not started?");
362 int WaitPidOptions = 0;
363 pid_t ChildPid = PI.Pid;
364 if (WaitUntilTerminates) {
366 } else if (SecondsToWait) {
367 // Install a timeout handler. The handler itself does nothing, but the
368 // simple fact of having a handler at all causes the wait below to return
369 // with EINTR, unlike if we used SIG_IGN.
370 memset(&Act, 0, sizeof(Act));
371 Act.sa_handler = TimeOutHandler;
372 sigemptyset(&Act.sa_mask);
373 sigaction(SIGALRM, &Act, &Old);
374 alarm(SecondsToWait);
375 } else if (SecondsToWait == 0)
376 WaitPidOptions = WNOHANG;
378 // Parent process: Wait for the child process to terminate.
380 ProcessInfo WaitResult;
383 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
384 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
386 if (WaitResult.Pid != PI.Pid) {
387 if (WaitResult.Pid == 0) {
388 // Non-blocking wait.
391 if (SecondsToWait && errno == EINTR) {
393 kill(PI.Pid, SIGKILL);
395 // Turn off the alarm and restore the signal handler
397 sigaction(SIGALRM, &Old, nullptr);
399 // Wait for child to die
400 if (wait(&status) != ChildPid)
401 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
403 MakeErrMsg(ErrMsg, "Child timed out", 0);
405 WaitResult.ReturnCode = -2; // Timeout detected
407 } else if (errno != EINTR) {
408 MakeErrMsg(ErrMsg, "Error waiting for child process");
409 WaitResult.ReturnCode = -1;
415 // We exited normally without timeout, so turn off the timer.
416 if (SecondsToWait && !WaitUntilTerminates) {
418 sigaction(SIGALRM, &Old, nullptr);
421 // Return the proper exit status. Detect error conditions
422 // so we can return -1 for them and set ErrMsg informatively.
424 if (WIFEXITED(status)) {
425 result = WEXITSTATUS(status);
426 WaitResult.ReturnCode = result;
430 *ErrMsg = llvm::sys::StrError(ENOENT);
431 WaitResult.ReturnCode = -1;
436 *ErrMsg = "Program could not be executed";
437 WaitResult.ReturnCode = -1;
440 } else if (WIFSIGNALED(status)) {
442 *ErrMsg = strsignal(WTERMSIG(status));
444 if (WCOREDUMP(status))
445 *ErrMsg += " (core dumped)";
448 // Return a special value to indicate that the process received an unhandled
449 // signal during execution as opposed to failing to execute.
450 WaitResult.ReturnCode = -2;
454 *ErrMsg = "Program::Wait is not implemented on this platform yet!";
455 ProcessInfo WaitResult;
456 WaitResult.ReturnCode = -2;
461 std::error_code sys::ChangeStdinToBinary(){
462 // Do nothing, as Unix doesn't differentiate between text and binary.
463 return std::error_code();
466 std::error_code sys::ChangeStdoutToBinary(){
467 // Do nothing, as Unix doesn't differentiate between text and binary.
468 return std::error_code();
472 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
473 WindowsEncodingMethod Encoding /*unused*/) {
475 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
483 return std::make_error_code(std::errc::io_error);
488 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
489 static long ArgMax = sysconf(_SC_ARG_MAX);
491 // System says no practical limit.
495 // Conservatively account for space required by environment variables.
496 long HalfArgMax = ArgMax / 2;
498 size_t ArgLength = 0;
499 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
501 ArgLength += strlen(*I) + 1;
502 if (ArgLength > size_t(HalfArgMax)) {