blob: 43a3e7f28339318ca3ad9749cf348e3833153843 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- llvm/System/Unix/Program.cpp -----------------------------*- C++ -*-===//
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +00002//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +00007//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008//===----------------------------------------------------------------------===//
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"
Bill Wendling94e1abc2008-05-29 22:02:08 +000021#include <iostream>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#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
35namespace llvm {
36using namespace sys;
37
Daniel Dunbar1b399062009-08-03 05:02:46 +000038Program::Program() : Pid_(0) {}
39
40Program::~Program() {}
41
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042// This function just uses the PATH environment variable to find the program.
43Path
44Program::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();
Benjamin Kramer9cd3dfe2009-07-28 22:08:15 +000052 // Use the given path verbatim if it contains any slashes; this matches
53 // the behavior of sh(1) and friends.
Dan Gohman33bff132009-07-28 23:25:18 +000054 if (progName.find('/') != std::string::npos)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055 return temp;
56
57 // At this point, the file name is valid and its not executable
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +000058
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059 // Get the path. If its empty, we can't do anything to find it.
60 const char *PathStr = getenv("PATH");
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +000061 if (PathStr == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062 return Path();
63
64 // Now we have a colon separated list of directories to search; try them.
Evan Cheng591bfc82008-05-05 18:30:58 +000065 size_t PathLen = strlen(PathStr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066 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
Matthijs Kooijman641150d2008-06-12 10:47:18 +000091static 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();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101
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 "
Daniel Dunbarf7ea85d2009-04-20 20:50:13 +0000106 + (FD == 0 ? "input" : "output"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000107 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
119static bool Timeout = false;
120static void TimeOutHandler(int Sig) {
121 Timeout = true;
122}
123
124static 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
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000149bool
150Program::Execute(const Path& path,
151 const char** args,
152 const char** envp,
153 const Path** redirects,
154 unsigned memoryLimit,
155 std::string* ErrMsg)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000156{
157 if (!path.canExecute()) {
158 if (ErrMsg)
159 *ErrMsg = path.toString() + " is not executable";
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000160 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 }
162
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 // 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");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000169 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170
171 // Child process: Execute the program.
172 case 0: {
173 // Redirect file descriptors...
174 if (redirects) {
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000175 // Redirect stdin
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000176 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000177 // Redirect stdout
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000178 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000179 if (redirects[1] && redirects[2] &&
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000180 *(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");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000185 return false;
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000186 }
187 } else {
188 // Just redirect stderr
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000189 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000190 }
191 }
192
193 // Set memory limits
194 if (memoryLimit!=0) {
195 SetMemoryLimits(memoryLimit);
196 }
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000197
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 // Execute!
199 if (envp != 0)
Daniel Dunbar1df47e82009-08-04 20:32:25 +0000200 execve(path.c_str(), (char**)args, (char**)envp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201 else
Daniel Dunbar1df47e82009-08-04 20:32:25 +0000202 execv(path.c_str(), (char**)args);
Dan Gohmana629b692009-08-05 00:09:12 +0000203 // If the execve() failed, we should exit. Follow Unix protocol and
204 // return 127 if the executable was not found, and 126 otherwise.
205 // Use _exit rather than exit so that atexit functions and static
206 // object destructors cloned from the parent process aren't
207 // redundantly run, and so that any data buffered in stdio buffers
208 // cloned from the parent aren't redundantly written out.
209 _exit(errno == ENOENT ? 127 : 126);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 }
211
212 // Parent process: Break out of the switch to do our processing.
213 default:
214 break;
215 }
216
217 // Make sure stderr and stdout have been flushed
Bill Wendling94e1abc2008-05-29 22:02:08 +0000218 std::cerr << std::flush;
219 std::cout << std::flush;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 fsync(1);
221 fsync(2);
222
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000223 Pid_ = child;
224
225 return true;
226}
227
228int
229Program::Wait(unsigned secondsToWait,
230 std::string* ErrMsg)
231{
232#ifdef HAVE_SYS_WAIT_H
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 struct sigaction Act, Old;
234
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000235 if (Pid_ == 0) {
236 MakeErrMsg(ErrMsg, "Process not started!");
237 return -1;
238 }
239
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240 // Install a timeout handler.
241 if (secondsToWait) {
242 Timeout = false;
243 Act.sa_sigaction = 0;
244 Act.sa_handler = TimeOutHandler;
245 sigemptyset(&Act.sa_mask);
246 Act.sa_flags = 0;
247 sigaction(SIGALRM, &Act, &Old);
248 alarm(secondsToWait);
249 }
250
251 // Parent process: Wait for the child process to terminate.
252 int status;
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000253 int child = this->Pid_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 while (wait(&status) != child)
255 if (secondsToWait && errno == EINTR) {
256 // Kill the child.
257 kill(child, SIGKILL);
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000258
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 // Turn off the alarm and restore the signal handler
260 alarm(0);
261 sigaction(SIGALRM, &Old, 0);
262
263 // Wait for child to die
264 if (wait(&status) != child)
265 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
Devang Patel930a5ad2008-02-04 20:57:54 +0000266 else
267 MakeErrMsg(ErrMsg, "Child timed out", 0);
268
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000269 return -1; // Timeout detected
Devang Patel930a5ad2008-02-04 20:57:54 +0000270 } else if (errno != EINTR) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 MakeErrMsg(ErrMsg, "Error waiting for child process");
272 return -1;
273 }
274
275 // We exited normally without timeout, so turn off the timer.
276 if (secondsToWait) {
277 alarm(0);
278 sigaction(SIGALRM, &Old, 0);
279 }
280
281 // Return the proper exit status. 0=success, >0 is programs' exit status,
282 // <0 means a signal was returned, -9999999 means the program dumped core.
283 int result = 0;
284 if (WIFEXITED(status))
285 result = WEXITSTATUS(status);
286 else if (WIFSIGNALED(status))
287 result = 0 - WTERMSIG(status);
288#ifdef WCOREDUMP
289 else if (WCOREDUMP(status))
290 result |= 0x01000000;
291#endif
292 return result;
293#else
294 return -99;
295#endif
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000296
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297}
298
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000299bool Program::ChangeStdinToBinary(){
300 // Do nothing, as Unix doesn't differentiate between text and binary.
301 return false;
302}
303
304bool Program::ChangeStdoutToBinary(){
305 // Do nothing, as Unix doesn't differentiate between text and binary.
306 return false;
307}
308
309}