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 ErrorOr<std::string> sys::findProgramByName(StringRef Name,
59 ArrayRef<StringRef> Paths) {
60 assert(!Name.empty() && "Must have a name!");
61 // Use the given path verbatim if it contains any slashes; this matches
62 // the behavior of sh(1) and friends.
63 if (Name.find('/') != StringRef::npos)
64 return std::string(Name);
66 SmallVector<StringRef, 16> EnvironmentPaths;
68 if (const char *PathEnv = std::getenv("PATH")) {
69 SplitString(PathEnv, EnvironmentPaths, ":");
70 Paths = EnvironmentPaths;
73 for (auto Path : Paths) {
77 // Check to see if this first directory contains the executable...
78 SmallString<128> FilePath(Path);
79 sys::path::append(FilePath, Name);
80 if (sys::fs::can_execute(FilePath.c_str()))
81 return std::string(FilePath.str()); // Found the executable!
83 return std::errc::no_such_file_or_directory;
86 static bool RedirectIO(const StringRef *Path, int FD, std::string* ErrMsg) {
91 // Redirect empty paths to /dev/null
97 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
99 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
100 + (FD == 0 ? "input" : "output"));
104 // Install it as the requested FD
105 if (dup2(InFD, FD) == -1) {
106 MakeErrMsg(ErrMsg, "Cannot dup2");
110 close(InFD); // Close the original FD
114 #ifdef HAVE_POSIX_SPAWN
115 static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
116 posix_spawn_file_actions_t *FileActions) {
121 // Redirect empty paths to /dev/null
124 File = Path->c_str();
126 if (int Err = posix_spawn_file_actions_addopen(
127 FileActions, FD, File,
128 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
129 return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
134 static void TimeOutHandler(int Sig) {
137 static void SetMemoryLimits (unsigned size)
139 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
141 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
144 getrlimit (RLIMIT_DATA, &r);
146 setrlimit (RLIMIT_DATA, &r);
148 // Resident set size.
149 getrlimit (RLIMIT_RSS, &r);
151 setrlimit (RLIMIT_RSS, &r);
153 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
154 // Don't set virtual memory limit if built with any Sanitizer. They need 80Tb
155 // of virtual memory for shadow memory mapping.
156 #if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD
158 getrlimit (RLIMIT_AS, &r);
160 setrlimit (RLIMIT_AS, &r);
168 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
169 const char **envp, const StringRef **redirects,
170 unsigned memoryLimit, std::string *ErrMsg) {
171 if (!llvm::sys::fs::exists(Program)) {
173 *ErrMsg = std::string("Executable \"") + Program.str() +
174 std::string("\" doesn't exist!");
178 // If this OS has posix_spawn and there is no memory limit being implied, use
179 // posix_spawn. It is more efficient than fork/exec.
180 #ifdef HAVE_POSIX_SPAWN
181 if (memoryLimit == 0) {
182 posix_spawn_file_actions_t FileActionsStore;
183 posix_spawn_file_actions_t *FileActions = nullptr;
185 // If we call posix_spawn_file_actions_addopen we have to make sure the
186 // c strings we pass to it stay alive until the call to posix_spawn,
187 // so we copy any StringRefs into this variable.
188 std::string RedirectsStorage[3];
191 std::string *RedirectsStr[3] = {nullptr, nullptr, nullptr};
192 for (int I = 0; I < 3; ++I) {
194 RedirectsStorage[I] = *redirects[I];
195 RedirectsStr[I] = &RedirectsStorage[I];
199 FileActions = &FileActionsStore;
200 posix_spawn_file_actions_init(FileActions);
202 // Redirect stdin/stdout.
203 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
204 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
206 if (redirects[1] == nullptr || redirects[2] == nullptr ||
207 *redirects[1] != *redirects[2]) {
208 // Just redirect stderr
209 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
212 // If stdout and stderr should go to the same place, redirect stderr
213 // to the FD already open for stdout.
214 if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
215 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
220 #if !defined(__APPLE__)
221 envp = const_cast<const char **>(environ);
223 // environ is missing in dylibs.
224 envp = const_cast<const char **>(*_NSGetEnviron());
227 // Explicitly initialized to prevent what appears to be a valgrind false
230 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
231 /*attrp*/nullptr, const_cast<char **>(args),
232 const_cast<char **>(envp));
235 posix_spawn_file_actions_destroy(FileActions);
238 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
246 // Create a child process.
249 // An error occurred: Return to the caller.
251 MakeErrMsg(ErrMsg, "Couldn't fork");
254 // Child process: Execute the program.
256 // Redirect file descriptors...
259 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
261 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
262 if (redirects[1] && redirects[2] &&
263 *(redirects[1]) == *(redirects[2])) {
264 // If stdout and stderr should go to the same place, redirect stderr
265 // to the FD already open for stdout.
266 if (-1 == dup2(1,2)) {
267 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
271 // Just redirect stderr
272 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
277 if (memoryLimit!=0) {
278 SetMemoryLimits(memoryLimit);
282 std::string PathStr = Program;
284 execve(PathStr.c_str(),
285 const_cast<char **>(args),
286 const_cast<char **>(envp));
288 execv(PathStr.c_str(),
289 const_cast<char **>(args));
290 // If the execve() failed, we should exit. Follow Unix protocol and
291 // return 127 if the executable was not found, and 126 otherwise.
292 // Use _exit rather than exit so that atexit functions and static
293 // object destructors cloned from the parent process aren't
294 // redundantly run, and so that any data buffered in stdio buffers
295 // cloned from the parent aren't redundantly written out.
296 _exit(errno == ENOENT ? 127 : 126);
299 // Parent process: Break out of the switch to do our processing.
311 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
312 bool WaitUntilTerminates, std::string *ErrMsg) {
313 #ifdef HAVE_SYS_WAIT_H
314 struct sigaction Act, Old;
315 assert(PI.Pid && "invalid pid to wait on, process not started?");
317 int WaitPidOptions = 0;
318 pid_t ChildPid = PI.Pid;
319 if (WaitUntilTerminates) {
321 } else if (SecondsToWait) {
322 // Install a timeout handler. The handler itself does nothing, but the
323 // simple fact of having a handler at all causes the wait below to return
324 // with EINTR, unlike if we used SIG_IGN.
325 memset(&Act, 0, sizeof(Act));
326 Act.sa_handler = TimeOutHandler;
327 sigemptyset(&Act.sa_mask);
328 sigaction(SIGALRM, &Act, &Old);
329 alarm(SecondsToWait);
330 } else if (SecondsToWait == 0)
331 WaitPidOptions = WNOHANG;
333 // Parent process: Wait for the child process to terminate.
335 ProcessInfo WaitResult;
338 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
339 } while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
341 if (WaitResult.Pid != PI.Pid) {
342 if (WaitResult.Pid == 0) {
343 // Non-blocking wait.
346 if (SecondsToWait && errno == EINTR) {
348 kill(PI.Pid, SIGKILL);
350 // Turn off the alarm and restore the signal handler
352 sigaction(SIGALRM, &Old, nullptr);
354 // Wait for child to die
355 if (wait(&status) != ChildPid)
356 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
358 MakeErrMsg(ErrMsg, "Child timed out", 0);
360 WaitResult.ReturnCode = -2; // Timeout detected
362 } else if (errno != EINTR) {
363 MakeErrMsg(ErrMsg, "Error waiting for child process");
364 WaitResult.ReturnCode = -1;
370 // We exited normally without timeout, so turn off the timer.
371 if (SecondsToWait && !WaitUntilTerminates) {
373 sigaction(SIGALRM, &Old, nullptr);
376 // Return the proper exit status. Detect error conditions
377 // so we can return -1 for them and set ErrMsg informatively.
379 if (WIFEXITED(status)) {
380 result = WEXITSTATUS(status);
381 WaitResult.ReturnCode = result;
385 *ErrMsg = llvm::sys::StrError(ENOENT);
386 WaitResult.ReturnCode = -1;
391 *ErrMsg = "Program could not be executed";
392 WaitResult.ReturnCode = -1;
395 } else if (WIFSIGNALED(status)) {
397 *ErrMsg = strsignal(WTERMSIG(status));
399 if (WCOREDUMP(status))
400 *ErrMsg += " (core dumped)";
403 // Return a special value to indicate that the process received an unhandled
404 // signal during execution as opposed to failing to execute.
405 WaitResult.ReturnCode = -2;
409 *ErrMsg = "Program::Wait is not implemented on this platform yet!";
410 ProcessInfo WaitResult;
411 WaitResult.ReturnCode = -2;
416 std::error_code sys::ChangeStdinToBinary(){
417 // Do nothing, as Unix doesn't differentiate between text and binary.
418 return std::error_code();
421 std::error_code sys::ChangeStdoutToBinary(){
422 // Do nothing, as Unix doesn't differentiate between text and binary.
423 return std::error_code();
427 llvm::sys::writeFileWithEncoding(StringRef FileName, StringRef Contents,
428 WindowsEncodingMethod Encoding /*unused*/) {
430 llvm::raw_fd_ostream OS(FileName, EC, llvm::sys::fs::OpenFlags::F_Text);
438 return std::make_error_code(std::errc::io_error);
443 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
444 static long ArgMax = sysconf(_SC_ARG_MAX);
446 // System says no practical limit.
450 // Conservatively account for space required by environment variables.
451 long HalfArgMax = ArgMax / 2;
453 size_t ArgLength = 0;
454 for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
456 ArgLength += strlen(*I) + 1;
457 if (ArgLength > size_t(HalfArgMax)) {