22#include "llvm/Config/config.h"
32#include <sys/resource.h>
38#ifdef HAVE_POSIX_SPAWN
42#include <TargetConditionals.h>
45#if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
46#define USE_NSGETENVIRON 1
48#define USE_NSGETENVIRON 0
54#include <crt_externs.h>
61ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
68 if (
Name.contains(
'/'))
69 return std::string(
Name);
73 if (
const char *PathEnv = std::getenv(
"PATH")) {
74 SplitString(PathEnv, EnvironmentPaths,
":");
75 Paths = EnvironmentPaths;
78 for (
auto Path : Paths) {
84 sys::path::append(FilePath,
Name);
85 if (sys::fs::can_execute(FilePath.c_str()))
86 return std::string(FilePath);
88 return errc::no_such_file_or_directory;
91static bool RedirectIO(std::optional<StringRef> Path,
int FD, std::string *ErrMsg) {
99 File = std::string(*Path);
102 int InFD = open(
File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666);
104 MakeErrMsg(ErrMsg,
"Cannot open file '" + File +
"' for " +
105 (FD == 0 ?
"input" :
"output"));
110 if (dup2(InFD, FD) == -1) {
119#ifdef HAVE_POSIX_SPAWN
120static bool RedirectIO_PS(
const std::string *Path,
int FD, std::string *ErrMsg,
121 posix_spawn_file_actions_t *FileActions) {
131 if (
int Err = posix_spawn_file_actions_addopen(
132 FileActions, FD, File, FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
133 return MakeErrMsg(ErrMsg,
"Cannot posix_spawn_file_actions_addopen", Err);
138static void TimeOutHandler(
int Sig) {}
140static void SetMemoryLimits(
unsigned size) {
142 __typeof__(r.rlim_cur) limit = (__typeof__(r.rlim_cur))(size)*1048576;
145 getrlimit(RLIMIT_DATA, &r);
147 setrlimit(RLIMIT_DATA, &r);
150 getrlimit(RLIMIT_RSS, &r);
152 setrlimit(RLIMIT_RSS, &r);
156static std::vector<const char *>
158 std::vector<const char *>
Result;
161 Result.push_back(
nullptr);
168 ArrayRef<std::optional<StringRef>> Redirects,
169 unsigned MemoryLimit, std::string *ErrMsg,
170 BitVector *AffinityMask,
bool DetachProcess) {
173 *ErrMsg = std::string(
"Executable \"") + Program.
str() +
174 std::string(
"\" doesn't exist!");
178 assert(!AffinityMask &&
"Starting a process with an affinity mask is "
179 "currently not supported on Unix!");
183 std::vector<const char *>
ArgVector, EnvVector;
184 const char **Argv =
nullptr;
185 const char **Envp =
nullptr;
186 ArgVector = toNullTerminatedCStringArray(Args, Saver);
189 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
190 Envp = EnvVector.data();
195#ifdef HAVE_POSIX_SPAWN
197 if (MemoryLimit == 0 && !DetachProcess) {
198 posix_spawn_file_actions_t FileActionsStore;
199 posix_spawn_file_actions_t *FileActions =
nullptr;
204 std::string RedirectsStorage[3];
206 if (!Redirects.empty()) {
207 assert(Redirects.size() == 3);
208 std::string *RedirectsStr[3] = {
nullptr,
nullptr,
nullptr};
209 for (
int I = 0;
I < 3; ++
I) {
211 RedirectsStorage[
I] = std::string(*Redirects[
I]);
212 RedirectsStr[
I] = &RedirectsStorage[
I];
216 FileActions = &FileActionsStore;
217 posix_spawn_file_actions_init(FileActions);
220 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
221 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
223 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
225 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
230 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
231 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
237 Envp =
const_cast<const char **
>(environ);
240 Envp =
const_cast<const char **
>(*_NSGetEnviron());
243 constexpr int maxRetries = 8;
249 Err = posix_spawn(&PID, Program.
str().c_str(), FileActions,
250 nullptr,
const_cast<char **
>(Argv),
251 const_cast<char **
>(Envp));
252 }
while (Err == EINTR && ++retries < maxRetries);
255 posix_spawn_file_actions_destroy(FileActions);
258 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
278 if (!Redirects.empty()) {
280 if (RedirectIO(Redirects[0], 0, ErrMsg)) {
284 if (RedirectIO(Redirects[1], 1, ErrMsg)) {
287 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
290 if (-1 == dup2(1, 2)) {
291 MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout");
296 if (RedirectIO(Redirects[2], 2, ErrMsg)) {
304 if (::setsid() == -1) {
305 MakeErrMsg(ErrMsg,
"Could not detach process, ::setsid failed");
311 if (MemoryLimit != 0) {
312 SetMemoryLimits(MemoryLimit);
316 std::string PathStr = std::string(Program);
318 execve(PathStr.c_str(),
const_cast<char **
>(Argv),
319 const_cast<char **
>(Envp));
321 execv(PathStr.c_str(),
const_cast<char **
>(Argv));
328 _exit(errno == ENOENT ? 127 : 126);
346static pid_t(wait4)(pid_t pid,
int *
status,
int options,
struct rusage *usage);
347#elif !defined(__Fuchsia__)
357 struct rusage *usage);
360 struct rusage *usage) {
361 assert(pid > 0 &&
"Only expecting to handle actual PID values!");
362 assert((options & ~WNOHANG) == 0 &&
"Expecting WNOHANG at most!");
363 assert(usage &&
"Expecting usage collection!");
366 if (!(options & WNOHANG))
367 return ::wait4(pid, status, options, usage);
371 siginfo_t WaitIdInfo;
372 WaitIdInfo.si_pid = 0;
374 waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
376 if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
379 assert(WaitIdInfo.si_pid == pid);
384 return ::wait4(pid, status, options & ~WNOHANG, usage);
389 std::optional<unsigned> SecondsToWait,
391 std::optional<ProcessStatistics> *ProcStat,
393 struct sigaction Act, Old;
394 assert(PI.
Pid &&
"invalid pid to wait on, process not started?");
396 int WaitPidOptions = 0;
397 pid_t ChildPid = PI.
Pid;
398 bool WaitUntilTerminates =
false;
399 if (!SecondsToWait) {
400 WaitUntilTerminates =
true;
402 if (*SecondsToWait == 0)
403 WaitPidOptions = WNOHANG;
408 memset(&Act, 0,
sizeof(Act));
409 Act.sa_handler = TimeOutHandler;
410 sigemptyset(&Act.sa_mask);
411 sigaction(SIGALRM, &Act, &Old);
413 alarm(*SecondsToWait);
425 WaitResult.
Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &
Info);
426 }
while (WaitUntilTerminates && WaitResult.
Pid == -1 && errno == EINTR);
429 if (WaitResult.
Pid != PI.
Pid) {
430 if (WaitResult.
Pid == 0) {
434 if (SecondsToWait && errno == EINTR && !Polling) {
436 kill(PI.
Pid, SIGKILL);
440 sigaction(SIGALRM, &Old,
nullptr);
445 if (wait(&status) != ChildPid)
446 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
452 }
else if (errno != EINTR) {
453 MakeErrMsg(ErrMsg,
"Error waiting for child process");
461 if (SecondsToWait && !WaitUntilTerminates) {
463 sigaction(SIGALRM, &Old,
nullptr);
471#if !defined(__HAIKU__) && !defined(__MVS__)
481 if (WIFEXITED(status)) {
482 result = WEXITSTATUS(status);
493 *ErrMsg =
"Program could not be executed";
497 }
else if (WIFSIGNALED(status)) {
499 *ErrMsg = strsignal(WTERMSIG(status));
501 if (WCOREDUMP(status))
502 *ErrMsg +=
" (core dumped)";
513 if (!(Flags & fs::OF_Text))
515 return std::error_code();
519 if (!(Flags & fs::OF_Text))
521 return std::error_code();
526 return disablezOSAutoConversion(STDIN_FILENO);
529 return std::error_code();
535 return std::error_code();
558 static long ArgMax = sysconf(_SC_ARG_MAX);
561 static long ArgMin = _POSIX_ARG_MAX;
564 long EffectiveArgMax = 128 * 1024;
566 if (EffectiveArgMax > ArgMax)
567 EffectiveArgMax = ArgMax;
568 else if (EffectiveArgMax < ArgMin)
569 EffectiveArgMax = ArgMin;
576 long HalfArgMax = EffectiveArgMax / 2;
578 size_t ArgLength = Program.
size() + 1;
585 if (Arg.size() >= (32 * 4096))
588 ArgLength += Arg.size() + 1;
589 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.