22 #include <llvm/Config/config.h>
26 #if HAVE_SYS_RESOURCE_H
27 #include <sys/resource.h>
38 #ifdef HAVE_POSIX_SPAWN
40 #define _RESTRICT_KYWD
43 #if !defined(__APPLE__)
44 extern char **environ;
46 #include <crt_externs.h>
60 if (progName.length() == 0)
62 std::string temp = progName;
65 if (progName.find(
'/') != std::string::npos)
72 const char *PathStr =
getenv(
"PATH");
77 size_t PathLen =
strlen(PathStr);
80 const char *Colon = std::find(PathStr, PathStr+PathLen,
':');
83 SmallString<128> FilePath(PathStr,Colon);
86 return FilePath.str();
89 PathLen -= Colon-PathStr;
93 while (*PathStr ==
':') {
101 static bool RedirectIO(
const StringRef *Path,
int FD, std::string* ErrMsg) {
112 int InFD =
open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
114 MakeErrMsg(ErrMsg,
"Cannot open file '" + File +
"' for "
115 + (FD == 0 ?
"input" :
"output"));
120 if (dup2(InFD, FD) == -1) {
129 #ifdef HAVE_POSIX_SPAWN
130 static bool RedirectIO_PS(
const std::string *Path,
int FD, std::string *ErrMsg,
131 posix_spawn_file_actions_t *FileActions) {
139 File = Path->c_str();
141 if (
int Err = posix_spawn_file_actions_addopen(
142 FileActions, FD, File,
143 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
144 return MakeErrMsg(ErrMsg,
"Cannot dup2", Err);
149 static void TimeOutHandler(
int Sig) {
152 static void SetMemoryLimits (
unsigned size)
154 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
156 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
159 getrlimit (RLIMIT_DATA, &r);
161 setrlimit (RLIMIT_DATA, &r);
164 getrlimit (RLIMIT_RSS, &r);
166 setrlimit (RLIMIT_RSS, &r);
168 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
171 #if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD
173 getrlimit (RLIMIT_AS, &r);
175 setrlimit (RLIMIT_AS, &r);
183 static bool Execute(ProcessInfo &PI, StringRef Program,
const char **args,
184 const char **envp,
const StringRef **redirects,
185 unsigned memoryLimit, std::string *ErrMsg) {
188 *ErrMsg = std::string(
"Executable \"") + Program.str() +
189 std::string(
"\" doesn't exist!");
195 #ifdef HAVE_POSIX_SPAWN
196 if (memoryLimit == 0) {
197 posix_spawn_file_actions_t FileActionsStore;
198 posix_spawn_file_actions_t *FileActions = 0;
203 std::string RedirectsStorage[3];
206 std::string *RedirectsStr[3] = {0, 0, 0};
207 for (
int I = 0;
I < 3; ++
I) {
209 RedirectsStorage[
I] = *redirects[
I];
210 RedirectsStr[
I] = &RedirectsStorage[
I];
214 FileActions = &FileActionsStore;
215 posix_spawn_file_actions_init(FileActions);
218 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
219 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
221 if (redirects[1] == 0 || redirects[2] == 0 ||
222 *redirects[1] != *redirects[2]) {
224 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
229 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
230 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
235 #if !defined(__APPLE__)
236 envp =
const_cast<const char **
>(environ);
239 envp =
const_cast<const char **
>(*_NSGetEnviron());
245 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions, 0,
246 const_cast<char **
>(args), const_cast<char **>(envp));
249 posix_spawn_file_actions_destroy(FileActions);
252 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
273 if (RedirectIO(redirects[0], 0, ErrMsg)) {
return false; }
275 if (RedirectIO(redirects[1], 1, ErrMsg)) {
return false; }
276 if (redirects[1] && redirects[2] &&
277 *(redirects[1]) == *(redirects[2])) {
280 if (-1 == dup2(1,2)) {
281 MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout");
286 if (RedirectIO(redirects[2], 2, ErrMsg)) {
return false; }
291 if (memoryLimit!=0) {
292 SetMemoryLimits(memoryLimit);
296 std::string PathStr = Program;
298 execve(PathStr.c_str(),
299 const_cast<char **
>(args),
300 const_cast<char **>(envp));
302 execv(PathStr.c_str(),
303 const_cast<char **
>(args));
310 _exit(errno == ENOENT ? 127 : 126);
325 ProcessInfo
sys::Wait(
const ProcessInfo &PI,
unsigned SecondsToWait,
326 bool WaitUntilTerminates, std::string *ErrMsg) {
327 #ifdef HAVE_SYS_WAIT_H
328 struct sigaction Act, Old;
329 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
331 int WaitPidOptions = 0;
332 pid_t ChildPid = PI.Pid;
333 if (WaitUntilTerminates) {
336 }
else if (SecondsToWait) {
340 memset(&Act, 0,
sizeof(Act));
341 Act.sa_handler = TimeOutHandler;
342 sigemptyset(&Act.sa_mask);
343 sigaction(SIGALRM, &Act, &Old);
344 alarm(SecondsToWait);
345 }
else if (SecondsToWait == 0)
346 WaitPidOptions = WNOHANG;
350 ProcessInfo WaitResult;
351 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
352 if (WaitResult.Pid != PI.Pid) {
353 if (WaitResult.Pid == 0) {
357 if (SecondsToWait && errno == EINTR) {
359 kill(PI.Pid, SIGKILL);
363 sigaction(SIGALRM, &Old, 0);
366 if (wait(&status) != ChildPid)
367 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
371 WaitResult.ReturnCode = -2;
373 }
else if (errno != EINTR) {
374 MakeErrMsg(ErrMsg,
"Error waiting for child process");
375 WaitResult.ReturnCode = -1;
382 if (SecondsToWait && !WaitUntilTerminates) {
384 sigaction(SIGALRM, &Old, 0);
392 WaitResult.ReturnCode = result;
397 WaitResult.ReturnCode = -1;
402 *ErrMsg =
"Program could not be executed";
403 WaitResult.ReturnCode = -1;
406 }
else if (WIFSIGNALED(status)) {
408 *ErrMsg = strsignal(WTERMSIG(status));
410 if (WCOREDUMP(status))
411 *ErrMsg +=
" (core dumped)";
416 WaitResult.ReturnCode = -2;
420 *ErrMsg =
"Program::Wait is not implemented on this platform yet!";
421 WaitResult.ReturnCode = -2;
442 static long ArgMax = sysconf(_SC_ARG_MAX);
451 size_t ArgLength = 0;
452 for (ArrayRef<const char*>::iterator
I = Args.begin(), E = Args.end();
455 if (ArgLength >
size_t(ArgMax)) {
bool can_execute(const Twine &Path)
Can we execute this file?
int open(const char *path, int oflag, ... );
error_code ChangeStdinToBinary()
bool argumentsFitWithinSystemLimits(ArrayRef< const char * > Args)
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
error_code status(const Twine &path, file_status &result)
Get file status as if by POSIX stat().
error_code ChangeStderrToBinary()
static bool Execute(ProcessInfo &PI, StringRef Program, const char **args, const char **env, const StringRef **Redirects, unsigned memoryLimit, std::string *ErrMsg)
#define WEXITSTATUS(stat_val)
#define WIFEXITED(stat_val)
size_t strlen(const char *s);
bool MakeErrMsg(std::string *ErrMsg, const std::string &prefix)
std::string FindProgramByName(const std::string &name)
Construct a Program by finding it by name.
ProcessInfo Wait(const ProcessInfo &PI, unsigned SecondsToWait, bool WaitUntilTerminates, std::string *ErrMsg=0)
bool exists(file_status status)
Does file exist?
char *getenv(const char *name);
error_code make_error_code(errc _e)
error_code ChangeStdoutToBinary()