Using a signal handler that does nothing should be
[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
34 namespace llvm {
35 using namespace sys;
36
37 Program::Program() : Pid_(0) {}
38
39 Program::~Program() {}
40
41 // This function just uses the PATH environment variable to find the program.
42 Path
43 Program::FindProgramByName(const std::string& progName) {
44
45   // Check some degenerate cases
46   if (progName.length() == 0) // no program
47     return Path();
48   Path temp;
49   if (!temp.set(progName)) // invalid name
50     return Path();
51   // Use the given path verbatim if it contains any slashes; this matches
52   // the behavior of sh(1) and friends.
53   if (progName.find('/') != std::string::npos)
54     return temp;
55
56   // At this point, the file name does not contain slashes. Search for it
57   // through the directories specified in the PATH environment variable.
58
59   // Get the path. If its empty, we can't do anything to find it.
60   const char *PathStr = getenv("PATH");
61   if (PathStr == 0)
62     return Path();
63
64   // Now we have a colon separated list of directories to search; try them.
65   size_t PathLen = strlen(PathStr);
66   while (PathLen) {
67     // Find the first colon...
68     const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
69
70     // Check to see if this first directory contains the executable...
71     Path FilePath;
72     if (FilePath.set(std::string(PathStr,Colon))) {
73       FilePath.appendComponent(progName);
74       if (FilePath.canExecute())
75         return FilePath;                    // Found the executable!
76     }
77
78     // Nope it wasn't in this directory, check the next path in the list!
79     PathLen -= Colon-PathStr;
80     PathStr = Colon;
81
82     // Advance past duplicate colons
83     while (*PathStr == ':') {
84       PathStr++;
85       PathLen--;
86     }
87   }
88   return Path();
89 }
90
91 static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
92   if (Path == 0)
93     // Noop
94     return false;
95   std::string File;
96   if (Path->isEmpty())
97     // Redirect empty paths to /dev/null
98     File = "/dev/null";
99   else
100     File = Path->str();
101
102   // Open the file
103   int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
104   if (InFD == -1) {
105     MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
106               + (FD == 0 ? "input" : "output"));
107     return true;
108   }
109
110   // Install it as the requested FD
111   if (-1 == dup2(InFD, FD)) {
112     MakeErrMsg(ErrMsg, "Cannot dup2");
113     return true;
114   }
115   close(InFD);      // Close the original FD
116   return false;
117 }
118
119 static void SetMemoryLimits (unsigned size)
120 {
121 #if HAVE_SYS_RESOURCE_H
122   struct rlimit r;
123   __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
124
125   // Heap size
126   getrlimit (RLIMIT_DATA, &r);
127   r.rlim_cur = limit;
128   setrlimit (RLIMIT_DATA, &r);
129 #ifdef RLIMIT_RSS
130   // Resident set size.
131   getrlimit (RLIMIT_RSS, &r);
132   r.rlim_cur = limit;
133   setrlimit (RLIMIT_RSS, &r);
134 #endif
135 #ifdef RLIMIT_AS  // e.g. NetBSD doesn't have it.
136   // Virtual memory.
137   getrlimit (RLIMIT_AS, &r);
138   r.rlim_cur = limit;
139   setrlimit (RLIMIT_AS, &r);
140 #endif
141 #endif
142 }
143
144 bool
145 Program::Execute(const Path& path,
146                  const char** args,
147                  const char** envp,
148                  const Path** redirects,
149                  unsigned memoryLimit,
150                  std::string* ErrMsg)
151 {
152   if (!path.canExecute()) {
153     if (ErrMsg)
154       *ErrMsg = path.str() + " is not executable";
155     return false;
156   }
157
158   // Create a child process.
159   int child = fork();
160   switch (child) {
161     // An error occured:  Return to the caller.
162     case -1:
163       MakeErrMsg(ErrMsg, "Couldn't fork");
164       return false;
165
166     // Child process: Execute the program.
167     case 0: {
168       // Redirect file descriptors...
169       if (redirects) {
170         // Redirect stdin
171         if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
172         // Redirect stdout
173         if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
174         if (redirects[1] && redirects[2] &&
175             *(redirects[1]) == *(redirects[2])) {
176           // If stdout and stderr should go to the same place, redirect stderr
177           // to the FD already open for stdout.
178           if (-1 == dup2(1,2)) {
179             MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
180             return false;
181           }
182         } else {
183           // Just redirect stderr
184           if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
185         }
186       }
187
188       // Set memory limits
189       if (memoryLimit!=0) {
190         SetMemoryLimits(memoryLimit);
191       }
192
193       // Execute!
194       if (envp != 0)
195         execve(path.c_str(), (char**)args, (char**)envp);
196       else
197         execv(path.c_str(), (char**)args);
198       // If the execve() failed, we should exit. Follow Unix protocol and
199       // return 127 if the executable was not found, and 126 otherwise.
200       // Use _exit rather than exit so that atexit functions and static
201       // object destructors cloned from the parent process aren't
202       // redundantly run, and so that any data buffered in stdio buffers
203       // cloned from the parent aren't redundantly written out.
204       _exit(errno == ENOENT ? 127 : 126);
205     }
206
207     // Parent process: Break out of the switch to do our processing.
208     default:
209       break;
210   }
211
212   Pid_ = child;
213
214   return true;
215 }
216
217 int
218 Program::Wait(unsigned secondsToWait,
219               std::string* ErrMsg)
220 {
221 #ifdef HAVE_SYS_WAIT_H
222   struct sigaction Act, Old;
223
224   if (Pid_ == 0) {
225     MakeErrMsg(ErrMsg, "Process not started!");
226     return -1;
227   }
228
229   // Install a timeout handler.
230   if (secondsToWait) {
231     memset(&Act, 0, sizeof(Act));
232     Act.sa_handler = SIG_IGN;
233     sigemptyset(&Act.sa_mask);
234     sigaction(SIGALRM, &Act, &Old);
235     alarm(secondsToWait);
236   }
237
238   // Parent process: Wait for the child process to terminate.
239   int status;
240   int child = this->Pid_;
241   while (wait(&status) != child)
242     if (secondsToWait && errno == EINTR) {
243       // Kill the child.
244       kill(child, SIGKILL);
245
246       // Turn off the alarm and restore the signal handler
247       alarm(0);
248       sigaction(SIGALRM, &Old, 0);
249
250       // Wait for child to die
251       if (wait(&status) != child)
252         MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
253       else
254         MakeErrMsg(ErrMsg, "Child timed out", 0);
255
256       return -1;   // Timeout detected
257     } else if (errno != EINTR) {
258       MakeErrMsg(ErrMsg, "Error waiting for child process");
259       return -1;
260     }
261
262   // We exited normally without timeout, so turn off the timer.
263   if (secondsToWait) {
264     alarm(0);
265     sigaction(SIGALRM, &Old, 0);
266   }
267
268   // Return the proper exit status. 0=success, >0 is programs' exit status,
269   // <0 means a signal was returned, -9999999 means the program dumped core.
270   int result = 0;
271   if (WIFEXITED(status))
272     result = WEXITSTATUS(status);
273   else if (WIFSIGNALED(status))
274     result = 0 - WTERMSIG(status);
275 #ifdef WCOREDUMP
276   else if (WCOREDUMP(status))
277     result |= 0x01000000;
278 #endif
279   return result;
280 #else
281   return -99;
282 #endif
283
284 }
285
286 bool Program::ChangeStdinToBinary(){
287   // Do nothing, as Unix doesn't differentiate between text and binary.
288   return false;
289 }
290
291 bool Program::ChangeStdoutToBinary(){
292   // Do nothing, as Unix doesn't differentiate between text and binary.
293   return false;
294 }
295
296 }