Add non-blocking Wait() for launched processes
[oota-llvm.git] / lib / Support / Unix / Program.inc
1 //===- llvm/Support/Unix/Program.cpp -----------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Unix specific portion of the Program class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 //===----------------------------------------------------------------------===//
15 //=== WARNING: Implementation here must contain only generic UNIX code that
16 //===          is guaranteed to work on *all* UNIX variants.
17 //===----------------------------------------------------------------------===//
18
19 #include "Unix.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/FileSystem.h"
22 #include <llvm/Config/config.h>
23 #if HAVE_SYS_STAT_H
24 #include <sys/stat.h>
25 #endif
26 #if HAVE_SYS_RESOURCE_H
27 #include <sys/resource.h>
28 #endif
29 #if HAVE_SIGNAL_H
30 #include <signal.h>
31 #endif
32 #if HAVE_FCNTL_H
33 #include <fcntl.h>
34 #endif
35 #if HAVE_UNISTD_H
36 #include <unistd.h>
37 #endif
38 #ifdef HAVE_POSIX_SPAWN
39 #include <spawn.h>
40 #if !defined(__APPLE__)
41   extern char **environ;
42 #else
43 #include <crt_externs.h> // _NSGetEnviron
44 #endif
45 #endif
46
47 namespace llvm {
48 using namespace sys;
49
50 ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
51
52 // This function just uses the PATH environment variable to find the program.
53 std::string
54 sys::FindProgramByName(const std::string& progName) {
55
56   // Check some degenerate cases
57   if (progName.length() == 0) // no program
58     return "";
59   std::string temp = progName;
60   // Use the given path verbatim if it contains any slashes; this matches
61   // the behavior of sh(1) and friends.
62   if (progName.find('/') != std::string::npos)
63     return temp;
64
65   // At this point, the file name is valid and does not contain slashes. Search
66   // for it through the directories specified in the PATH environment variable.
67
68   // Get the path. If its empty, we can't do anything to find it.
69   const char *PathStr = getenv("PATH");
70   if (PathStr == 0)
71     return "";
72
73   // Now we have a colon separated list of directories to search; try them.
74   size_t PathLen = strlen(PathStr);
75   while (PathLen) {
76     // Find the first colon...
77     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
78
79     // Check to see if this first directory contains the executable...
80     SmallString<128> FilePath(PathStr,Colon);
81     sys::path::append(FilePath, progName);
82     if (sys::fs::can_execute(Twine(FilePath)))
83       return FilePath.str();                    // Found the executable!
84
85     // Nope it wasn't in this directory, check the next path in the list!
86     PathLen -= Colon-PathStr;
87     PathStr = Colon;
88
89     // Advance past duplicate colons
90     while (*PathStr == ':') {
91       PathStr++;
92       PathLen--;
93     }
94   }
95   return "";
96 }
97
98 static bool RedirectIO(const StringRef *Path, int FD, std::string* ErrMsg) {
99   if (Path == 0) // Noop
100     return false;
101   std::string File;
102   if (Path->empty())
103     // Redirect empty paths to /dev/null
104     File = "/dev/null";
105   else
106     File = *Path;
107
108   // Open the file
109   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
110   if (InFD == -1) {
111     MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
112               + (FD == 0 ? "input" : "output"));
113     return true;
114   }
115
116   // Install it as the requested FD
117   if (dup2(InFD, FD) == -1) {
118     MakeErrMsg(ErrMsg, "Cannot dup2");
119     close(InFD);
120     return true;
121   }
122   close(InFD);      // Close the original FD
123   return false;
124 }
125
126 #ifdef HAVE_POSIX_SPAWN
127 static bool RedirectIO_PS(const std::string *Path, int FD, std::string *ErrMsg,
128                           posix_spawn_file_actions_t *FileActions) {
129   if (Path == 0) // Noop
130     return false;
131   const char *File;
132   if (Path->empty())
133     // Redirect empty paths to /dev/null
134     File = "/dev/null";
135   else
136     File = Path->c_str();
137
138   if (int Err = posix_spawn_file_actions_addopen(
139           FileActions, FD, File,
140           FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
141     return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
142   return false;
143 }
144 #endif
145
146 static void TimeOutHandler(int Sig) {
147 }
148
149 static void SetMemoryLimits (unsigned size)
150 {
151 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
152   struct rlimit r;
153   __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
154
155   // Heap size
156   getrlimit (RLIMIT_DATA, &r);
157   r.rlim_cur = limit;
158   setrlimit (RLIMIT_DATA, &r);
159 #ifdef RLIMIT_RSS
160   // Resident set size.
161   getrlimit (RLIMIT_RSS, &r);
162   r.rlim_cur = limit;
163   setrlimit (RLIMIT_RSS, &r);
164 #endif
165 #ifdef RLIMIT_AS  // e.g. NetBSD doesn't have it.
166   // Don't set virtual memory limit if built with any Sanitizer. They need 80Tb
167   // of virtual memory for shadow memory mapping.
168 #if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD
169   // Virtual memory.
170   getrlimit (RLIMIT_AS, &r);
171   r.rlim_cur = limit;
172   setrlimit (RLIMIT_AS, &r);
173 #endif
174 #endif
175 #endif
176 }
177
178 }
179
180 static bool Execute(ProcessInfo &PI, StringRef Program, const char **args,
181                     const char **envp, const StringRef **redirects,
182                     unsigned memoryLimit, std::string *ErrMsg) {
183   if (!llvm::sys::fs::exists(Program)) {
184     if (ErrMsg)
185       *ErrMsg = std::string("Executable \"") + Program.str() +
186                 std::string("\" doesn't exist!");
187     return false;
188   }
189
190   // If this OS has posix_spawn and there is no memory limit being implied, use
191   // posix_spawn.  It is more efficient than fork/exec.
192 #ifdef HAVE_POSIX_SPAWN
193   if (memoryLimit == 0) {
194     posix_spawn_file_actions_t FileActionsStore;
195     posix_spawn_file_actions_t *FileActions = 0;
196
197     // If we call posix_spawn_file_actions_addopen we have to make sure the
198     // c strings we pass to it stay alive until the call to posix_spawn,
199     // so we copy any StringRefs into this variable.
200     std::string RedirectsStorage[3];
201
202     if (redirects) {
203       std::string *RedirectsStr[3] = {0, 0, 0};
204       for (int I = 0; I < 3; ++I) {
205         if (redirects[I]) {
206           RedirectsStorage[I] = *redirects[I];
207           RedirectsStr[I] = &RedirectsStorage[I];
208         }
209       }
210
211       FileActions = &FileActionsStore;
212       posix_spawn_file_actions_init(FileActions);
213
214       // Redirect stdin/stdout.
215       if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
216           RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
217         return false;
218       if (redirects[1] == 0 || redirects[2] == 0 ||
219           *redirects[1] != *redirects[2]) {
220         // Just redirect stderr
221         if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
222           return false;
223       } else {
224         // If stdout and stderr should go to the same place, redirect stderr
225         // to the FD already open for stdout.
226         if (int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
227           return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
228       }
229     }
230
231     if (!envp)
232 #if !defined(__APPLE__)
233       envp = const_cast<const char **>(environ);
234 #else
235       // environ is missing in dylibs.
236       envp = const_cast<const char **>(*_NSGetEnviron());
237 #endif
238
239     // Explicitly initialized to prevent what appears to be a valgrind false
240     // positive.
241     pid_t PID = 0;
242     int Err = posix_spawn(&PID, Program.str().c_str(), FileActions, /*attrp*/0,
243                           const_cast<char **>(args), const_cast<char **>(envp));
244
245     if (FileActions)
246       posix_spawn_file_actions_destroy(FileActions);
247
248     if (Err)
249      return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
250
251     PI.Pid = PID;
252
253     return true;
254   }
255 #endif
256
257   // Create a child process.
258   int child = fork();
259   switch (child) {
260     // An error occurred:  Return to the caller.
261     case -1:
262       MakeErrMsg(ErrMsg, "Couldn't fork");
263       return false;
264
265     // Child process: Execute the program.
266     case 0: {
267       // Redirect file descriptors...
268       if (redirects) {
269         // Redirect stdin
270         if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
271         // Redirect stdout
272         if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
273         if (redirects[1] && redirects[2] &&
274             *(redirects[1]) == *(redirects[2])) {
275           // If stdout and stderr should go to the same place, redirect stderr
276           // to the FD already open for stdout.
277           if (-1 == dup2(1,2)) {
278             MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
279             return false;
280           }
281         } else {
282           // Just redirect stderr
283           if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
284         }
285       }
286
287       // Set memory limits
288       if (memoryLimit!=0) {
289         SetMemoryLimits(memoryLimit);
290       }
291
292       // Execute!
293       std::string PathStr = Program;
294       if (envp != 0)
295         execve(PathStr.c_str(),
296                const_cast<char **>(args),
297                const_cast<char **>(envp));
298       else
299         execv(PathStr.c_str(),
300               const_cast<char **>(args));
301       // If the execve() failed, we should exit. Follow Unix protocol and
302       // return 127 if the executable was not found, and 126 otherwise.
303       // Use _exit rather than exit so that atexit functions and static
304       // object destructors cloned from the parent process aren't
305       // redundantly run, and so that any data buffered in stdio buffers
306       // cloned from the parent aren't redundantly written out.
307       _exit(errno == ENOENT ? 127 : 126);
308     }
309
310     // Parent process: Break out of the switch to do our processing.
311     default:
312       break;
313   }
314
315   PI.Pid = child;
316
317   return true;
318 }
319
320 namespace llvm {
321
322 ProcessInfo sys::Wait(const ProcessInfo &PI, unsigned SecondsToWait,
323                       bool WaitUntilTerminates, std::string *ErrMsg) {
324 #ifdef HAVE_SYS_WAIT_H
325   struct sigaction Act, Old;
326   assert(PI.Pid && "invalid pid to wait on, process not started?");
327
328   int WaitPidOptions = 0;
329   pid_t ChildPid = PI.Pid;
330   if (WaitUntilTerminates) {
331     SecondsToWait = 0;
332     ChildPid = -1; // mimic a wait() using waitpid()
333   } else if (SecondsToWait) {
334     // Install a timeout handler.  The handler itself does nothing, but the
335     // simple fact of having a handler at all causes the wait below to return
336     // with EINTR, unlike if we used SIG_IGN.
337     memset(&Act, 0, sizeof(Act));
338     Act.sa_handler = TimeOutHandler;
339     sigemptyset(&Act.sa_mask);
340     sigaction(SIGALRM, &Act, &Old);
341     alarm(SecondsToWait);
342   } else if (SecondsToWait == 0)
343     WaitPidOptions = WNOHANG;
344
345   // Parent process: Wait for the child process to terminate.
346   int status;
347   ProcessInfo WaitResult;
348   WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
349   if (WaitResult.Pid != PI.Pid) {
350     if (WaitResult.Pid == 0) {
351       // Non-blocking wait.
352       return WaitResult;
353     } else {
354       if (SecondsToWait && errno == EINTR) {
355         // Kill the child.
356         kill(PI.Pid, SIGKILL);
357
358         // Turn off the alarm and restore the signal handler
359         alarm(0);
360         sigaction(SIGALRM, &Old, 0);
361
362         // Wait for child to die
363         if (wait(&status) != ChildPid)
364           MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
365         else
366           MakeErrMsg(ErrMsg, "Child timed out", 0);
367
368         WaitResult.ReturnCode = -2; // Timeout detected
369         return WaitResult;
370       } else if (errno != EINTR) {
371         MakeErrMsg(ErrMsg, "Error waiting for child process");
372         WaitResult.ReturnCode = -1;
373         return WaitResult;
374       }
375     }
376   }
377
378   // We exited normally without timeout, so turn off the timer.
379   if (SecondsToWait && !WaitUntilTerminates) {
380     alarm(0);
381     sigaction(SIGALRM, &Old, 0);
382   }
383
384   // Return the proper exit status. Detect error conditions
385   // so we can return -1 for them and set ErrMsg informatively.
386   int result = 0;
387   if (WIFEXITED(status)) {
388     result = WEXITSTATUS(status);
389     WaitResult.ReturnCode = result;
390
391     if (result == 127) {
392       if (ErrMsg)
393         *ErrMsg = llvm::sys::StrError(ENOENT);
394       WaitResult.ReturnCode = -1;
395       return WaitResult;
396     }
397     if (result == 126) {
398       if (ErrMsg)
399         *ErrMsg = "Program could not be executed";
400       WaitResult.ReturnCode = -1;
401       return WaitResult;
402     }
403   } else if (WIFSIGNALED(status)) {
404     if (ErrMsg) {
405       *ErrMsg = strsignal(WTERMSIG(status));
406 #ifdef WCOREDUMP
407       if (WCOREDUMP(status))
408         *ErrMsg += " (core dumped)";
409 #endif
410     }
411     // Return a special value to indicate that the process received an unhandled
412     // signal during execution as opposed to failing to execute.
413     WaitResult.ReturnCode = -2;
414   }
415 #else
416   if (ErrMsg)
417     *ErrMsg = "Program::Wait is not implemented on this platform yet!";
418   WaitResult.ReturnCode = -2;
419 #endif
420   return WaitResult;
421 }
422
423 error_code sys::ChangeStdinToBinary(){
424   // Do nothing, as Unix doesn't differentiate between text and binary.
425   return make_error_code(errc::success);
426 }
427
428 error_code sys::ChangeStdoutToBinary(){
429   // Do nothing, as Unix doesn't differentiate between text and binary.
430   return make_error_code(errc::success);
431 }
432
433 error_code sys::ChangeStderrToBinary(){
434   // Do nothing, as Unix doesn't differentiate between text and binary.
435   return make_error_code(errc::success);
436 }
437
438 bool llvm::sys::argumentsFitWithinSystemLimits(ArrayRef<const char*> Args) {
439   static long ArgMax = sysconf(_SC_ARG_MAX);
440
441   // System says no practical limit.
442   if (ArgMax == -1)
443     return true;
444
445   // Conservatively account for space required by environment variables.
446   ArgMax /= 2;
447
448   size_t ArgLength = 0;
449   for (ArrayRef<const char*>::iterator I = Args.begin(), E = Args.end();
450        I != E; ++I) {
451     ArgLength += strlen(*I) + 1;
452     if (ArgLength > size_t(ArgMax)) {
453       return false;
454     }
455   }
456   return true;
457 }
458 }