blob: 476e90b38b22f351a3ab854e6dc1feba5818419a [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>
35#endif
Reid Spencer52a7efa2004-08-29 19:20:41 +000036
Nick Lewyckyb7dfca92010-04-18 06:22:26 +000037extern char **environ;
38
Reid Spencer52a7efa2004-08-29 19:20:41 +000039namespace llvm {
40using namespace sys;
41
Daniel Dunbar57d69032009-09-22 04:44:56 +000042Program::Program() : Data_(0) {}
43
44Program::~Program() {}
45
46unsigned Program::GetPid() const {
47 uint64_t pid = reinterpret_cast<uint64_t>(Data_);
48 return static_cast<unsigned>(pid);
49}
50
Reid Spencer52a7efa2004-08-29 19:20:41 +000051// This function just uses the PATH environment variable to find the program.
Reid Spencer25659432004-09-13 21:48:44 +000052Path
Reid Spencer52a7efa2004-08-29 19:20:41 +000053Program::FindProgramByName(const std::string& progName) {
54
55 // Check some degenerate cases
56 if (progName.length() == 0) // no program
Reid Spencer25659432004-09-13 21:48:44 +000057 return Path();
58 Path temp;
Reid Spencerdd04df02005-07-07 23:21:43 +000059 if (!temp.set(progName)) // invalid name
Reid Spencer25659432004-09-13 21:48:44 +000060 return Path();
Benjamin Kramerb0facb12009-07-28 22:08:15 +000061 // Use the given path verbatim if it contains any slashes; this matches
62 // the behavior of sh(1) and friends.
Dan Gohmana87861e2009-07-28 23:25:18 +000063 if (progName.find('/') != std::string::npos)
Reid Spencer52a7efa2004-08-29 19:20:41 +000064 return temp;
65
Dan Gohman88abb892009-08-05 17:32:39 +000066 // At this point, the file name does not contain slashes. Search for it
67 // through the directories specified in the PATH environment variable.
Mikhail Glushenkov234f6892009-07-17 20:38:17 +000068
Reid Spencer52a7efa2004-08-29 19:20:41 +000069 // Get the path. If its empty, we can't do anything to find it.
70 const char *PathStr = getenv("PATH");
Mikhail Glushenkov234f6892009-07-17 20:38:17 +000071 if (PathStr == 0)
Reid Spencer25659432004-09-13 21:48:44 +000072 return Path();
Reid Spencer52a7efa2004-08-29 19:20:41 +000073
74 // Now we have a colon separated list of directories to search; try them.
Evan Cheng34cd4a42008-05-05 18:30:58 +000075 size_t PathLen = strlen(PathStr);
Reid Spencer52a7efa2004-08-29 19:20:41 +000076 while (PathLen) {
77 // Find the first colon...
78 const char *Colon = std::find(PathStr, PathStr+PathLen, ':');
79
80 // Check to see if this first directory contains the executable...
Reid Spencer25659432004-09-13 21:48:44 +000081 Path FilePath;
Reid Spencerdd04df02005-07-07 23:21:43 +000082 if (FilePath.set(std::string(PathStr,Colon))) {
83 FilePath.appendComponent(progName);
Reid Spencerc7f08322005-07-07 18:21:42 +000084 if (FilePath.canExecute())
Reid Spencer52a7efa2004-08-29 19:20:41 +000085 return FilePath; // Found the executable!
86 }
87
88 // Nope it wasn't in this directory, check the next path in the list!
89 PathLen -= Colon-PathStr;
90 PathStr = Colon;
91
92 // Advance past duplicate colons
93 while (*PathStr == ':') {
94 PathStr++;
95 PathLen--;
96 }
97 }
Reid Spencer25659432004-09-13 21:48:44 +000098 return Path();
Reid Spencer52a7efa2004-08-29 19:20:41 +000099}
100
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000101static bool RedirectIO(const Path *Path, int FD, std::string* ErrMsg) {
Chris Lattner4f098b62010-04-18 04:14:37 +0000102 if (Path == 0) // Noop
Matthijs Kooijman905261e2008-06-12 10:47:18 +0000103 return false;
104 std::string File;
105 if (Path->isEmpty())
106 // Redirect empty paths to /dev/null
107 File = "/dev/null";
108 else
Chris Lattner74382b72009-08-23 22:45:37 +0000109 File = Path->str();
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000110
111 // Open the file
112 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
113 if (InFD == -1) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000114 MakeErrMsg(ErrMsg, "Cannot open file '" + File + "' for "
Daniel Dunbara7f2a9e2009-04-20 20:50:13 +0000115 + (FD == 0 ? "input" : "output"));
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000116 return true;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000117 }
118
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000119 // Install it as the requested FD
Chris Lattnercdff5f72010-03-14 23:16:45 +0000120 if (dup2(InFD, FD) == -1) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000121 MakeErrMsg(ErrMsg, "Cannot dup2");
Chris Lattnercdff5f72010-03-14 23:16:45 +0000122 close(InFD);
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000123 return true;
124 }
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000125 close(InFD); // Close the original FD
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000126 return false;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000127}
128
Chris Lattner4f098b62010-04-18 04:14:37 +0000129#ifdef HAVE_POSIX_SPAWN
130static bool RedirectIO_PS(const Path *Path, int FD, std::string *ErrMsg,
Nick Lewyckyb7dfca92010-04-18 06:22:26 +0000131 posix_spawn_file_actions_t &FileActions) {
Chris Lattner4f098b62010-04-18 04:14:37 +0000132 if (Path == 0) // Noop
133 return false;
134 std::string File;
135 if (Path->isEmpty())
136 // Redirect empty paths to /dev/null
137 File = "/dev/null";
138 else
139 File = Path->str();
140
141 if (int Err = posix_spawn_file_actions_addopen(&FileActions, FD,
142 File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666))
143 return MakeErrMsg(ErrMsg, "Cannot dup2", Err);
144 return false;
145}
146#endif
147
Duncan Sands68d29d02009-11-08 20:55:48 +0000148static void TimeOutHandler(int Sig) {
149}
150
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000151static void SetMemoryLimits (unsigned size)
152{
Chris Lattner6ae7bbb2010-02-12 00:37:46 +0000153#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000154 struct rlimit r;
155 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
156
157 // Heap size
158 getrlimit (RLIMIT_DATA, &r);
159 r.rlim_cur = limit;
160 setrlimit (RLIMIT_DATA, &r);
Gabor Greifaa6b7fd2007-07-06 10:31:27 +0000161#ifdef RLIMIT_RSS
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000162 // Resident set size.
163 getrlimit (RLIMIT_RSS, &r);
164 r.rlim_cur = limit;
165 setrlimit (RLIMIT_RSS, &r);
Reid Spencer2e40d032007-04-23 07:22:51 +0000166#endif
Devang Patel69bdf682007-06-04 15:28:57 +0000167#ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000168 // Virtual memory.
169 getrlimit (RLIMIT_AS, &r);
170 r.rlim_cur = limit;
171 setrlimit (RLIMIT_AS, &r);
172#endif
Devang Patel69bdf682007-06-04 15:28:57 +0000173#endif
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000174}
175
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000176bool
Chris Lattner4f098b62010-04-18 04:14:37 +0000177Program::Execute(const Path &path, const char **args, const char **envp,
178 const Path **redirects, unsigned memoryLimit,
179 std::string *ErrMsg) {
180 // If this OS has posix_spawn and there is no memory limit being implied, use
181 // posix_spawn. It is more efficient than fork/exec.
182#ifdef HAVE_POSIX_SPAWN
183 if (memoryLimit == 0) {
184 posix_spawn_file_actions_t FileActions;
185 posix_spawn_file_actions_init(&FileActions);
186
187 if (redirects) {
188 // Redirect stdin/stdout.
189 if (RedirectIO_PS(redirects[0], 0, ErrMsg, FileActions) ||
190 RedirectIO_PS(redirects[1], 1, ErrMsg, FileActions))
191 return false;
192 if (redirects[1] == 0 || redirects[2] == 0 ||
193 *redirects[1] != *redirects[2]) {
194 // Just redirect stderr
195 if (RedirectIO_PS(redirects[2], 2, ErrMsg, FileActions)) return false;
196 } else {
197 // If stdout and stderr should go to the same place, redirect stderr
198 // to the FD already open for stdout.
199 if (int Err = posix_spawn_file_actions_adddup2(&FileActions, 1, 2))
200 return !MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout", Err);
201 }
202 }
203
204 pid_t PID;
Nick Lewyckyb7dfca92010-04-18 06:22:26 +0000205 if (!envp) envp = (const char**)environ;
Chris Lattner4f098b62010-04-18 04:14:37 +0000206 int Err = posix_spawn(&PID, path.c_str(), &FileActions,
207 /*attrp*/0, (char**)args, (char**)envp);
208
209 posix_spawn_file_actions_destroy(&FileActions);
210
211 if (Err)
212 return !MakeErrMsg(ErrMsg, "posix_spawn failed", Err);
213
214 Data_ = reinterpret_cast<void*>(PID);
215 return true;
216 }
217#endif
218
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000219 if (!path.canExecute()) {
220 if (ErrMsg)
Chris Lattner74382b72009-08-23 22:45:37 +0000221 *ErrMsg = path.str() + " is not executable";
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000222 return false;
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000223 }
Reid Spencer52a7efa2004-08-29 19:20:41 +0000224
Reid Spencer52a7efa2004-08-29 19:20:41 +0000225 // Create a child process.
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000226 int child = fork();
227 switch (child) {
Reid Spencer52a7efa2004-08-29 19:20:41 +0000228 // An error occured: Return to the caller.
229 case -1:
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000230 MakeErrMsg(ErrMsg, "Couldn't fork");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000231 return false;
Reid Spencer52a7efa2004-08-29 19:20:41 +0000232
233 // Child process: Execute the program.
Reid Spencere2e24112004-12-14 04:18:51 +0000234 case 0: {
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000235 // Redirect file descriptors...
236 if (redirects) {
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000237 // Redirect stdin
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000238 if (RedirectIO(redirects[0], 0, ErrMsg)) { return false; }
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000239 // Redirect stdout
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000240 if (RedirectIO(redirects[1], 1, ErrMsg)) { return false; }
Mikhail Glushenkov234f6892009-07-17 20:38:17 +0000241 if (redirects[1] && redirects[2] &&
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000242 *(redirects[1]) == *(redirects[2])) {
243 // If stdout and stderr should go to the same place, redirect stderr
244 // to the FD already open for stdout.
245 if (-1 == dup2(1,2)) {
246 MakeErrMsg(ErrMsg, "Can't redirect stderr to stdout");
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000247 return false;
Matthijs Kooijmancf45ca02008-06-12 12:53:35 +0000248 }
249 } else {
250 // Just redirect stderr
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000251 if (RedirectIO(redirects[2], 2, ErrMsg)) { return false; }
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000252 }
253 }
254
Anton Korobeynikov9ba8a762007-02-16 19:11:07 +0000255 // Set memory limits
256 if (memoryLimit!=0) {
257 SetMemoryLimits(memoryLimit);
258 }
Mikhail Glushenkov234f6892009-07-17 20:38:17 +0000259
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000260 // Execute!
Evan Cheng2fafaf12006-06-09 20:43:11 +0000261 if (envp != 0)
Daniel Dunbar6db0a8b2009-08-04 20:32:25 +0000262 execve(path.c_str(), (char**)args, (char**)envp);
Evan Cheng2fafaf12006-06-09 20:43:11 +0000263 else
Daniel Dunbar6db0a8b2009-08-04 20:32:25 +0000264 execv(path.c_str(), (char**)args);
Dan Gohman33968522009-08-05 00:09:12 +0000265 // If the execve() failed, we should exit. Follow Unix protocol and
266 // return 127 if the executable was not found, and 126 otherwise.
267 // Use _exit rather than exit so that atexit functions and static
268 // object destructors cloned from the parent process aren't
269 // redundantly run, and so that any data buffered in stdio buffers
270 // cloned from the parent aren't redundantly written out.
271 _exit(errno == ENOENT ? 127 : 126);
Reid Spencere2e24112004-12-14 04:18:51 +0000272 }
Reid Spencer52a7efa2004-08-29 19:20:41 +0000273
274 // Parent process: Break out of the switch to do our processing.
275 default:
276 break;
277 }
278
Daniel Dunbar57d69032009-09-22 04:44:56 +0000279 Data_ = reinterpret_cast<void*>(child);
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000280
281 return true;
282}
283
284int
285Program::Wait(unsigned secondsToWait,
286 std::string* ErrMsg)
287{
288#ifdef HAVE_SYS_WAIT_H
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000289 struct sigaction Act, Old;
290
Daniel Dunbar57d69032009-09-22 04:44:56 +0000291 if (Data_ == 0) {
Mikhail Glushenkov31406192009-07-18 21:43:12 +0000292 MakeErrMsg(ErrMsg, "Process not started!");
293 return -1;
294 }
295
Duncan Sands68d29d02009-11-08 20:55:48 +0000296 // Install a timeout handler. The handler itself does nothing, but the simple
297 // fact of having a handler at all causes the wait below to return with EINTR,
298 // unlike if we used SIG_IGN.
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000299 if (secondsToWait) {
Chris Lattner47e47662010-04-10 17:54:51 +0000300#ifndef __HAIKU__
Duncan Sands68d29d02009-11-08 20:55:48 +0000301 Act.sa_sigaction = 0;
Chris Lattner47e47662010-04-10 17:54:51 +0000302#endif
Duncan Sands68d29d02009-11-08 20:55:48 +0000303 Act.sa_handler = TimeOutHandler;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000304 sigemptyset(&Act.sa_mask);
Duncan Sands68d29d02009-11-08 20:55:48 +0000305 Act.sa_flags = 0;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000306 sigaction(SIGALRM, &Act, &Old);
307 alarm(secondsToWait);
308 }
309
Reid Spencer52a7efa2004-08-29 19:20:41 +0000310 // Parent process: Wait for the child process to terminate.
311 int status;
Daniel Dunbar57d69032009-09-22 04:44:56 +0000312 uint64_t pid = reinterpret_cast<uint64_t>(Data_);
313 pid_t child = static_cast<pid_t>(pid);
Ted Kremenek8201ebd2009-10-22 22:16:17 +0000314 while (waitpid(pid, &status, 0) != child)
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000315 if (secondsToWait && errno == EINTR) {
316 // Kill the child.
317 kill(child, SIGKILL);
Mikhail Glushenkov234f6892009-07-17 20:38:17 +0000318
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000319 // Turn off the alarm and restore the signal handler
320 alarm(0);
321 sigaction(SIGALRM, &Old, 0);
322
323 // Wait for child to die
324 if (wait(&status) != child)
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000325 MakeErrMsg(ErrMsg, "Child timed out but wouldn't die");
Devang Patela1e4bba2008-02-04 20:57:54 +0000326 else
327 MakeErrMsg(ErrMsg, "Child timed out", 0);
328
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000329 return -1; // Timeout detected
Devang Patela1e4bba2008-02-04 20:57:54 +0000330 } else if (errno != EINTR) {
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000331 MakeErrMsg(ErrMsg, "Error waiting for child process");
332 return -1;
Reid Spencer2a7d9e92004-12-19 18:00:44 +0000333 }
334
335 // We exited normally without timeout, so turn off the timer.
336 if (secondsToWait) {
337 alarm(0);
338 sigaction(SIGALRM, &Old, 0);
339 }
Reid Spencer52a7efa2004-08-29 19:20:41 +0000340
Reid Spencerd555f412005-12-22 20:00:16 +0000341 // Return the proper exit status. 0=success, >0 is programs' exit status,
342 // <0 means a signal was returned, -9999999 means the program dumped core.
343 int result = 0;
Chris Lattner0228c0f2006-07-12 22:37:18 +0000344 if (WIFEXITED(status))
Reid Spencerd555f412005-12-22 20:00:16 +0000345 result = WEXITSTATUS(status);
Reid Spencer52a7efa2004-08-29 19:20:41 +0000346 else if (WIFSIGNALED(status))
Reid Spencerd555f412005-12-22 20:00:16 +0000347 result = 0 - WTERMSIG(status);
348#ifdef WCOREDUMP
Chris Lattner0228c0f2006-07-12 22:37:18 +0000349 else if (WCOREDUMP(status))
Reid Spencerd555f412005-12-22 20:00:16 +0000350 result |= 0x01000000;
Reid Spencer52a7efa2004-08-29 19:20:41 +0000351#endif
Reid Spencerd555f412005-12-22 20:00:16 +0000352 return result;
353#else
354 return -99;
355#endif
Mikhail Glushenkov234f6892009-07-17 20:38:17 +0000356
Reid Spencer52a7efa2004-08-29 19:20:41 +0000357}
358
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000359bool
360Program::Kill(std::string* ErrMsg) {
Daniel Dunbar57d69032009-09-22 04:44:56 +0000361 if (Data_ == 0) {
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000362 MakeErrMsg(ErrMsg, "Process not started!");
363 return true;
364 }
365
Daniel Dunbar57d69032009-09-22 04:44:56 +0000366 uint64_t pid64 = reinterpret_cast<uint64_t>(Data_);
367 pid_t pid = static_cast<pid_t>(pid64);
368
369 if (kill(pid, SIGKILL) != 0) {
Mikhail Glushenkov8add2692009-09-09 09:51:47 +0000370 MakeErrMsg(ErrMsg, "The process couldn't be killed!");
371 return true;
372 }
373
374 return false;
Mikhail Glushenkova6072022009-09-08 19:50:27 +0000375}
376
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000377bool Program::ChangeStdinToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000378 // Do nothing, as Unix doesn't differentiate between text and binary.
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000379 return false;
Reid Spencer32f55532006-06-07 23:18:34 +0000380}
381
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000382bool Program::ChangeStdoutToBinary(){
Reid Spencer32f55532006-06-07 23:18:34 +0000383 // Do nothing, as Unix doesn't differentiate between text and binary.
Reid Spencer4ce5dc62006-08-21 06:02:44 +0000384 return false;
Reid Spencer32f55532006-06-07 23:18:34 +0000385}
386
Douglas Gregor21569cd2010-01-28 06:42:08 +0000387bool Program::ChangeStderrToBinary(){
388 // Do nothing, as Unix doesn't differentiate between text and binary.
389 return false;
390}
391
Reid Spencer52a7efa2004-08-29 19:20:41 +0000392}