Fix linux build. posix_spawn doesn't inherit the environment by default.
[oota-llvm.git] / lib / System / Unix / Program.inc
1 //===- llvm/System/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 <llvm/Config/config.h>
20 #include "Unix.h"
21 #if HAVE_SYS_STAT_H
22 #include <sys/stat.h>
23 #endif
24 #if HAVE_SYS_RESOURCE_H
25 #include <sys/resource.h>
26 #endif
27 #if HAVE_SIGNAL_H
28 #include <signal.h>
29 #endif
30 #if HAVE_FCNTL_H
31 #include <fcntl.h>
32 #endif
33 #ifdef HAVE_POSIX_SPAWN
34 #include <spawn.h>
35 #endif
36
37 extern char **environ;
38
39 namespace llvm {
40 using namespace sys;
41
42 Program::Program() : Data_(0) {}
43
44 Program::~Program() {}
45
46 unsigned Program::GetPid() const {
47   uint64_t pid = reinterpret_cast<uint64_t>(Data_);
48   return static_cast<unsigned>(pid);
49 }
50
51 // This function just uses the PATH environment variable to find the program.
52 Path
53 Program::FindProgramByName(const std::string& progName) {
54
55   // Check some degenerate cases
56   if (progName.length() == 0) // no program
57     return Path();
58   Path temp;
59   if (!temp.set(progName)) // invalid name
60     return Path();
61   // Use the given path verbatim if it contains any slashes; this matches
62   // the behavior of sh(1) and friends.
63   if (progName.find('/') != std::string::npos)
64     return temp;
65
66   // At this point, the file name does not contain slashes. Search for it
67   // through the directories specified in the PATH environment variable.
68
69   // Get the path. If its empty, we can't do anything to find it.
70   const char *PathStr = getenv("PATH");
71   if (PathStr == 0)
72     return Path();
73
74   // Now we have a colon separated list of directories to search; try them.
75   size_t PathLen = strlen(PathStr);
76   while (PathLen) {
77     // Find the first colon...
78     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
79
80     // Check to see if this first directory contains the executable...
81     Path FilePath;
82     if (FilePath.set(std::string(PathStr,Colon))) {
83       FilePath.appendComponent(progName);
84       if (FilePath.canExecute())
85         return FilePath;                    // Found the executable!
86     }
87
88     // Nope it wasn't in this directory, check the next path in the list!
89     PathLen -= Colon-PathStr;
90     PathStr = Colon;
91
92     // Advance past duplicate colons
93     while (*PathStr == ':') {
94       PathStr++;
95       PathLen--;
96     }
97   }
98   return Path();
99 }
100
101 static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
102   if (Path == 0) // Noop
103     return false;
104   std::string File;
105   if (Path->isEmpty())
106     // Redirect empty paths to /dev/null
107     File = "/dev/null";
108   else
109     File = Path->str();
110
111   // Open the file
112   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
113   if (InFD == -1) {
114     MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
115               + (FD == 0 ? "input" : "output"));
116     return true;
117   }
118
119   // Install it as the requested FD
120   if (dup2(InFD, FD) == -1) {
121     MakeErrMsg(ErrMsg, "Cannot dup2");
122     close(InFD);
123     return true;
124   }
125   close(InFD);      // Close the original FD
126   return false;
127 }
128
129 #ifdef HAVE_POSIX_SPAWN
130 static bool RedirectIO_PS(const Path *Path, int FD, std::string *ErrMsg,
131                           posix_spawn_file_actions_t &FileActions) {
132   if (Path == 0) // Noop
133     return false;
134   std::string File;
135   if (Path->isEmpty())
136     // Redirect empty paths to /dev/null
137     File = "/dev/null";
138   else
139     File = Path->str();
140     
141   if (int Err = posix_spawn_file_actions_addopen(&FileActions, FD,
142                     File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666))
143     return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
144   return false;
145 }
146 #endif
147
148 static void TimeOutHandler(int Sig) {
149 }
150
151 static void SetMemoryLimits (unsigned size)
152 {
153 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
154   struct rlimit r;
155   __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
156
157   // Heap size
158   getrlimit (RLIMIT_DATA, &r);
159   r.rlim_cur = limit;
160   setrlimit (RLIMIT_DATA, &r);
161 #ifdef RLIMIT_RSS
162   // Resident set size.
163   getrlimit (RLIMIT_RSS, &r);
164   r.rlim_cur = limit;
165   setrlimit (RLIMIT_RSS, &r);
166 #endif
167 #ifdef RLIMIT_AS  // e.g. NetBSD doesn't have it.
168   // Virtual memory.
169   getrlimit (RLIMIT_AS, &r);
170   r.rlim_cur = limit;
171   setrlimit (RLIMIT_AS, &r);
172 #endif
173 #endif
174 }
175
176 bool
177 Program::Execute(const Path &path, const char **args, const char **envp,
178                  const Path **redirects, unsigned memoryLimit,
179                   std::string *ErrMsg) {
180   // If this OS has posix_spawn and there is no memory limit being implied, use
181   // posix_spawn.  It is more efficient than fork/exec.
182 #ifdef HAVE_POSIX_SPAWN
183   if (memoryLimit == 0) {
184     posix_spawn_file_actions_t FileActions;
185     posix_spawn_file_actions_init(&FileActions);
186
187     if (redirects) {
188       // Redirect stdin/stdout.
189       if (RedirectIO_PS(redirects[0], 0, ErrMsg, FileActions) ||
190           RedirectIO_PS(redirects[1], 1, ErrMsg, FileActions))
191         return false;
192       if (redirects[1] == 0 || redirects[2] == 0 ||
193           *redirects[1] != *redirects[2]) {
194         // Just redirect stderr
195         if (RedirectIO_PS(redirects[2], 2, ErrMsg, FileActions)) return false;
196       } else {       
197         // If stdout and stderr should go to the same place, redirect stderr
198         // to the FD already open for stdout.
199         if (int Err = posix_spawn_file_actions_adddup2(&FileActions, 1, 2))
200           return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
201       }
202     }
203
204     pid_t PID;
205     if (!envp) envp = (const char**)environ;
206     int Err = posix_spawn(&PID, path.c_str(), &FileActions,
207                           /*attrp*/0, (char**)args, (char**)envp);
208                           
209     posix_spawn_file_actions_destroy(&FileActions);
210
211     if (Err)
212      return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
213       
214     Data_ = reinterpret_cast<void*>(PID);
215     return true;
216   }
217 #endif
218   
219   if (!path.canExecute()) {
220     if (ErrMsg)
221       *ErrMsg = path.str() + " is not executable";
222     return false;
223   }
224
225   // Create a child process.
226   int child = fork();
227   switch (child) {
228     // An error occured:  Return to the caller.
229     case -1:
230       MakeErrMsg(ErrMsg, "Couldn't fork");
231       return false;
232
233     // Child process: Execute the program.
234     case 0: {
235       // Redirect file descriptors...
236       if (redirects) {
237         // Redirect stdin
238         if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
239         // Redirect stdout
240         if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
241         if (redirects[1] && redirects[2] &&
242             *(redirects[1]) == *(redirects[2])) {
243           // If stdout and stderr should go to the same place, redirect stderr
244           // to the FD already open for stdout.
245           if (-1 == dup2(1,2)) {
246             MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
247             return false;
248           }
249         } else {
250           // Just redirect stderr
251           if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
252         }
253       }
254
255       // Set memory limits
256       if (memoryLimit!=0) {
257         SetMemoryLimits(memoryLimit);
258       }
259
260       // Execute!
261       if (envp != 0)
262         execve(path.c_str(), (char**)args, (char**)envp);
263       else
264         execv(path.c_str(), (char**)args);
265       // If the execve() failed, we should exit. Follow Unix protocol and
266       // return 127 if the executable was not found, and 126 otherwise.
267       // Use _exit rather than exit so that atexit functions and static
268       // object destructors cloned from the parent process aren't
269       // redundantly run, and so that any data buffered in stdio buffers
270       // cloned from the parent aren't redundantly written out.
271       _exit(errno == ENOENT ? 127 : 126);
272     }
273
274     // Parent process: Break out of the switch to do our processing.
275     default:
276       break;
277   }
278
279   Data_ = reinterpret_cast<void*>(child);
280
281   return true;
282 }
283
284 int
285 Program::Wait(unsigned secondsToWait,
286               std::string* ErrMsg)
287 {
288 #ifdef HAVE_SYS_WAIT_H
289   struct sigaction Act, Old;
290
291   if (Data_ == 0) {
292     MakeErrMsg(ErrMsg, "Process not started!");
293     return -1;
294   }
295
296   // Install a timeout handler.  The handler itself does nothing, but the simple
297   // fact of having a handler at all causes the wait below to return with EINTR,
298   // unlike if we used SIG_IGN.
299   if (secondsToWait) {
300 #ifndef __HAIKU__
301     Act.sa_sigaction = 0;
302 #endif
303     Act.sa_handler = TimeOutHandler;
304     sigemptyset(&Act.sa_mask);
305     Act.sa_flags = 0;
306     sigaction(SIGALRM, &Act, &Old);
307     alarm(secondsToWait);
308   }
309
310   // Parent process: Wait for the child process to terminate.
311   int status;
312   uint64_t pid = reinterpret_cast<uint64_t>(Data_);
313   pid_t child = static_cast<pid_t>(pid);
314   while (waitpid(pid, &status, 0) != child)
315     if (secondsToWait && errno == EINTR) {
316       // Kill the child.
317       kill(child, SIGKILL);
318
319       // Turn off the alarm and restore the signal handler
320       alarm(0);
321       sigaction(SIGALRM, &Old, 0);
322
323       // Wait for child to die
324       if (wait(&status) != child)
325         MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
326       else
327         MakeErrMsg(ErrMsg, "Child timed out", 0);
328
329       return -1;   // Timeout detected
330     } else if (errno != EINTR) {
331       MakeErrMsg(ErrMsg, "Error waiting for child process");
332       return -1;
333     }
334
335   // We exited normally without timeout, so turn off the timer.
336   if (secondsToWait) {
337     alarm(0);
338     sigaction(SIGALRM, &Old, 0);
339   }
340
341   // Return the proper exit status. 0=success, >0 is programs' exit status,
342   // <0 means a signal was returned, -9999999 means the program dumped core.
343   int result = 0;
344   if (WIFEXITED(status))
345     result = WEXITSTATUS(status);
346   else if (WIFSIGNALED(status))
347     result = 0 - WTERMSIG(status);
348 #ifdef WCOREDUMP
349   else if (WCOREDUMP(status))
350     result |= 0x01000000;
351 #endif
352   return result;
353 #else
354   return -99;
355 #endif
356
357 }
358
359 bool
360 Program::Kill(std::string* ErrMsg) {
361   if (Data_ == 0) {
362     MakeErrMsg(ErrMsg, "Process not started!");
363     return true;
364   }
365
366   uint64_t pid64 = reinterpret_cast<uint64_t>(Data_);
367   pid_t pid = static_cast<pid_t>(pid64);
368
369   if (kill(pid, SIGKILL) != 0) {
370     MakeErrMsg(ErrMsg, "The process couldn't be killed!");
371     return true;
372   }
373
374   return false;
375 }
376
377 bool Program::ChangeStdinToBinary(){
378   // Do nothing, as Unix doesn't differentiate between text and binary.
379   return false;
380 }
381
382 bool Program::ChangeStdoutToBinary(){
383   // Do nothing, as Unix doesn't differentiate between text and binary.
384   return false;
385 }
386
387 bool Program::ChangeStderrToBinary(){
388   // Do nothing, as Unix doesn't differentiate between text and binary.
389   return false;
390 }
391
392 }