22 #include "llvm/Config/config.h"
32 #if HAVE_SYS_RESOURCE_H
33 #include <sys/resource.h>
44 #ifdef HAVE_POSIX_SPAWN
47 #if defined(__APPLE__)
48 #include <TargetConditionals.h>
51 #if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
52 #define USE_NSGETENVIRON 1
54 #define USE_NSGETENVIRON 0
58 extern char **environ;
60 #include <crt_externs.h>
74 if (
Name.contains(
'/'))
75 return std::string(
Name);
79 if (
const char *PathEnv = std::getenv(
"PATH")) {
80 SplitString(PathEnv, EnvironmentPaths,
":");
81 Paths = EnvironmentPaths;
84 for (
auto Path : Paths) {
92 return std::string(FilePath.str());
105 File = std::string(*Path);
108 int InFD = open(
File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
110 MakeErrMsg(ErrMsg,
"Cannot open file '" + File +
"' for "
111 + (FD == 0 ?
"input" :
"output"));
116 if (dup2(InFD, FD) == -1) {
125 #ifdef HAVE_POSIX_SPAWN
126 static bool RedirectIO_PS(
const std::string *Path,
int FD, std::string *ErrMsg,
127 posix_spawn_file_actions_t *FileActions) {
137 if (
int Err = posix_spawn_file_actions_addopen(
138 FileActions, FD, File,
139 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
140 return MakeErrMsg(ErrMsg,
"Cannot posix_spawn_file_actions_addopen", Err);
145 static void TimeOutHandler(
int Sig) {
148 static void SetMemoryLimits(
unsigned size) {
149 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
151 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (
size) * 1048576;
154 getrlimit (RLIMIT_DATA, &r);
156 setrlimit (RLIMIT_DATA, &r);
159 getrlimit (RLIMIT_RSS, &r);
161 setrlimit (RLIMIT_RSS, &r);
166 static std::vector<const char *>
168 std::vector<const char *>
Result;
171 Result.push_back(
nullptr);
178 unsigned MemoryLimit, std::string *ErrMsg,
182 *ErrMsg = std::string(
"Executable \"") + Program.
str() +
183 std::string(
"\" doesn't exist!");
187 assert(!AffinityMask &&
"Starting a process with an affinity mask is "
188 "currently not supported on Unix!");
192 std::vector<const char *> ArgVector, EnvVector;
193 const char **Argv =
nullptr;
194 const char **Envp =
nullptr;
195 ArgVector = toNullTerminatedCStringArray(
Args, Saver);
196 Argv = ArgVector.data();
198 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
199 Envp = EnvVector.data();
204 #ifdef HAVE_POSIX_SPAWN
205 if (MemoryLimit == 0) {
206 posix_spawn_file_actions_t FileActionsStore;
207 posix_spawn_file_actions_t *FileActions =
nullptr;
212 std::string RedirectsStorage[3];
214 if (!Redirects.empty()) {
215 assert(Redirects.size() == 3);
216 std::string *RedirectsStr[3] = {
nullptr,
nullptr,
nullptr};
217 for (
int I = 0;
I < 3; ++
I) {
219 RedirectsStorage[
I] = std::string(*Redirects[
I]);
220 RedirectsStr[
I] = &RedirectsStorage[
I];
224 FileActions = &FileActionsStore;
225 posix_spawn_file_actions_init(FileActions);
228 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
229 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
231 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
233 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
238 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
239 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
244 #if !USE_NSGETENVIRON
245 Envp =
const_cast<const char **
>(environ);
248 Envp =
const_cast<const char **
>(*_NSGetEnviron());
251 constexpr
int maxRetries = 8;
257 Err = posix_spawn(&PID, Program.
str().c_str(), FileActions,
258 nullptr,
const_cast<char **
>(Argv),
259 const_cast<char **
>(Envp));
260 }
while (Err == EINTR && ++retries < maxRetries);
263 posix_spawn_file_actions_destroy(FileActions);
266 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
286 if (!Redirects.empty()) {
288 if (RedirectIO(Redirects[0], 0, ErrMsg)) {
return false; }
290 if (RedirectIO(Redirects[1], 1, ErrMsg)) {
return false; }
291 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
294 if (-1 == dup2(1,2)) {
295 MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout");
300 if (RedirectIO(Redirects[2], 2, ErrMsg)) {
return false; }
305 if (MemoryLimit!=0) {
306 SetMemoryLimits(MemoryLimit);
310 std::string PathStr = std::string(Program);
312 execve(PathStr.c_str(),
const_cast<char **
>(Argv),
313 const_cast<char **
>(Envp));
315 execv(PathStr.c_str(),
const_cast<char **
>(Argv));
322 _exit(errno == ENOENT ? 127 : 126);
342 static pid_t (wait4)(pid_t pid,
int *
status,
int options,
struct rusage *usage);
350 extern "C" pid_t (wait4)(pid_t pid,
int *
status,
int options,
351 struct rusage *usage);
353 pid_t (llvm::sys::wait4)(pid_t pid,
int *
status,
int options,
354 struct rusage *usage) {
355 assert(pid > 0 &&
"Only expecting to handle actual PID values!");
356 assert((
options & ~WNOHANG) == 0 &&
"Expecting WNOHANG at most!");
357 assert(usage &&
"Expecting usage collection!");
365 siginfo_t WaitIdInfo;
366 WaitIdInfo.si_pid = 0;
368 waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED |
options);
370 if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
373 assert(WaitIdInfo.si_pid == pid);
382 ProcessInfo
llvm::sys::Wait(
const ProcessInfo &PI,
unsigned SecondsToWait,
383 bool WaitUntilTerminates, std::string *ErrMsg,
385 struct sigaction Act, Old;
386 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
388 int WaitPidOptions = 0;
389 pid_t ChildPid = PI.Pid;
390 if (WaitUntilTerminates) {
392 }
else if (SecondsToWait) {
396 memset(&Act, 0,
sizeof(Act));
397 Act.sa_handler = TimeOutHandler;
398 sigemptyset(&Act.sa_mask);
399 sigaction(SIGALRM, &Act, &Old);
401 alarm(SecondsToWait);
402 }
else if (SecondsToWait == 0)
403 WaitPidOptions = WNOHANG;
407 ProcessInfo WaitResult;
413 WaitResult.Pid = sys::wait4(ChildPid, &
status, WaitPidOptions, &
Info);
414 }
while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
416 if (WaitResult.Pid != PI.Pid) {
417 if (WaitResult.Pid == 0) {
421 if (SecondsToWait && errno == EINTR) {
423 kill(PI.Pid, SIGKILL);
427 sigaction(SIGALRM, &Old,
nullptr);
432 if (wait(&
status) != ChildPid)
433 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
437 WaitResult.ReturnCode = -2;
439 }
else if (errno != EINTR) {
440 MakeErrMsg(ErrMsg,
"Error waiting for child process");
441 WaitResult.ReturnCode = -1;
448 if (SecondsToWait && !WaitUntilTerminates) {
450 sigaction(SIGALRM, &Old,
nullptr);
460 *ProcStat = ProcessStatistics{UserT + KernelT, UserT, PeakMemory};
468 WaitResult.ReturnCode =
result;
473 WaitResult.ReturnCode = -1;
478 *ErrMsg =
"Program could not be executed";
479 WaitResult.ReturnCode = -1;
482 }
else if (WIFSIGNALED(
status)) {
484 *ErrMsg = strsignal(WTERMSIG(
status));
487 *ErrMsg +=
" (core dumped)";
492 WaitResult.ReturnCode = -2;
500 return std::error_code();
506 return std::error_code();
511 return std::error_code();
516 return std::error_code();
538 static long ArgMax = sysconf(_SC_ARG_MAX);
541 static long ArgMin = _POSIX_ARG_MAX;
544 long EffectiveArgMax = 128 * 1024;
546 if (EffectiveArgMax > ArgMax)
547 EffectiveArgMax = ArgMax;
548 else if (EffectiveArgMax < ArgMin)
549 EffectiveArgMax = ArgMin;
556 long HalfArgMax = EffectiveArgMax / 2;
558 size_t ArgLength = Program.
size() + 1;
565 if (
Arg.size() >= (32 * 4096))
568 ArgLength +=
Arg.size() + 1;
569 if (ArgLength >
size_t(HalfArgMax)) {