22#include "llvm/Config/config.h"
32#if HAVE_SYS_RESOURCE_H
33#include <sys/resource.h>
42#ifdef HAVE_POSIX_SPAWN
46#include <TargetConditionals.h>
49#if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
50#define USE_NSGETENVIRON 1
52#define USE_NSGETENVIRON 0
58#include <crt_externs.h>
65ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
72 if (
Name.contains(
'/'))
73 return std::string(
Name);
77 if (
const char *PathEnv = std::getenv(
"PATH")) {
78 SplitString(PathEnv, EnvironmentPaths,
":");
79 Paths = EnvironmentPaths;
82 for (
auto Path : Paths) {
88 sys::path::append(FilePath,
Name);
89 if (sys::fs::can_execute(FilePath.c_str()))
90 return std::string(FilePath);
92 return errc::no_such_file_or_directory;
95static bool RedirectIO(std::optional<StringRef> Path,
int FD, std::string *ErrMsg) {
103 File = std::string(*Path);
106 int InFD = open(
File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666);
108 MakeErrMsg(ErrMsg,
"Cannot open file '" + File +
"' for " +
109 (FD == 0 ?
"input" :
"output"));
114 if (dup2(InFD, FD) == -1) {
123#ifdef HAVE_POSIX_SPAWN
124static bool RedirectIO_PS(
const std::string *Path,
int FD, std::string *ErrMsg,
125 posix_spawn_file_actions_t *FileActions) {
135 if (
int Err = posix_spawn_file_actions_addopen(
136 FileActions, FD, File, FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
137 return MakeErrMsg(ErrMsg,
"Cannot posix_spawn_file_actions_addopen", Err);
142static void TimeOutHandler(
int Sig) {}
144static void SetMemoryLimits(
unsigned size) {
145#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
147 __typeof__(r.rlim_cur) limit = (__typeof__(r.rlim_cur))(size)*1048576;
150 getrlimit(RLIMIT_DATA, &r);
152 setrlimit(RLIMIT_DATA, &r);
155 getrlimit(RLIMIT_RSS, &r);
157 setrlimit(RLIMIT_RSS, &r);
162static std::vector<const char *>
164 std::vector<const char *>
Result;
167 Result.push_back(
nullptr);
174 ArrayRef<std::optional<StringRef>> Redirects,
175 unsigned MemoryLimit, std::string *ErrMsg,
176 BitVector *AffinityMask,
bool DetachProcess) {
179 *ErrMsg = std::string(
"Executable \"") + Program.
str() +
180 std::string(
"\" doesn't exist!");
184 assert(!AffinityMask &&
"Starting a process with an affinity mask is "
185 "currently not supported on Unix!");
189 std::vector<const char *>
ArgVector, EnvVector;
190 const char **Argv =
nullptr;
191 const char **Envp =
nullptr;
192 ArgVector = toNullTerminatedCStringArray(Args, Saver);
195 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
196 Envp = EnvVector.data();
201#ifdef HAVE_POSIX_SPAWN
203 if (MemoryLimit == 0 && !DetachProcess) {
204 posix_spawn_file_actions_t FileActionsStore;
205 posix_spawn_file_actions_t *FileActions =
nullptr;
210 std::string RedirectsStorage[3];
212 if (!Redirects.empty()) {
213 assert(Redirects.size() == 3);
214 std::string *RedirectsStr[3] = {
nullptr,
nullptr,
nullptr};
215 for (
int I = 0;
I < 3; ++
I) {
217 RedirectsStorage[
I] = std::string(*Redirects[
I]);
218 RedirectsStr[
I] = &RedirectsStorage[
I];
222 FileActions = &FileActionsStore;
223 posix_spawn_file_actions_init(FileActions);
226 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
227 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
229 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
231 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
236 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
237 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
243 Envp =
const_cast<const char **
>(environ);
246 Envp =
const_cast<const char **
>(*_NSGetEnviron());
249 constexpr int maxRetries = 8;
255 Err = posix_spawn(&PID, Program.
str().c_str(), FileActions,
256 nullptr,
const_cast<char **
>(Argv),
257 const_cast<char **
>(Envp));
258 }
while (Err == EINTR && ++retries < maxRetries);
261 posix_spawn_file_actions_destroy(FileActions);
264 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
284 if (!Redirects.empty()) {
286 if (RedirectIO(Redirects[0], 0, ErrMsg)) {
290 if (RedirectIO(Redirects[1], 1, ErrMsg)) {
293 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
296 if (-1 == dup2(1, 2)) {
297 MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout");
302 if (RedirectIO(Redirects[2], 2, ErrMsg)) {
310 if (::setsid() == -1) {
311 MakeErrMsg(ErrMsg,
"Could not detach process, ::setsid failed");
317 if (MemoryLimit != 0) {
318 SetMemoryLimits(MemoryLimit);
322 std::string PathStr = std::string(Program);
324 execve(PathStr.c_str(),
const_cast<char **
>(Argv),
325 const_cast<char **
>(Envp));
327 execv(PathStr.c_str(),
const_cast<char **
>(Argv));
334 _exit(errno == ENOENT ? 127 : 126);
352static pid_t(wait4)(pid_t pid,
int *
status,
int options,
struct rusage *usage);
353#elif !defined(__Fuchsia__)
363 struct rusage *usage);
366 struct rusage *usage) {
367 assert(pid > 0 &&
"Only expecting to handle actual PID values!");
368 assert((options & ~WNOHANG) == 0 &&
"Expecting WNOHANG at most!");
369 assert(usage &&
"Expecting usage collection!");
372 if (!(options & WNOHANG))
373 return ::wait4(pid, status, options, usage);
377 siginfo_t WaitIdInfo;
378 WaitIdInfo.si_pid = 0;
380 waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
382 if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
385 assert(WaitIdInfo.si_pid == pid);
390 return ::wait4(pid, status, options & ~WNOHANG, usage);
395 std::optional<unsigned> SecondsToWait,
397 std::optional<ProcessStatistics> *ProcStat,
399 struct sigaction Act, Old;
400 assert(PI.
Pid &&
"invalid pid to wait on, process not started?");
402 int WaitPidOptions = 0;
403 pid_t ChildPid = PI.
Pid;
404 bool WaitUntilTerminates =
false;
405 if (!SecondsToWait) {
406 WaitUntilTerminates =
true;
408 if (*SecondsToWait == 0)
409 WaitPidOptions = WNOHANG;
414 memset(&Act, 0,
sizeof(Act));
415 Act.sa_handler = TimeOutHandler;
416 sigemptyset(&Act.sa_mask);
417 sigaction(SIGALRM, &Act, &Old);
419 alarm(*SecondsToWait);
431 WaitResult.
Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &
Info);
432 }
while (WaitUntilTerminates && WaitResult.
Pid == -1 && errno == EINTR);
435 if (WaitResult.
Pid != PI.
Pid) {
436 if (WaitResult.
Pid == 0) {
440 if (SecondsToWait && errno == EINTR && !Polling) {
442 kill(PI.
Pid, SIGKILL);
446 sigaction(SIGALRM, &Old,
nullptr);
451 if (wait(&status) != ChildPid)
452 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
458 }
else if (errno != EINTR) {
459 MakeErrMsg(ErrMsg,
"Error waiting for child process");
467 if (SecondsToWait && !WaitUntilTerminates) {
469 sigaction(SIGALRM, &Old,
nullptr);
477#if !defined(__HAIKU__) && !defined(__MVS__)
487 if (WIFEXITED(status)) {
488 result = WEXITSTATUS(status);
499 *ErrMsg =
"Program could not be executed";
503 }
else if (WIFSIGNALED(status)) {
505 *ErrMsg = strsignal(WTERMSIG(status));
507 if (WCOREDUMP(status))
508 *ErrMsg +=
" (core dumped)";
519 if (!(Flags & fs::OF_Text))
521 return std::error_code();
525 if (!(Flags & fs::OF_Text))
527 return std::error_code();
532 return disablezOSAutoConversion(STDIN_FILENO);
535 return std::error_code();
541 return std::error_code();
564 static long ArgMax = sysconf(_SC_ARG_MAX);
567 static long ArgMin = _POSIX_ARG_MAX;
570 long EffectiveArgMax = 128 * 1024;
572 if (EffectiveArgMax > ArgMax)
573 EffectiveArgMax = ArgMax;
574 else if (EffectiveArgMax < ArgMin)
575 EffectiveArgMax = ArgMin;
582 long HalfArgMax = EffectiveArgMax / 2;
584 size_t ArgLength = Program.
size() + 1;
591 if (Arg.size() >= (32 * 4096))
594 ArgLength += Arg.size() + 1;
595 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.