3a562e45d41d5df83e5c2b506929c3fa5d370ffb
[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 #include <iostream>
22 #if HAVE_SYS_STAT_H
23 #include <sys/stat.h>
24 #endif
25 #if HAVE_SYS_RESOURCE_H
26 #include <sys/resource.h>
27 #endif
28 #if HAVE_SIGNAL_H
29 #include <signal.h>
30 #endif
31 #if HAVE_FCNTL_H
32 #include <fcntl.h>
33 #endif
34
35 namespace llvm {
36 using namespace sys;
37
38 Program::Program() : Pid_(0) {}
39
40 Program::~Program() {}
41
42 // This function just uses the PATH environment variable to find the program.
43 Path
44 Program::FindProgramByName(const std::string& progName) {
45
46   // Check some degenerate cases
47   if (progName.length() == 0) // no program
48     return Path();
49   Path temp;
50   if (!temp.set(progName)) // invalid name
51     return Path();
52   // Use the given path verbatim if it contains any slashes; this matches
53   // the behavior of sh(1) and friends.
54   if (progName.find('/') != std::string::npos)
55     return temp;
56
57   // At this point, the file name is valid and its not executable
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->toString();
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 bool Timeout = false;
120 static void TimeOutHandler(int Sig) {
121   Timeout = true;
122 }
123
124 static void SetMemoryLimits (unsigned size)
125 {
126 #if HAVE_SYS_RESOURCE_H
127   struct rlimit r;
128   __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
129
130   // Heap size
131   getrlimit (RLIMIT_DATA, &r);
132   r.rlim_cur = limit;
133   setrlimit (RLIMIT_DATA, &r);
134 #ifdef RLIMIT_RSS
135   // Resident set size.
136   getrlimit (RLIMIT_RSS, &r);
137   r.rlim_cur = limit;
138   setrlimit (RLIMIT_RSS, &r);
139 #endif
140 #ifdef RLIMIT_AS  // e.g. NetBSD doesn't have it.
141   // Virtual memory.
142   getrlimit (RLIMIT_AS, &r);
143   r.rlim_cur = limit;
144   setrlimit (RLIMIT_AS, &r);
145 #endif
146 #endif
147 }
148
149 bool
150 Program::Execute(const Path& path,
151                  const char** args,
152                  const char** envp,
153                  const Path** redirects,
154                  unsigned memoryLimit,
155                  std::string* ErrMsg)
156 {
157   if (!path.canExecute()) {
158     if (ErrMsg)
159       *ErrMsg = path.toString() + " is not executable";
160     return false;
161   }
162
163   // Create a child process.
164   int child = fork();
165   switch (child) {
166     // An error occured:  Return to the caller.
167     case -1:
168       MakeErrMsg(ErrMsg, "Couldn't fork");
169       return false;
170
171     // Child process: Execute the program.
172     case 0: {
173       // Redirect file descriptors...
174       if (redirects) {
175         // Redirect stdin
176         if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
177         // Redirect stdout
178         if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
179         if (redirects[1] && redirects[2] &&
180             *(redirects[1]) == *(redirects[2])) {
181           // If stdout and stderr should go to the same place, redirect stderr
182           // to the FD already open for stdout.
183           if (-1 == dup2(1,2)) {
184             MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
185             return false;
186           }
187         } else {
188           // Just redirect stderr
189           if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
190         }
191       }
192
193       // Set memory limits
194       if (memoryLimit!=0) {
195         SetMemoryLimits(memoryLimit);
196       }
197
198       // Execute!
199       if (envp != 0)
200         execve (path.c_str(), (char**)args, (char**)envp);
201       else
202         execv (path.c_str(), (char**)args);
203       // If the execve() failed, we should exit and let the parent pick up
204       // our non-zero exit status.
205       exit (errno);
206     }
207
208     // Parent process: Break out of the switch to do our processing.
209     default:
210       break;
211   }
212
213   // Make sure stderr and stdout have been flushed
214   std::cerr << std::flush;
215   std::cout << std::flush;
216   fsync(1);
217   fsync(2);
218
219   Pid_ = child;
220
221   return true;
222 }
223
224 int
225 Program::Wait(unsigned secondsToWait,
226               std::string* ErrMsg)
227 {
228 #ifdef HAVE_SYS_WAIT_H
229   struct sigaction Act, Old;
230
231   if (Pid_ == 0) {
232     MakeErrMsg(ErrMsg, "Process not started!");
233     return -1;
234   }
235
236   // Install a timeout handler.
237   if (secondsToWait) {
238     Timeout = false;
239     Act.sa_sigaction = 0;
240     Act.sa_handler = TimeOutHandler;
241     sigemptyset(&Act.sa_mask);
242     Act.sa_flags = 0;
243     sigaction(SIGALRM, &Act, &Old);
244     alarm(secondsToWait);
245   }
246
247   // Parent process: Wait for the child process to terminate.
248   int status;
249   int child = this->Pid_;
250   while (wait(&status) != child)
251     if (secondsToWait && errno == EINTR) {
252       // Kill the child.
253       kill(child, SIGKILL);
254
255       // Turn off the alarm and restore the signal handler
256       alarm(0);
257       sigaction(SIGALRM, &Old, 0);
258
259       // Wait for child to die
260       if (wait(&status) != child)
261         MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
262       else
263         MakeErrMsg(ErrMsg, "Child timed out", 0);
264
265       return -1;   // Timeout detected
266     } else if (errno != EINTR) {
267       MakeErrMsg(ErrMsg, "Error waiting for child process");
268       return -1;
269     }
270
271   // We exited normally without timeout, so turn off the timer.
272   if (secondsToWait) {
273     alarm(0);
274     sigaction(SIGALRM, &Old, 0);
275   }
276
277   // Return the proper exit status. 0=success, >0 is programs' exit status,
278   // <0 means a signal was returned, -9999999 means the program dumped core.
279   int result = 0;
280   if (WIFEXITED(status))
281     result = WEXITSTATUS(status);
282   else if (WIFSIGNALED(status))
283     result = 0 - WTERMSIG(status);
284 #ifdef WCOREDUMP
285   else if (WCOREDUMP(status))
286     result |= 0x01000000;
287 #endif
288   return result;
289 #else
290   return -99;
291 #endif
292
293 }
294
295 bool Program::ChangeStdinToBinary(){
296   // Do nothing, as Unix doesn't differentiate between text and binary.
297   return false;
298 }
299
300 bool Program::ChangeStdoutToBinary(){
301   // Do nothing, as Unix doesn't differentiate between text and binary.
302   return false;
303 }
304
305 }