blob: 7fdf3872dd9bfc94f5b31e9a79dc1a91582c0a86 [file] [log] [blame]
Reid Spencer52a7efa2004-08-29 19:20:41 +00001//===- llvm/System/Unix/Program.cpp -----------------------------*- C++ -*-===//
Mikhail Glushenkov234f6892009-07-17 20:38:17 +00002//
Reid Spencer52a7efa2004-08-29 19:20:41 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Glushenkov234f6892009-07-17 20:38:17 +00007//
Reid Spencer52a7efa2004-08-29 19:20:41 +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
Reid Spencer551ccae2004-09-01 22:55:40 +000019#include <llvm/Config/config.h>
Reid Spencer52a7efa2004-08-29 19:20:41 +000020#include "Unix.h"
Reid Spencercdf54d02004-12-27 06:16:52 +000021#if HAVE_SYS_STAT_H
22#include <sys/stat.h>
23#endif
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +000024#if HAVE_SYS_RESOURCE_H
25#include <sys/resource.h>
26#endif
Reid Spencercdf54d02004-12-27 06:16:52 +000027#if HAVE_SIGNAL_H
28#include <signal.h>
29#endif
30#if HAVE_FCNTL_H
31#include <fcntl.h>
32#endif
Chris Lattner4f098b62010-04-18 04:14:37 +000033#ifdef HAVE_POSIX_SPAWN
34#include <spawn.h>
Nick Lewycky65238032010-04-18 07:07:48 +000035#if !defined(__APPLE__)
36 extern char **environ;
37#endif
Chris Lattner4f098b62010-04-18 04:14:37 +000038#endif
Reid Spencer52a7efa2004-08-29 19:20:41 +000039
Reid Spencer52a7efa2004-08-29 19:20:41 +000040namespace llvm {
41using namespace sys;
42
Daniel Dunbar57d69032009-09-22 04:44:56 +000043Program::Program() : Data_(0) {}
44
45Program::~Program() {}
46
47unsigned Program::GetPid() const {
48 uint64_t pid = reinterpret_cast<uint64_t>(Data_);
49 return static_cast<unsigned>(pid);
50}
51
Reid Spencer52a7efa2004-08-29 19:20:41 +000052// This function just uses the PATH environment variable to find the program.
Reid Spencer25659432004-09-13 21:48:44 +000053Path
Reid Spencer52a7efa2004-08-29 19:20:41 +000054Program::FindProgramByName(const std::string& progName) {
55
56 // Check some degenerate cases
57 if (progName.length() == 0) // no program
Reid Spencer25659432004-09-13 21:48:44 +000058 return Path();
59 Path temp;
Reid Spencerdd04df02005-07-07 23:21:43 +000060 if (!temp.set(progName)) // invalid name
Reid Spencer25659432004-09-13 21:48:44 +000061 return Path();
Benjamin Kramerb0facb12009-07-28 22:08:15 +000062 // Use the given path verbatim if it contains any slashes; this matches
63 // the behavior of sh(1) and friends.
Dan Gohmana87861e2009-07-28 23:25:18 +000064 if (progName.find('/') != std::string::npos)
Reid Spencer52a7efa2004-08-29 19:20:41 +000065 return temp;
66
Dan Gohman88abb892009-08-05 17:32:39 +000067 // At this point, the file name does not contain slashes. Search for it
68 // through the directories specified in the PATH environment variable.
Mikhail Glushenkov234f6892009-07-17 20:38:17 +000069
Reid Spencer52a7efa2004-08-29 19:20:41 +000070 // Get the path. If its empty, we can't do anything to find it.
71 const char *PathStr = getenv("PATH");
Mikhail Glushenkov234f6892009-07-17 20:38:17 +000072 if (PathStr == 0)
Reid Spencer25659432004-09-13 21:48:44 +000073 return Path();
Reid Spencer52a7efa2004-08-29 19:20:41 +000074
75 // Now we have a colon separated list of directories to search; try them.
Evan Cheng34cd4a42008-05-05 18:30:58 +000076 size_t PathLen = strlen(PathStr);
Reid Spencer52a7efa2004-08-29 19:20:41 +000077 while (PathLen) {
78 // Find the first colon...
79 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
80
81 // Check to see if this first directory contains the executable...
Reid Spencer25659432004-09-13 21:48:44 +000082 Path FilePath;
Reid Spencerdd04df02005-07-07 23:21:43 +000083 if (FilePath.set(std::string(PathStr,Colon))) {
84 FilePath.appendComponent(progName);
Reid Spencerc7f08322005-07-07 18:21:42 +000085 if (FilePath.canExecute())
Reid Spencer52a7efa2004-08-29 19:20:41 +000086 return FilePath; // Found the executable!
87 }
88
89 // Nope it wasn't in this directory, check the next path in the list!
90 PathLen -= Colon-PathStr;
91 PathStr = Colon;
92
93 // Advance past duplicate colons
94 while (*PathStr == ':') {
95 PathStr++;
96 PathLen--;
97 }
98 }
Reid Spencer25659432004-09-13 21:48:44 +000099 return Path();
Reid Spencer52a7efa2004-08-29 19:20:41 +0000100}
101
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000102static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
Chris Lattner4f098b62010-04-18 04:14:37 +0000103 if (Path == 0) // Noop
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000104 return false;
105 std::string File;
106 if (Path->isEmpty())
107 // Redirect empty paths to /dev/null
108 File = "/dev/null";
109 else
Chris Lattner74382b72009-08-23 22:45:37 +0000110 File = Path->str();
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000111
112 // Open the file
113 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
114 if (InFD == -1) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000115 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000116 + (FD == 0 ? "input" : "output"));
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000117 return true;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000118 }
119
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000120 // Install it as the requested FD
Chris Lattnercdff5f72010-03-14 23:16:45 +0000121 if (dup2(InFD, FD) == -1) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000122 MakeErrMsg(ErrMsg, "Cannot dup2");
Chris Lattnercdff5f72010-03-14 23:16:45 +0000123 close(InFD);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000124 return true;
125 }
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000126 close(InFD); // Close the original FD
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000127 return false;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000128}
129
Chris Lattner4f098b62010-04-18 04:14:37 +0000130#ifdef HAVE_POSIX_SPAWN
131static bool RedirectIO_PS(const Path *Path, int FD, std::string *ErrMsg,
Nick Lewyckyb7dfca92010-04-18 06:22:26 +0000132 posix_spawn_file_actions_t &FileActions) {
Chris Lattner4f098b62010-04-18 04:14:37 +0000133 if (Path == 0) // Noop
134 return false;
135 std::string File;
136 if (Path->isEmpty())
137 // Redirect empty paths to /dev/null
138 File = "/dev/null";
139 else
140 File = Path->str();
141
142 if (int Err = posix_spawn_file_actions_addopen(&FileActions, FD,
143 File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666))
144 return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
145 return false;
146}
147#endif
148
Duncan Sands68d29d02009-11-08 20:55:48 +0000149static void TimeOutHandler(int Sig) {
150}
151
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000152static void SetMemoryLimits (unsigned size)
153{
Chris Lattner6ae7bbb2010-02-12 00:37:46 +0000154#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000155 struct rlimit r;
156 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
157
158 // Heap size
159 getrlimit (RLIMIT_DATA, &r);
160 r.rlim_cur = limit;
161 setrlimit (RLIMIT_DATA, &r);
Gabor Greifaa6b7fd2007-07-06 10:31:27 +0000162#ifdef RLIMIT_RSS
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000163 // Resident set size.
164 getrlimit (RLIMIT_RSS, &r);
165 r.rlim_cur = limit;
166 setrlimit (RLIMIT_RSS, &r);
Reid Spencer2e40d032007-04-23 07:22:51 +0000167#endif
Devang Patel69bdf682007-06-04 15:28:57 +0000168#ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000169 // Virtual memory.
170 getrlimit (RLIMIT_AS, &r);
171 r.rlim_cur = limit;
172 setrlimit (RLIMIT_AS, &r);
173#endif
Devang Patel69bdf682007-06-04 15:28:57 +0000174#endif
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000175}
176
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000177bool
Chris Lattner4f098b62010-04-18 04:14:37 +0000178Program::Execute(const Path &path, const char **args, const char **envp,
179 const Path **redirects, unsigned memoryLimit,
180 std::string *ErrMsg) {
181 // If this OS has posix_spawn and there is no memory limit being implied, use
182 // posix_spawn. It is more efficient than fork/exec.
183#ifdef HAVE_POSIX_SPAWN
184 if (memoryLimit == 0) {
185 posix_spawn_file_actions_t FileActions;
186 posix_spawn_file_actions_init(&FileActions);
187
188 if (redirects) {
189 // Redirect stdin/stdout.
190 if (RedirectIO_PS(redirects[0], 0, ErrMsg, FileActions) ||
191 RedirectIO_PS(redirects[1], 1, ErrMsg, FileActions))
192 return false;
193 if (redirects[1] == 0 || redirects[2] == 0 ||
194 *redirects[1] != *redirects[2]) {
195 // Just redirect stderr
196 if (RedirectIO_PS(redirects[2], 2, ErrMsg, FileActions)) return false;
197 } else {
198 // If stdout and stderr should go to the same place, redirect stderr
199 // to the FD already open for stdout.
200 if (int Err = posix_spawn_file_actions_adddup2(&FileActions, 1, 2))
201 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
202 }
203 }
204
Nick Lewycky65238032010-04-18 07:07:48 +0000205#if !defined(__APPLE__)
206 if (!envp) envp = (const char**)environ;
207#endif
208
Chris Lattner4f098b62010-04-18 04:14:37 +0000209 pid_t PID;
210 int Err = posix_spawn(&PID, path.c_str(), &FileActions,
211 /*attrp*/0, (char**)args, (char**)envp);
212
213 posix_spawn_file_actions_destroy(&FileActions);
214
215 if (Err)
216 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
217
218 Data_ = reinterpret_cast<void*>(PID);
219 return true;
220 }
221#endif
222
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000223 if (!path.canExecute()) {
224 if (ErrMsg)
Chris Lattner74382b72009-08-23 22:45:37 +0000225 *ErrMsg = path.str() + " is not executable";
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000226 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000227 }
Reid Spencer52a7efa2004-08-29 19:20:41 +0000228
Reid Spencer52a7efa2004-08-29 19:20:41 +0000229 // Create a child process.
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000230 int child = fork();
231 switch (child) {
Reid Spencer52a7efa2004-08-29 19:20:41 +0000232 // An error occured: Return to the caller.
233 case -1:
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000234 MakeErrMsg(ErrMsg, "Couldn't fork");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000235 return false;
Reid Spencer52a7efa2004-08-29 19:20:41 +0000236
237 // Child process: Execute the program.
Reid Spencere2e24112004-12-14 04:18:51 +0000238 case 0: {
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000239 // Redirect file descriptors...
240 if (redirects) {
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000241 // Redirect stdin
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000242 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000243 // Redirect stdout
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000244 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
Mikhail Glushenkov234f6892009-07-17 20:38:17 +0000245 if (redirects[1] && redirects[2] &&
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000246 *(redirects[1]) == *(redirects[2])) {
247 // If stdout and stderr should go to the same place, redirect stderr
248 // to the FD already open for stdout.
249 if (-1 == dup2(1,2)) {
250 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000251 return false;
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000252 }
253 } else {
254 // Just redirect stderr
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000255 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000256 }
257 }
258
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000259 // Set memory limits
260 if (memoryLimit!=0) {
261 SetMemoryLimits(memoryLimit);
262 }
Mikhail Glushenkov234f6892009-07-17 20:38:17 +0000263
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000264 // Execute!
Evan Cheng2fafaf12006-06-09 20:43:11 +0000265 if (envp != 0)
Daniel Dunbar6db0a8b2009-08-04 20:32:25 +0000266 execve(path.c_str(), (char**)args, (char**)envp);
Evan Cheng2fafaf12006-06-09 20:43:11 +0000267 else
Daniel Dunbar6db0a8b2009-08-04 20:32:25 +0000268 execv(path.c_str(), (char**)args);
Dan Gohman33968522009-08-05 00:09:12 +0000269 // If the execve() failed, we should exit. Follow Unix protocol and
270 // return 127 if the executable was not found, and 126 otherwise.
271 // Use _exit rather than exit so that atexit functions and static
272 // object destructors cloned from the parent process aren't
273 // redundantly run, and so that any data buffered in stdio buffers
274 // cloned from the parent aren't redundantly written out.
275 _exit(errno == ENOENT ? 127 : 126);
Reid Spencere2e24112004-12-14 04:18:51 +0000276 }
Reid Spencer52a7efa2004-08-29 19:20:41 +0000277
278 // Parent process: Break out of the switch to do our processing.
279 default:
280 break;
281 }
282
Daniel Dunbar57d69032009-09-22 04:44:56 +0000283 Data_ = reinterpret_cast<void*>(child);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000284
285 return true;
286}
287
288int
289Program::Wait(unsigned secondsToWait,
290 std::string* ErrMsg)
291{
292#ifdef HAVE_SYS_WAIT_H
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000293 struct sigaction Act, Old;
294
Daniel Dunbar57d69032009-09-22 04:44:56 +0000295 if (Data_ == 0) {
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000296 MakeErrMsg(ErrMsg, "Process not started!");
297 return -1;
298 }
299
Duncan Sands68d29d02009-11-08 20:55:48 +0000300 // Install a timeout handler. The handler itself does nothing, but the simple
301 // fact of having a handler at all causes the wait below to return with EINTR,
302 // unlike if we used SIG_IGN.
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000303 if (secondsToWait) {
Chris Lattner47e47662010-04-10 17:54:51 +0000304#ifndef __HAIKU__
Duncan Sands68d29d02009-11-08 20:55:48 +0000305 Act.sa_sigaction = 0;
Chris Lattner47e47662010-04-10 17:54:51 +0000306#endif
Duncan Sands68d29d02009-11-08 20:55:48 +0000307 Act.sa_handler = TimeOutHandler;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000308 sigemptyset(&Act.sa_mask);
Duncan Sands68d29d02009-11-08 20:55:48 +0000309 Act.sa_flags = 0;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000310 sigaction(SIGALRM, &Act, &Old);
311 alarm(secondsToWait);
312 }
313
Reid Spencer52a7efa2004-08-29 19:20:41 +0000314 // Parent process: Wait for the child process to terminate.
315 int status;
Daniel Dunbar57d69032009-09-22 04:44:56 +0000316 uint64_t pid = reinterpret_cast<uint64_t>(Data_);
317 pid_t child = static_cast<pid_t>(pid);
Ted Kremenek8201ebd2009-10-22 22:16:17 +0000318 while (waitpid(pid, &status, 0) != child)
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000319 if (secondsToWait && errno == EINTR) {
320 // Kill the child.
321 kill(child, SIGKILL);
Mikhail Glushenkov234f6892009-07-17 20:38:17 +0000322
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000323 // Turn off the alarm and restore the signal handler
324 alarm(0);
325 sigaction(SIGALRM, &Old, 0);
326
327 // Wait for child to die
328 if (wait(&status) != child)
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000329 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
Devang Patela1e4bba2008-02-04 20:57:54 +0000330 else
331 MakeErrMsg(ErrMsg, "Child timed out", 0);
332
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000333 return -1; // Timeout detected
Devang Patela1e4bba2008-02-04 20:57:54 +0000334 } else if (errno != EINTR) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000335 MakeErrMsg(ErrMsg, "Error waiting for child process");
336 return -1;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000337 }
338
339 // We exited normally without timeout, so turn off the timer.
340 if (secondsToWait) {
341 alarm(0);
342 sigaction(SIGALRM, &Old, 0);
343 }
Reid Spencer52a7efa2004-08-29 19:20:41 +0000344
Reid Spencerd555f412005-12-22 20:00:16 +0000345 // Return the proper exit status. 0=success, >0 is programs' exit status,
346 // <0 means a signal was returned, -9999999 means the program dumped core.
347 int result = 0;
Chris Lattner0228c0f2006-07-12 22:37:18 +0000348 if (WIFEXITED(status))
Reid Spencerd555f412005-12-22 20:00:16 +0000349 result = WEXITSTATUS(status);
Reid Spencer52a7efa2004-08-29 19:20:41 +0000350 else if (WIFSIGNALED(status))
Reid Spencerd555f412005-12-22 20:00:16 +0000351 result = 0 - WTERMSIG(status);
352#ifdef WCOREDUMP
Chris Lattner0228c0f2006-07-12 22:37:18 +0000353 else if (WCOREDUMP(status))
Reid Spencerd555f412005-12-22 20:00:16 +0000354 result |= 0x01000000;
Reid Spencer52a7efa2004-08-29 19:20:41 +0000355#endif
Reid Spencerd555f412005-12-22 20:00:16 +0000356 return result;
357#else
358 return -99;
359#endif
Mikhail Glushenkov234f6892009-07-17 20:38:17 +0000360
Reid Spencer52a7efa2004-08-29 19:20:41 +0000361}
362
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000363bool
364Program::Kill(std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000365 if (Data_ == 0) {
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000366 MakeErrMsg(ErrMsg, "Process not started!");
367 return true;
368 }
369
Daniel Dunbar57d69032009-09-22 04:44:56 +0000370 uint64_t pid64 = reinterpret_cast<uint64_t>(Data_);
371 pid_t pid = static_cast<pid_t>(pid64);
372
373 if (kill(pid, SIGKILL) != 0) {
Mikhail Glushenkov8add2692009-09-09 09:51:47 +0000374 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
375 return true;
376 }
377
378 return false;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000379}
380
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000381bool Program::ChangeStdinToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000382 // Do nothing, as Unix doesn't differentiate between text and binary.
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000383 return false;
Reid Spencer32f55532006-06-07 23:18:34 +0000384}
385
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000386bool Program::ChangeStdoutToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000387 // Do nothing, as Unix doesn't differentiate between text and binary.
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000388 return false;
Reid Spencer32f55532006-06-07 23:18:34 +0000389}
390
Douglas Gregor21569cd2010-01-28 06:42:08 +0000391bool Program::ChangeStderrToBinary(){
392 // Do nothing, as Unix doesn't differentiate between text and binary.
393 return false;
394}
395
Reid Spencer52a7efa2004-08-29 19:20:41 +0000396}