22#include "llvm/Config/config.h"
32#if HAVE_SYS_RESOURCE_H
33#include <sys/resource.h>
44#ifdef HAVE_POSIX_SPAWN
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
60#include <crt_externs.h>
67ProcessInfo::ProcessInfo() : Pid(0), ReturnCode(0) {}
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) {
90 sys::path::append(FilePath,
Name);
91 if (sys::fs::can_execute(FilePath.c_str()))
92 return std::string(FilePath.str());
94 return errc::no_such_file_or_directory;
97static bool RedirectIO(std::optional<StringRef> Path,
int FD, std::string *ErrMsg) {
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
126static 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, FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
139 return MakeErrMsg(ErrMsg,
"Cannot posix_spawn_file_actions_addopen", Err);
144static void TimeOutHandler(
int Sig) {}
146static void SetMemoryLimits(
unsigned size) {
147#if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
149 __typeof__(r.rlim_cur) limit = (__typeof__(r.rlim_cur))(size)*1048576;
152 getrlimit(RLIMIT_DATA, &r);
154 setrlimit(RLIMIT_DATA, &r);
157 getrlimit(RLIMIT_RSS, &r);
159 setrlimit(RLIMIT_RSS, &r);
164static std::vector<const char *>
166 std::vector<const char *>
Result;
169 Result.push_back(
nullptr);
175 ArrayRef<std::optional<StringRef>> Redirects,
176 unsigned MemoryLimit, std::string *ErrMsg,
180 *ErrMsg = std::string(
"Executable \"") + Program.
str() +
181 std::string(
"\" doesn't exist!");
185 assert(!AffinityMask &&
"Starting a process with an affinity mask is "
186 "currently not supported on Unix!");
190 std::vector<const char *>
ArgVector, EnvVector;
191 const char **Argv =
nullptr;
192 const char **Envp =
nullptr;
193 ArgVector = toNullTerminatedCStringArray(Args, Saver);
196 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
197 Envp = EnvVector.data();
202#ifdef HAVE_POSIX_SPAWN
203 if (MemoryLimit == 0) {
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)) {
309 if (MemoryLimit != 0) {
310 SetMemoryLimits(MemoryLimit);
314 std::string PathStr = std::string(Program);
316 execve(PathStr.c_str(),
const_cast<char **
>(Argv),
317 const_cast<char **
>(Envp));
319 execv(PathStr.c_str(),
const_cast<char **
>(Argv));
326 _exit(errno == ENOENT ? 127 : 126);
346static pid_t(wait4)(pid_t pid,
int *
status,
int options,
struct rusage *usage);
355 struct rusage *usage);
358 struct rusage *usage) {
359 assert(pid > 0 &&
"Only expecting to handle actual PID values!");
360 assert((options & ~WNOHANG) == 0 &&
"Expecting WNOHANG at most!");
361 assert(usage &&
"Expecting usage collection!");
364 if (!(options & WNOHANG))
365 return ::wait4(pid, status, options, usage);
369 siginfo_t WaitIdInfo;
370 WaitIdInfo.si_pid = 0;
372 waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
374 if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
377 assert(WaitIdInfo.si_pid == pid);
382 return ::wait4(pid, status, options & ~WNOHANG, usage);
387 std::optional<unsigned> SecondsToWait,
389 std::optional<ProcessStatistics> *ProcStat,
391 struct sigaction Act, Old;
392 assert(PI.
Pid &&
"invalid pid to wait on, process not started?");
394 int WaitPidOptions = 0;
395 pid_t ChildPid = PI.
Pid;
396 bool WaitUntilTerminates =
false;
397 if (!SecondsToWait) {
398 WaitUntilTerminates =
true;
400 if (*SecondsToWait == 0)
401 WaitPidOptions = WNOHANG;
406 memset(&Act, 0,
sizeof(Act));
407 Act.sa_handler = TimeOutHandler;
408 sigemptyset(&Act.sa_mask);
409 sigaction(SIGALRM, &Act, &Old);
411 alarm(*SecondsToWait);
422 WaitResult.
Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &
Info);
423 }
while (WaitUntilTerminates && WaitResult.
Pid == -1 && errno == EINTR);
425 if (WaitResult.
Pid != PI.
Pid) {
426 if (WaitResult.
Pid == 0) {
430 if (SecondsToWait && errno == EINTR && !Polling) {
432 kill(PI.
Pid, SIGKILL);
436 sigaction(SIGALRM, &Old,
nullptr);
441 if (wait(&status) != ChildPid)
442 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
448 }
else if (errno != EINTR) {
449 MakeErrMsg(ErrMsg,
"Error waiting for child process");
457 if (SecondsToWait && !WaitUntilTerminates) {
459 sigaction(SIGALRM, &Old,
nullptr);
475 if (WIFEXITED(status)) {
476 result = WEXITSTATUS(status);
487 *ErrMsg =
"Program could not be executed";
491 }
else if (WIFSIGNALED(status)) {
493 *ErrMsg = strsignal(WTERMSIG(status));
495 if (WCOREDUMP(status))
496 *ErrMsg +=
" (core dumped)";
507 if (!(
Flags & fs::OF_Text))
509 return std::error_code();
513 if (!(
Flags & fs::OF_Text))
515 return std::error_code();
520 return std::error_code();
525 return std::error_code();
548 static long ArgMax = sysconf(_SC_ARG_MAX);
551 static long ArgMin = _POSIX_ARG_MAX;
554 long EffectiveArgMax = 128 * 1024;
556 if (EffectiveArgMax > ArgMax)
557 EffectiveArgMax = ArgMax;
558 else if (EffectiveArgMax < ArgMin)
559 EffectiveArgMax = ArgMin;
566 long HalfArgMax = EffectiveArgMax / 2;
568 size_t ArgLength = Program.
size() + 1;
575 if (
Arg.size() >= (32 * 4096))
578 ArgLength +=
Arg.size() + 1;
579 if (ArgLength >
size_t(HalfArgMax)) {
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
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)
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),...
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.
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.