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>
68 if (
Name.contains(
'/'))
69 return std::string(Name);
73 if (
const char *PathEnv = std::getenv(
"PATH")) {
75 Paths = EnvironmentPaths;
78 for (
auto Path : Paths) {
86 return std::string(FilePath);
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) {
171 assert(!AffinityMask &&
"Starting a process with an affinity mask is "
172 "currently not supported on Unix!");
176 std::vector<const char *>
ArgVector, EnvVector;
177 const char **Argv =
nullptr;
178 const char **Envp =
nullptr;
179 ArgVector = toNullTerminatedCStringArray(Args, Saver);
182 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
183 Envp = EnvVector.data();
188#ifdef HAVE_POSIX_SPAWN
190 if (MemoryLimit == 0 && !DetachProcess) {
191 posix_spawn_file_actions_t FileActionsStore;
192 posix_spawn_file_actions_t *FileActions =
nullptr;
197 std::string RedirectsStorage[3];
199 if (!Redirects.empty()) {
200 assert(Redirects.size() == 3);
201 std::string *RedirectsStr[3] = {
nullptr,
nullptr,
nullptr};
202 for (
int I = 0;
I < 3; ++
I) {
204 RedirectsStorage[
I] = std::string(*Redirects[
I]);
205 RedirectsStr[
I] = &RedirectsStorage[
I];
209 FileActions = &FileActionsStore;
210 posix_spawn_file_actions_init(FileActions);
213 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
214 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
216 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
218 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
223 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
224 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
230 Envp =
const_cast<const char **
>(environ);
233 Envp =
const_cast<const char **
>(*_NSGetEnviron());
236 constexpr int maxRetries = 8;
242 Err = posix_spawn(&PID, Program.
str().c_str(), FileActions,
243 nullptr,
const_cast<char **
>(Argv),
244 const_cast<char **
>(Envp));
245 }
while (Err == EINTR && ++retries < maxRetries);
248 posix_spawn_file_actions_destroy(FileActions);
251 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
271 if (!Redirects.empty()) {
273 if (RedirectIO(Redirects[0], 0, ErrMsg)) {
277 if (RedirectIO(Redirects[1], 1, ErrMsg)) {
280 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
283 if (-1 == dup2(1, 2)) {
284 MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout");
289 if (RedirectIO(Redirects[2], 2, ErrMsg)) {
297 if (::setsid() == -1) {
298 MakeErrMsg(ErrMsg,
"Could not detach process, ::setsid failed");
304 if (MemoryLimit != 0) {
305 SetMemoryLimits(MemoryLimit);
309 std::string PathStr = std::string(Program);
311 execve(PathStr.c_str(),
const_cast<char **
>(Argv),
312 const_cast<char **
>(Envp));
314 execv(PathStr.c_str(),
const_cast<char **
>(Argv));
321 _exit(errno == ENOENT ? 127 : 126);
339static pid_t(wait4)(pid_t pid,
int *
status,
int options,
struct rusage *usage);
340#elif !defined(__Fuchsia__)
350 struct rusage *usage);
353 struct rusage *usage) {
354 assert(pid > 0 &&
"Only expecting to handle actual PID values!");
355 assert((options & ~WNOHANG) == 0 &&
"Expecting WNOHANG at most!");
356 assert(usage &&
"Expecting usage collection!");
359 if (!(options & WNOHANG))
360 return ::wait4(pid, status, options, usage);
364 siginfo_t WaitIdInfo;
365 WaitIdInfo.si_pid = 0;
367 waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
369 if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
372 assert(WaitIdInfo.si_pid == pid);
377 return ::wait4(pid, status, options & ~WNOHANG, usage);
382 std::optional<unsigned> SecondsToWait,
384 std::optional<ProcessStatistics> *ProcStat,
386 struct sigaction Act, Old;
387 assert(PI.
Pid &&
"invalid pid to wait on, process not started?");
389 int WaitPidOptions = 0;
390 pid_t ChildPid = PI.
Pid;
391 bool WaitUntilTerminates =
false;
392 if (!SecondsToWait) {
393 WaitUntilTerminates =
true;
395 if (*SecondsToWait == 0)
396 WaitPidOptions = WNOHANG;
401 memset(&Act, 0,
sizeof(Act));
402 Act.sa_handler = TimeOutHandler;
403 sigemptyset(&Act.sa_mask);
404 sigaction(SIGALRM, &Act, &Old);
406 alarm(*SecondsToWait);
418 WaitResult.
Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &
Info);
419 }
while (WaitUntilTerminates && WaitResult.
Pid == -1 && errno == EINTR);
422 if (WaitResult.
Pid != PI.
Pid) {
423 if (WaitResult.
Pid == 0) {
427 if (SecondsToWait && errno == EINTR && !Polling) {
429 kill(PI.
Pid, SIGKILL);
433 sigaction(SIGALRM, &Old,
nullptr);
438 if (wait(&status) != ChildPid)
439 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
445 }
else if (errno != EINTR) {
446 MakeErrMsg(ErrMsg,
"Error waiting for child process");
454 if (SecondsToWait && !WaitUntilTerminates) {
456 sigaction(SIGALRM, &Old,
nullptr);
464#if !defined(__HAIKU__) && !defined(__MVS__)
474 if (WIFEXITED(status)) {
475 result = WEXITSTATUS(status);
486 *ErrMsg =
"Program could not be executed";
490 }
else if (WIFSIGNALED(status)) {
492 *ErrMsg = strsignal(WTERMSIG(status));
494 if (WCOREDUMP(status))
495 *ErrMsg +=
" (core dumped)";
508 return std::error_code();
514 return std::error_code();
522 return std::error_code();
528 return std::error_code();
551 static long ArgMax = sysconf(_SC_ARG_MAX);
554 static long ArgMin = _POSIX_ARG_MAX;
557 long EffectiveArgMax = 128 * 1024;
559 if (EffectiveArgMax > ArgMax)
560 EffectiveArgMax = ArgMax;
561 else if (EffectiveArgMax < ArgMin)
562 EffectiveArgMax = ArgMin;
569 long HalfArgMax = EffectiveArgMax / 2;
571 size_t ArgLength = Program.
size() + 1;
578 if (Arg.size() >= (32 * 4096))
581 ArgLength += Arg.size() + 1;
582 if (ArgLength >
size_t(HalfArgMax)) {
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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)
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.
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
LLVM_ABI bool can_execute(const Twine &Path)
Can we execute this file?
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
LLVM_ABI std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
LLVM_ABI std::error_code ChangeStdoutMode(fs::OpenFlags Flags)
std::chrono::nanoseconds toDuration(FILETIME Time)
LLVM_ABI std::string StrError()
Returns a string representation of the errno value, using whatever thread-safe variant of strerror() ...
LLVM_ABI std::error_code ChangeStdinMode(fs::OpenFlags Flags)
LLVM_ABI std::error_code ChangeStdinToBinary()
LLVM_ABI bool commandLineFitsWithinSystemLimits(StringRef Program, ArrayRef< StringRef > Args)
Return true if the given arguments fit within system-specific argument length limits.
LLVM_ABI 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.
LLVM_ABI ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
WindowsEncodingMethod
File encoding options when writing contents that a non-UTF8 tool will read (on Windows systems).
LLVM_ABI std::error_code ChangeStdoutToBinary()
LLVM_ABI 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.
This is an optimization pass for GlobalISel generic memory operations.
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
std::error_code make_error_code(BitcodeError E)
LLVM_ABI void SplitString(StringRef Source, SmallVectorImpl< StringRef > &OutFragments, StringRef Delimiters=" \t\n\v\f\r")
SplitString - Split up the specified string according to the specified delimiters,...
@ no_such_file_or_directory
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
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.