22#include "llvm/Config/config.h"
34#if HAVE_SYS_RESOURCE_H
35#include <sys/resource.h>
46#ifdef HAVE_POSIX_SPAWN
50#include <TargetConditionals.h>
53#if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
54#define USE_NSGETENVIRON 1
56#define USE_NSGETENVIRON 0
62#include <crt_externs.h>
69ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
76 if (
Name.contains(
'/'))
77 return std::string(
Name);
81 if (
const char *PathEnv = std::getenv(
"PATH")) {
82 SplitString(PathEnv, EnvironmentPaths,
":");
83 Paths = EnvironmentPaths;
86 for (
auto Path : Paths) {
92 sys::path::append(FilePath,
Name);
93 if (sys::fs::can_execute(FilePath.c_str()))
94 return std::string(FilePath);
96 return errc::no_such_file_or_directory;
99static bool RedirectIO(std::optional<StringRef> Path,
int FD, std::string *ErrMsg) {
107 File = std::string(*Path);
110 int InFD = open(
File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666);
112 MakeErrMsg(ErrMsg,
"Cannot open file '" + File +
"' for " +
113 (FD == 0 ?
"input" :
"output"));
118 if (dup2(InFD, FD) == -1) {
127#ifdef HAVE_POSIX_SPAWN
128static bool RedirectIO_PS(
const std::string *Path,
int FD, std::string *ErrMsg,
129 posix_spawn_file_actions_t *FileActions) {
139 if (
int Err = posix_spawn_file_actions_addopen(
140 FileActions, FD, File, FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
141 return MakeErrMsg(ErrMsg,
"Cannot posix_spawn_file_actions_addopen", Err);
146static void TimeOutHandler(
int Sig) {}
148static 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);
166static std::vector<const char *>
168 std::vector<const char *>
Result;
171 Result.push_back(
nullptr);
178 ArrayRef<std::optional<StringRef>> Redirects,
179 unsigned MemoryLimit, std::string *ErrMsg,
180 BitVector *AffinityMask,
bool DetachProcess) {
183 *ErrMsg = std::string(
"Executable \"") + Program.
str() +
184 std::string(
"\" doesn't exist!");
188 assert(!AffinityMask &&
"Starting a process with an affinity mask is "
189 "currently not supported on Unix!");
193 std::vector<const char *>
ArgVector, EnvVector;
194 const char **Argv =
nullptr;
195 const char **Envp =
nullptr;
196 ArgVector = toNullTerminatedCStringArray(Args, Saver);
199 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
200 Envp = EnvVector.data();
205#ifdef HAVE_POSIX_SPAWN
207 if (MemoryLimit == 0 && !DetachProcess) {
208 posix_spawn_file_actions_t FileActionsStore;
209 posix_spawn_file_actions_t *FileActions =
nullptr;
214 std::string RedirectsStorage[3];
216 if (!Redirects.empty()) {
217 assert(Redirects.size() == 3);
218 std::string *RedirectsStr[3] = {
nullptr,
nullptr,
nullptr};
219 for (
int I = 0;
I < 3; ++
I) {
221 RedirectsStorage[
I] = std::string(*Redirects[
I]);
222 RedirectsStr[
I] = &RedirectsStorage[
I];
226 FileActions = &FileActionsStore;
227 posix_spawn_file_actions_init(FileActions);
230 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
231 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
233 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
235 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
240 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
241 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
247 Envp =
const_cast<const char **
>(environ);
250 Envp =
const_cast<const char **
>(*_NSGetEnviron());
253 constexpr int maxRetries = 8;
259 Err = posix_spawn(&PID, Program.
str().c_str(), FileActions,
260 nullptr,
const_cast<char **
>(Argv),
261 const_cast<char **
>(Envp));
262 }
while (Err == EINTR && ++retries < maxRetries);
265 posix_spawn_file_actions_destroy(FileActions);
268 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
288 if (!Redirects.empty()) {
290 if (RedirectIO(Redirects[0], 0, ErrMsg)) {
294 if (RedirectIO(Redirects[1], 1, ErrMsg)) {
297 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
300 if (-1 == dup2(1, 2)) {
301 MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout");
306 if (RedirectIO(Redirects[2], 2, ErrMsg)) {
314 if (::setsid() == -1) {
315 MakeErrMsg(ErrMsg,
"Could not detach process, ::setsid failed");
321 if (MemoryLimit != 0) {
322 SetMemoryLimits(MemoryLimit);
326 std::string PathStr = std::string(Program);
328 execve(PathStr.c_str(),
const_cast<char **
>(Argv),
329 const_cast<char **
>(Envp));
331 execv(PathStr.c_str(),
const_cast<char **
>(Argv));
338 _exit(errno == ENOENT ? 127 : 126);
356static pid_t(wait4)(pid_t pid,
int *
status,
int options,
struct rusage *usage);
357#elif !defined(__Fuchsia__)
367 struct rusage *usage);
370 struct rusage *usage) {
371 assert(pid > 0 &&
"Only expecting to handle actual PID values!");
372 assert((options & ~WNOHANG) == 0 &&
"Expecting WNOHANG at most!");
373 assert(usage &&
"Expecting usage collection!");
376 if (!(options & WNOHANG))
377 return ::wait4(pid, status, options, usage);
381 siginfo_t WaitIdInfo;
382 WaitIdInfo.si_pid = 0;
384 waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
386 if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
389 assert(WaitIdInfo.si_pid == pid);
394 return ::wait4(pid, status, options & ~WNOHANG, usage);
399 std::optional<unsigned> SecondsToWait,
401 std::optional<ProcessStatistics> *ProcStat,
403 struct sigaction Act, Old;
404 assert(PI.
Pid &&
"invalid pid to wait on, process not started?");
406 int WaitPidOptions = 0;
407 pid_t ChildPid = PI.
Pid;
408 bool WaitUntilTerminates =
false;
409 if (!SecondsToWait) {
410 WaitUntilTerminates =
true;
412 if (*SecondsToWait == 0)
413 WaitPidOptions = WNOHANG;
418 memset(&Act, 0,
sizeof(Act));
419 Act.sa_handler = TimeOutHandler;
420 sigemptyset(&Act.sa_mask);
421 sigaction(SIGALRM, &Act, &Old);
423 alarm(*SecondsToWait);
435 WaitResult.
Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &
Info);
436 }
while (WaitUntilTerminates && WaitResult.
Pid == -1 && errno == EINTR);
439 if (WaitResult.
Pid != PI.
Pid) {
440 if (WaitResult.
Pid == 0) {
444 if (SecondsToWait && errno == EINTR && !Polling) {
446 kill(PI.
Pid, SIGKILL);
450 sigaction(SIGALRM, &Old,
nullptr);
455 if (wait(&status) != ChildPid)
456 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
462 }
else if (errno != EINTR) {
463 MakeErrMsg(ErrMsg,
"Error waiting for child process");
471 if (SecondsToWait && !WaitUntilTerminates) {
473 sigaction(SIGALRM, &Old,
nullptr);
481#if !defined(__HAIKU__) && !defined(__MVS__)
491 if (WIFEXITED(status)) {
492 result = WEXITSTATUS(status);
503 *ErrMsg =
"Program could not be executed";
507 }
else if (WIFSIGNALED(status)) {
509 *ErrMsg = strsignal(WTERMSIG(status));
511 if (WCOREDUMP(status))
512 *ErrMsg +=
" (core dumped)";
523 if (!(Flags & fs::OF_Text))
525 return std::error_code();
529 if (!(Flags & fs::OF_Text))
531 return std::error_code();
536 return disableAutoConversion(STDIN_FILENO);
539 return std::error_code();
545 return std::error_code();
568 static long ArgMax = sysconf(_SC_ARG_MAX);
571 static long ArgMin = _POSIX_ARG_MAX;
574 long EffectiveArgMax = 128 * 1024;
576 if (EffectiveArgMax > ArgMax)
577 EffectiveArgMax = ArgMax;
578 else if (EffectiveArgMax < ArgMin)
579 EffectiveArgMax = ArgMin;
586 long HalfArgMax = EffectiveArgMax / 2;
588 size_t ArgLength = Program.
size() + 1;
595 if (Arg.size() >= (32 * 4096))
598 ArgLength += Arg.size() + 1;
599 if (ArgLength >
size_t(HalfArgMax)) {
Analysis containing CSE Info
static bool Execute(ProcessInfo &PI, StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env, ArrayRef< std::optional< StringRef > > Redirects, unsigned MemoryLimit, std::string *ErrMsg, BitVector *AffinityMask, bool DetachProcess)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static bool MakeErrMsg(std::string *ErrMsg, const std::string &prefix, int errnum=-1)
This function builds an error message into ErrMsg using the prefix string and the Unix error number g...
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
bool empty() const
empty - Check if the array is empty.
Allocate memory in an ever growing pool, as if by bump-pointer.
Represents either an error or a value T.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
std::string str() const
str - Get the contents as an std::string.
constexpr size_t size() const
size - Get the string size.
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Saves strings in the provided stable storage and returns a StringRef with a stable character pointer.
StringRef save(const char *S)
A raw_ostream that writes to a file descriptor.
std::vector< std::string > ArgVector
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
bool exists(const basic_file_status &status)
Does file exist?
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
std::chrono::nanoseconds toDuration(FILETIME Time)
std::string StrError()
Returns a string representation of the errno value, using whatever thread-safe variant of strerror() ...
std::error_code ChangeStdinMode(fs::OpenFlags Flags)
std::error_code ChangeStdinToBinary()
ProcessInfo Wait(const ProcessInfo &PI, std::optional< unsigned > SecondsToWait, std::string *ErrMsg=nullptr, std::optional< ProcessStatistics > *ProcStat=nullptr, bool Polling=false)
This function waits for the process specified by PI to finish.
bool commandLineFitsWithinSystemLimits(StringRef Program, ArrayRef< StringRef > Args)
Return true if the given arguments fit within system-specific argument length limits.
std::error_code ChangeStdoutMode(fs::OpenFlags Flags)
WindowsEncodingMethod
File encoding options when writing contents that a non-UTF8 tool will read (on Windows systems).
std::error_code ChangeStdoutToBinary()
std::error_code writeFileWithEncoding(StringRef FileName, StringRef Contents, WindowsEncodingMethod Encoding=WEM_UTF8)
Saves the UTF8-encoded contents string into the file FileName using a specific encoding.
This is an optimization pass for GlobalISel generic memory operations.
std::error_code make_error_code(BitcodeError E)
This struct encapsulates information about a process.
process_t Process
The process identifier.
int ReturnCode
Platform-dependent process object.
This struct encapsulates information about a process execution.