22#include "llvm/Config/config.h"
32#if HAVE_SYS_RESOURCE_H
33#include <sys/resource.h>
40#ifdef HAVE_POSIX_SPAWN
44#include <TargetConditionals.h>
47#if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
48#define USE_NSGETENVIRON 1
50#define USE_NSGETENVIRON 0
56#include <crt_externs.h>
63ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
70 if (
Name.contains(
'/'))
71 return std::string(
Name);
75 if (
const char *PathEnv = std::getenv(
"PATH")) {
76 SplitString(PathEnv, EnvironmentPaths,
":");
77 Paths = EnvironmentPaths;
80 for (
auto Path : Paths) {
86 sys::path::append(FilePath,
Name);
87 if (sys::fs::can_execute(FilePath.c_str()))
88 return std::string(FilePath);
90 return errc::no_such_file_or_directory;
93static bool RedirectIO(std::optional<StringRef> Path,
int FD, std::string *ErrMsg) {
101 File = std::string(*Path);
104 int InFD = open(
File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666);
106 MakeErrMsg(ErrMsg,
"Cannot open file '" + File +
"' for " +
107 (FD == 0 ?
"input" :
"output"));
112 if (dup2(InFD, FD) == -1) {
121#ifdef HAVE_POSIX_SPAWN
122static bool RedirectIO_PS(
const std::string *Path,
int FD, std::string *ErrMsg,
123 posix_spawn_file_actions_t *FileActions) {
133 if (
int Err = posix_spawn_file_actions_addopen(
134 FileActions, FD, File, FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
135 return MakeErrMsg(ErrMsg,
"Cannot posix_spawn_file_actions_addopen", Err);
140static void TimeOutHandler(
int Sig) {}
142static void SetMemoryLimits(
unsigned size) {
143#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
145 __typeof__(r.rlim_cur) limit = (__typeof__(r.rlim_cur))(size)*1048576;
148 getrlimit(RLIMIT_DATA, &r);
150 setrlimit(RLIMIT_DATA, &r);
153 getrlimit(RLIMIT_RSS, &r);
155 setrlimit(RLIMIT_RSS, &r);
160static std::vector<const char *>
162 std::vector<const char *>
Result;
165 Result.push_back(
nullptr);
172 ArrayRef<std::optional<StringRef>> Redirects,
173 unsigned MemoryLimit, std::string *ErrMsg,
174 BitVector *AffinityMask,
bool DetachProcess) {
177 *ErrMsg = std::string(
"Executable \"") + Program.
str() +
178 std::string(
"\" doesn't exist!");
182 assert(!AffinityMask &&
"Starting a process with an affinity mask is "
183 "currently not supported on Unix!");
187 std::vector<const char *>
ArgVector, EnvVector;
188 const char **Argv =
nullptr;
189 const char **Envp =
nullptr;
190 ArgVector = toNullTerminatedCStringArray(Args, Saver);
193 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
194 Envp = EnvVector.data();
199#ifdef HAVE_POSIX_SPAWN
201 if (MemoryLimit == 0 && !DetachProcess) {
202 posix_spawn_file_actions_t FileActionsStore;
203 posix_spawn_file_actions_t *FileActions =
nullptr;
208 std::string RedirectsStorage[3];
210 if (!Redirects.empty()) {
211 assert(Redirects.size() == 3);
212 std::string *RedirectsStr[3] = {
nullptr,
nullptr,
nullptr};
213 for (
int I = 0;
I < 3; ++
I) {
215 RedirectsStorage[
I] = std::string(*Redirects[
I]);
216 RedirectsStr[
I] = &RedirectsStorage[
I];
220 FileActions = &FileActionsStore;
221 posix_spawn_file_actions_init(FileActions);
224 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
225 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
227 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
229 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
234 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
235 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
241 Envp =
const_cast<const char **
>(environ);
244 Envp =
const_cast<const char **
>(*_NSGetEnviron());
247 constexpr int maxRetries = 8;
253 Err = posix_spawn(&PID, Program.
str().c_str(), FileActions,
254 nullptr,
const_cast<char **
>(Argv),
255 const_cast<char **
>(Envp));
256 }
while (Err == EINTR && ++retries < maxRetries);
259 posix_spawn_file_actions_destroy(FileActions);
262 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
282 if (!Redirects.empty()) {
284 if (RedirectIO(Redirects[0], 0, ErrMsg)) {
288 if (RedirectIO(Redirects[1], 1, ErrMsg)) {
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)) {
308 if (::setsid() == -1) {
309 MakeErrMsg(ErrMsg,
"Could not detach process, ::setsid failed");
315 if (MemoryLimit != 0) {
316 SetMemoryLimits(MemoryLimit);
320 std::string PathStr = std::string(Program);
322 execve(PathStr.c_str(),
const_cast<char **
>(Argv),
323 const_cast<char **
>(Envp));
325 execv(PathStr.c_str(),
const_cast<char **
>(Argv));
332 _exit(errno == ENOENT ? 127 : 126);
350static pid_t(wait4)(pid_t pid,
int *
status,
int options,
struct rusage *usage);
351#elif !defined(__Fuchsia__)
361 struct rusage *usage);
364 struct rusage *usage) {
365 assert(pid > 0 &&
"Only expecting to handle actual PID values!");
366 assert((options & ~WNOHANG) == 0 &&
"Expecting WNOHANG at most!");
367 assert(usage &&
"Expecting usage collection!");
370 if (!(options & WNOHANG))
371 return ::wait4(pid, status, options, usage);
375 siginfo_t WaitIdInfo;
376 WaitIdInfo.si_pid = 0;
378 waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
380 if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
383 assert(WaitIdInfo.si_pid == pid);
388 return ::wait4(pid, status, options & ~WNOHANG, usage);
393 std::optional<unsigned> SecondsToWait,
395 std::optional<ProcessStatistics> *ProcStat,
397 struct sigaction Act, Old;
398 assert(PI.
Pid &&
"invalid pid to wait on, process not started?");
400 int WaitPidOptions = 0;
401 pid_t ChildPid = PI.
Pid;
402 bool WaitUntilTerminates =
false;
403 if (!SecondsToWait) {
404 WaitUntilTerminates =
true;
406 if (*SecondsToWait == 0)
407 WaitPidOptions = WNOHANG;
412 memset(&Act, 0,
sizeof(Act));
413 Act.sa_handler = TimeOutHandler;
414 sigemptyset(&Act.sa_mask);
415 sigaction(SIGALRM, &Act, &Old);
417 alarm(*SecondsToWait);
429 WaitResult.
Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &
Info);
430 }
while (WaitUntilTerminates && WaitResult.
Pid == -1 && errno == EINTR);
433 if (WaitResult.
Pid != PI.
Pid) {
434 if (WaitResult.
Pid == 0) {
438 if (SecondsToWait && errno == EINTR && !Polling) {
440 kill(PI.
Pid, SIGKILL);
444 sigaction(SIGALRM, &Old,
nullptr);
449 if (wait(&status) != ChildPid)
450 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
456 }
else if (errno != EINTR) {
457 MakeErrMsg(ErrMsg,
"Error waiting for child process");
465 if (SecondsToWait && !WaitUntilTerminates) {
467 sigaction(SIGALRM, &Old,
nullptr);
475#if !defined(__HAIKU__) && !defined(__MVS__)
485 if (WIFEXITED(status)) {
486 result = WEXITSTATUS(status);
497 *ErrMsg =
"Program could not be executed";
501 }
else if (WIFSIGNALED(status)) {
503 *ErrMsg = strsignal(WTERMSIG(status));
505 if (WCOREDUMP(status))
506 *ErrMsg +=
" (core dumped)";
517 if (!(Flags & fs::OF_Text))
519 return std::error_code();
523 if (!(Flags & fs::OF_Text))
525 return std::error_code();
530 return disablezOSAutoConversion(STDIN_FILENO);
533 return std::error_code();
539 return std::error_code();
562 static long ArgMax = sysconf(_SC_ARG_MAX);
565 static long ArgMin = _POSIX_ARG_MAX;
568 long EffectiveArgMax = 128 * 1024;
570 if (EffectiveArgMax > ArgMax)
571 EffectiveArgMax = ArgMax;
572 else if (EffectiveArgMax < ArgMin)
573 EffectiveArgMax = ArgMin;
580 long HalfArgMax = EffectiveArgMax / 2;
582 size_t ArgLength = Program.
size() + 1;
589 if (Arg.size() >= (32 * 4096))
592 ArgLength += Arg.size() + 1;
593 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.