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 #include <TargetConditionals.h>
48 #if !defined(__APPLE__) || defined(TARGET_OS_IPHONE)
49 extern char **environ;
51 #include <crt_externs.h> // _NSGetEnviron
59 ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
61 ErrorOr<std::string> sys::findProgramByName(StringRef Name,
62 ArrayRef<StringRef> Paths) {
63 assert(!Name.empty() && "Must have a name!");
64 // Use the given path verbatim if it contains any slashes; this matches
65 // the behavior of sh(1) and friends.
66 if (Name.find('/') != StringRef::npos)
67 return std::string(Name);
69 SmallVector<StringRef, 16> EnvironmentPaths;
71 if (const char *PathEnv = std::getenv("PATH")) {
72 SplitString(PathEnv, EnvironmentPaths, ":");
73 Paths = EnvironmentPaths;
76 for (auto Path : Paths) {
80 // Check to see if this first directory contains the executable...
81 SmallString<128> FilePath(Path);
82 sys::path::append(FilePath, Name);
83 if (sys::fs::can_execute(FilePath.c_str()))
84 return std::string(FilePath.str()); // Found the executable!
86 return std::errc::no_such_file_or_directory;
89 static bool RedirectIO(const StringRef *Path, int FD, std::string* ErrMsg) {
94 // Redirect empty paths to /dev/null
100 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
102 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
103 + (FD == 0 ? "input" : "output"));
107 // Install it as the requested FD
108 if (dup2(InFD, FD) == -1) {
109 MakeErrMsg(ErrMsg, "Cannot dup2");
113 close(InFD); // Close the original FD
117 #ifdef HAVE_POSIX_SPAWN
118 static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
119 posix_spawn_file_actions_t *FileActions) {
124 // Redirect empty paths to /dev/null
127 File = Path->c_str();
129 if (int Err = posix_spawn_file_actions_addopen(
130 FileActions, FD, File,
131 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
132 return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
137 static void TimeOutHandler(int Sig) {
140 static void SetMemoryLimits (unsigned size)
142 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
144 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
147 getrlimit (RLIMIT_DATA, &r);
149 setrlimit (RLIMIT_DATA, &r);
151 // Resident set size.
152 getrlimit (RLIMIT_RSS, &r);
154 setrlimit (RLIMIT_RSS, &r);
156 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
157 // Don't set virtual memory limit if built with any Sanitizer. They need 80Tb
158 // of virtual memory for shadow memory mapping.
159 #if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD
161 getrlimit (RLIMIT_AS, &r);
163 setrlimit (RLIMIT_AS, &r);
171 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
172 const char **envp, const StringRef **redirects,
173 unsigned memoryLimit, std::string *ErrMsg) {
174 if (!llvm::sys::fs::exists(Program)) {
176 *ErrMsg = std::string("Executable \"") + Program.str() +
177 std::string("\" doesn't exist!");
181 // If this OS has posix_spawn and there is no memory limit being implied, use
182 // posix_spawn. It is more efficient than fork/exec.
183 #ifdef HAVE_POSIX_SPAWN
184 if (memoryLimit == 0) {
185 posix_spawn_file_actions_t FileActionsStore;
186 posix_spawn_file_actions_t *FileActions = nullptr;
188 // If we call posix_spawn_file_actions_addopen we have to make sure the
189 // c strings we pass to it stay alive until the call to posix_spawn,
190 // so we copy any StringRefs into this variable.
191 std::string RedirectsStorage[3];
194 std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
195 for (int I = 0; I < 3; ++I) {
197 RedirectsStorage[I] = *redirects[I];
198 RedirectsStr[I] = &RedirectsStorage[I];
202 FileActions = &FileActionsStore;
203 posix_spawn_file_actions_init(FileActions);
205 // Redirect stdin/stdout.
206 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
207 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
209 if (redirects[1] == nullptr || redirects[2] == nullptr ||
210 *redirects[1] != *redirects[2]) {
211 // Just redirect stderr
212 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
215 // If stdout and stderr should go to the same place, redirect stderr
216 // to the FD already open for stdout.
217 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
218 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
223 #if !defined(__APPLE__) || defined(TARGET_OS_IPHONE)
224 envp = const_cast<const char **>(environ);
226 // environ is missing in dylibs.
227 envp = const_cast<const char **>(*_NSGetEnviron());
230 // Explicitly initialized to prevent what appears to be a valgrind false
233 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
234 /*attrp*/nullptr, const_cast<char **>(args),
235 const_cast<char **>(envp));
238 posix_spawn_file_actions_destroy(FileActions);
241 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
249 // Create a child process.
252 // An error occurred: Return to the caller.
254 MakeErrMsg(ErrMsg, "Couldn't fork");
257 // Child process: Execute the program.
259 // Redirect file descriptors...
262 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
264 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
265 if (redirects[1] && redirects[2] &&
266 *(redirects[1]) == *(redirects[2])) {
267 // If stdout and stderr should go to the same place, redirect stderr
268 // to the FD already open for stdout.
269 if (-1 == dup2(1,2)) {
270 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
274 // Just redirect stderr
275 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
280 if (memoryLimit!=0) {
281 SetMemoryLimits(memoryLimit);
285 std::string PathStr = Program;
287 execve(PathStr.c_str(),
288 const_cast<char **>(args),
289 const_cast<char **>(envp));
291 execv(PathStr.c_str(),
292 const_cast<char **>(args));
293 // If the execve() failed, we should exit. Follow Unix protocol and
294 // return 127 if the executable was not found, and 126 otherwise.
295 // Use _exit rather than exit so that atexit functions and static
296 // object destructors cloned from the parent process aren't
297 // redundantly run, and so that any data buffered in stdio buffers
298 // cloned from the parent aren't redundantly written out.
299 _exit(errno == ENOENT ? 127 : 126);
302 // Parent process: Break out of the switch to do our processing.
314 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
315 bool WaitUntilTerminates, std::string *ErrMsg) {
316 #ifdef HAVE_SYS_WAIT_H
317 struct sigaction Act, Old;
318 assert(PI.Pid && "invalid pid to wait on, process not started?");
320 int WaitPidOptions = 0;
321 pid_t ChildPid = PI.Pid;
322 if (WaitUntilTerminates) {
324 } else if (SecondsToWait) {
325 // Install a timeout handler. The handler itself does nothing, but the
326 // simple fact of having a handler at all causes the wait below to return
327 // with EINTR, unlike if we used SIG_IGN.
328 memset(&Act, 0, sizeof(Act));
329 Act.sa_handler = TimeOutHandler;
330 sigemptyset(&Act.sa_mask);
331 sigaction(SIGALRM, &Act, &Old);
332 alarm(SecondsToWait);
333 } else if (SecondsToWait == 0)
334 WaitPidOptions = WNOHANG;
336 // Parent process: Wait for the child process to terminate.
338 ProcessInfo WaitResult;
341 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
342 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
344 if (WaitResult.Pid != PI.Pid) {
345 if (WaitResult.Pid == 0) {
346 // Non-blocking wait.
349 if (SecondsToWait && errno == EINTR) {
351 kill(PI.Pid, SIGKILL);
353 // Turn off the alarm and restore the signal handler
355 sigaction(SIGALRM, &Old, nullptr);
357 // Wait for child to die
358 if (wait(&status) != ChildPid)
359 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
361 MakeErrMsg(ErrMsg, "Child timed out", 0);
363 WaitResult.ReturnCode = -2; // Timeout detected
365 } else if (errno != EINTR) {
366 MakeErrMsg(ErrMsg, "Error waiting for child process");
367 WaitResult.ReturnCode = -1;
373 // We exited normally without timeout, so turn off the timer.
374 if (SecondsToWait && !WaitUntilTerminates) {
376 sigaction(SIGALRM, &Old, nullptr);
379 // Return the proper exit status. Detect error conditions
380 // so we can return -1 for them and set ErrMsg informatively.
382 if (WIFEXITED(status)) {
383 result = WEXITSTATUS(status);
384 WaitResult.ReturnCode = result;
388 *ErrMsg = llvm::sys::StrError(ENOENT);
389 WaitResult.ReturnCode = -1;
394 *ErrMsg = "Program could not be executed";
395 WaitResult.ReturnCode = -1;
398 } else if (WIFSIGNALED(status)) {
400 *ErrMsg = strsignal(WTERMSIG(status));
402 if (WCOREDUMP(status))
403 *ErrMsg += " (core dumped)";
406 // Return a special value to indicate that the process received an unhandled
407 // signal during execution as opposed to failing to execute.
408 WaitResult.ReturnCode = -2;
412 *ErrMsg = "Program::Wait is not implemented on this platform yet!";
413 ProcessInfo WaitResult;
414 WaitResult.ReturnCode = -2;
419 std::error_code sys::ChangeStdinToBinary(){
420 // Do nothing, as Unix doesn't differentiate between text and binary.
421 return std::error_code();
424 std::error_code sys::ChangeStdoutToBinary(){
425 // Do nothing, as Unix doesn't differentiate between text and binary.
426 return std::error_code();
430 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
431 WindowsEncodingMethod Encoding /*unused*/) {
433 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
441 return std::make_error_code(std::errc::io_error);
446 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
447 static long ArgMax = sysconf(_SC_ARG_MAX);
449 // System says no practical limit.
453 // Conservatively account for space required by environment variables.
454 long HalfArgMax = ArgMax / 2;
456 size_t ArgLength = 0;
457 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
459 ArgLength += strlen(*I) + 1;
460 if (ArgLength > size_t(HalfArgMax)) {