blob: 3c5a54cffc1a88102b958b0fb9260045a5230c0f [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
38// This function just uses the PATH environment variable to find the program.
39Path
40Program::FindProgramByName(const std::string& progName) {
41
42 // Check some degenerate cases
43 if (progName.length() == 0) // no program
44 return Path();
45 Path temp;
46 if (!temp.set(progName)) // invalid name
47 return Path();
Benjamin Kramer9cd3dfe2009-07-28 22:08:15 +000048 // Use the given path verbatim if it contains any slashes; this matches
49 // the behavior of sh(1) and friends.
Dan Gohman33bff132009-07-28 23:25:18 +000050 if (progName.find('/') != std::string::npos)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051 return temp;
52
53 // At this point, the file name is valid and its not executable
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +000054
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055 // Get the path. If its empty, we can't do anything to find it.
56 const char *PathStr = getenv("PATH");
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +000057 if (PathStr == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058 return Path();
59
60 // Now we have a colon separated list of directories to search; try them.
Evan Cheng591bfc82008-05-05 18:30:58 +000061 size_t PathLen = strlen(PathStr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062 while (PathLen) {
63 // Find the first colon...
64 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
65
66 // Check to see if this first directory contains the executable...
67 Path FilePath;
68 if (FilePath.set(std::string(PathStr,Colon))) {
69 FilePath.appendComponent(progName);
70 if (FilePath.canExecute())
71 return FilePath; // Found the executable!
72 }
73
74 // Nope it wasn't in this directory, check the next path in the list!
75 PathLen -= Colon-PathStr;
76 PathStr = Colon;
77
78 // Advance past duplicate colons
79 while (*PathStr == ':') {
80 PathStr++;
81 PathLen--;
82 }
83 }
84 return Path();
85}
86
Matthijs Kooijman641150d2008-06-12 10:47:18 +000087static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
88 if (Path == 0)
89 // Noop
90 return false;
91 std::string File;
92 if (Path->isEmpty())
93 // Redirect empty paths to /dev/null
94 File = "/dev/null";
95 else
96 File = Path->toString();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097
98 // Open the file
99 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
100 if (InFD == -1) {
101 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
Daniel Dunbarf7ea85d2009-04-20 20:50:13 +0000102 + (FD == 0 ? "input" : "output"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103 return true;
104 }
105
106 // Install it as the requested FD
107 if (-1 == dup2(InFD, FD)) {
108 MakeErrMsg(ErrMsg, "Cannot dup2");
109 return true;
110 }
111 close(InFD); // Close the original FD
112 return false;
113}
114
115static bool Timeout = false;
116static void TimeOutHandler(int Sig) {
117 Timeout = true;
118}
119
120static void SetMemoryLimits (unsigned size)
121{
122#if HAVE_SYS_RESOURCE_H
123 struct rlimit r;
124 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
125
126 // Heap size
127 getrlimit (RLIMIT_DATA, &r);
128 r.rlim_cur = limit;
129 setrlimit (RLIMIT_DATA, &r);
130#ifdef RLIMIT_RSS
131 // Resident set size.
132 getrlimit (RLIMIT_RSS, &r);
133 r.rlim_cur = limit;
134 setrlimit (RLIMIT_RSS, &r);
135#endif
136#ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
137 // Virtual memory.
138 getrlimit (RLIMIT_AS, &r);
139 r.rlim_cur = limit;
140 setrlimit (RLIMIT_AS, &r);
141#endif
142#endif
143}
144
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000145bool
146Program::Execute(const Path& path,
147 const char** args,
148 const char** envp,
149 const Path** redirects,
150 unsigned memoryLimit,
151 std::string* ErrMsg)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000152{
153 if (!path.canExecute()) {
154 if (ErrMsg)
155 *ErrMsg = path.toString() + " is not executable";
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000156 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 }
158
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000159 // Create a child process.
160 int child = fork();
161 switch (child) {
162 // An error occured: Return to the caller.
163 case -1:
164 MakeErrMsg(ErrMsg, "Couldn't fork");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000165 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000166
167 // Child process: Execute the program.
168 case 0: {
169 // Redirect file descriptors...
170 if (redirects) {
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000171 // Redirect stdin
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000172 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000173 // Redirect stdout
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000174 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000175 if (redirects[1] && redirects[2] &&
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000176 *(redirects[1]) == *(redirects[2])) {
177 // If stdout and stderr should go to the same place, redirect stderr
178 // to the FD already open for stdout.
179 if (-1 == dup2(1,2)) {
180 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000181 return false;
Matthijs Kooijman0e7dc8a2008-06-12 12:53:35 +0000182 }
183 } else {
184 // Just redirect stderr
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000185 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186 }
187 }
188
189 // Set memory limits
190 if (memoryLimit!=0) {
191 SetMemoryLimits(memoryLimit);
192 }
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000193
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194 // Execute!
195 if (envp != 0)
Dan Gohman5f222be2007-09-14 20:08:19 +0000196 execve (path.c_str(), (char**)args, (char**)envp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 else
Dan Gohman5f222be2007-09-14 20:08:19 +0000198 execv (path.c_str(), (char**)args);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 // If the execve() failed, we should exit and let the parent pick up
200 // our non-zero exit status.
201 exit (errno);
202 }
203
204 // Parent process: Break out of the switch to do our processing.
205 default:
206 break;
207 }
208
209 // Make sure stderr and stdout have been flushed
Bill Wendling94e1abc2008-05-29 22:02:08 +0000210 std::cerr << std::flush;
211 std::cout << std::flush;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212 fsync(1);
213 fsync(2);
214
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000215 Pid_ = child;
216
217 return true;
218}
219
220int
221Program::Wait(unsigned secondsToWait,
222 std::string* ErrMsg)
223{
224#ifdef HAVE_SYS_WAIT_H
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 struct sigaction Act, Old;
226
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000227 if (Pid_ == 0) {
228 MakeErrMsg(ErrMsg, "Process not started!");
229 return -1;
230 }
231
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 // Install a timeout handler.
233 if (secondsToWait) {
234 Timeout = false;
235 Act.sa_sigaction = 0;
236 Act.sa_handler = TimeOutHandler;
237 sigemptyset(&Act.sa_mask);
238 Act.sa_flags = 0;
239 sigaction(SIGALRM, &Act, &Old);
240 alarm(secondsToWait);
241 }
242
243 // Parent process: Wait for the child process to terminate.
244 int status;
Mikhail Glushenkovb23120b2009-07-18 21:43:12 +0000245 int child = this->Pid_;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 while (wait(&status) != child)
247 if (secondsToWait && errno == EINTR) {
248 // Kill the child.
249 kill(child, SIGKILL);
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000250
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251 // Turn off the alarm and restore the signal handler
252 alarm(0);
253 sigaction(SIGALRM, &Old, 0);
254
255 // Wait for child to die
256 if (wait(&status) != child)
257 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
Devang Patel930a5ad2008-02-04 20:57:54 +0000258 else
259 MakeErrMsg(ErrMsg, "Child timed out", 0);
260
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000261 return -1; // Timeout detected
Devang Patel930a5ad2008-02-04 20:57:54 +0000262 } else if (errno != EINTR) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 MakeErrMsg(ErrMsg, "Error waiting for child process");
264 return -1;
265 }
266
267 // We exited normally without timeout, so turn off the timer.
268 if (secondsToWait) {
269 alarm(0);
270 sigaction(SIGALRM, &Old, 0);
271 }
272
273 // Return the proper exit status. 0=success, >0 is programs' exit status,
274 // <0 means a signal was returned, -9999999 means the program dumped core.
275 int result = 0;
276 if (WIFEXITED(status))
277 result = WEXITSTATUS(status);
278 else if (WIFSIGNALED(status))
279 result = 0 - WTERMSIG(status);
280#ifdef WCOREDUMP
281 else if (WCOREDUMP(status))
282 result |= 0x01000000;
283#endif
284 return result;
285#else
286 return -99;
287#endif
Mikhail Glushenkov63b88c72009-07-17 20:38:17 +0000288
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289}
290
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291bool Program::ChangeStdinToBinary(){
292 // Do nothing, as Unix doesn't differentiate between text and binary.
293 return false;
294}
295
296bool Program::ChangeStdoutToBinary(){
297 // Do nothing, as Unix doesn't differentiate between text and binary.
298 return false;
299}
300
301}