22#include "llvm/Config/config.h"
32#include <sys/resource.h>
37#ifdef HAVE_POSIX_SPAWN
41#include <TargetConditionals.h>
44#if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
45#define USE_NSGETENVIRON 1
47#define USE_NSGETENVIRON 0
53#include <crt_externs.h>
67 if (
Name.contains(
'/'))
68 return std::string(Name);
72 if (
const char *PathEnv = std::getenv(
"PATH")) {
74 Paths = EnvironmentPaths;
77 for (
auto Path : Paths) {
85 return std::string(FilePath);
90static bool RedirectIO(std::optional<StringRef> Path,
int FD, std::string *ErrMsg) {
98 File = std::string(*Path);
101 int InFD = open(
File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666);
103 MakeErrMsg(ErrMsg,
"Cannot open file '" + File +
"' for " +
104 (FD == 0 ?
"input" :
"output"));
109 if (dup2(InFD, FD) == -1) {
118#ifdef HAVE_POSIX_SPAWN
119static bool RedirectIO_PS(
const std::string *Path,
int FD, std::string *ErrMsg,
120 posix_spawn_file_actions_t *FileActions) {
130 if (
int Err = posix_spawn_file_actions_addopen(
131 FileActions, FD, File, FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
132 return MakeErrMsg(ErrMsg,
"Cannot posix_spawn_file_actions_addopen", Err);
137static void TimeOutHandler(
int Sig) {}
139static void SetMemoryLimits(
unsigned size) {
141 __typeof__(r.rlim_cur) limit = (__typeof__(r.rlim_cur))(
size)*1048576;
144 getrlimit(RLIMIT_DATA, &r);
146 setrlimit(RLIMIT_DATA, &r);
149 getrlimit(RLIMIT_RSS, &r);
151 setrlimit(RLIMIT_RSS, &r);
155static std::vector<const char *>
157 std::vector<const char *>
Result;
160 Result.push_back(
nullptr);
167 ArrayRef<std::optional<StringRef>> Redirects,
168 unsigned MemoryLimit, std::string *ErrMsg,
169 BitVector *AffinityMask,
bool DetachProcess) {
170 assert(!AffinityMask &&
"Starting a process with an affinity mask is "
171 "currently not supported on Unix!");
175 std::vector<const char *>
ArgVector, EnvVector;
176 const char **Argv =
nullptr;
177 const char **Envp =
nullptr;
178 ArgVector = toNullTerminatedCStringArray(Args, Saver);
181 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
182 Envp = EnvVector.data();
187#ifdef HAVE_POSIX_SPAWN
189 if (MemoryLimit == 0 && !DetachProcess) {
190 posix_spawn_file_actions_t FileActionsStore;
191 posix_spawn_file_actions_t *FileActions =
nullptr;
196 std::string RedirectsStorage[3];
198 if (!Redirects.empty()) {
199 assert(Redirects.size() == 3);
200 std::string *RedirectsStr[3] = {
nullptr,
nullptr,
nullptr};
201 for (
int I = 0;
I < 3; ++
I) {
203 RedirectsStorage[
I] = std::string(*Redirects[
I]);
204 RedirectsStr[
I] = &RedirectsStorage[
I];
208 FileActions = &FileActionsStore;
209 posix_spawn_file_actions_init(FileActions);
212 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
213 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
215 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
217 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
222 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
223 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
229 Envp =
const_cast<const char **
>(environ);
232 Envp =
const_cast<const char **
>(*_NSGetEnviron());
235 constexpr int maxRetries = 8;
241 Err = posix_spawn(&PID, Program.
str().c_str(), FileActions,
242 nullptr,
const_cast<char **
>(Argv),
243 const_cast<char **
>(Envp));
244 }
while (Err == EINTR && ++retries < maxRetries);
247 posix_spawn_file_actions_destroy(FileActions);
250 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
270 if (!Redirects.empty()) {
272 if (RedirectIO(Redirects[0], 0, ErrMsg)) {
276 if (RedirectIO(Redirects[1], 1, ErrMsg)) {
279 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
282 if (-1 == dup2(1, 2)) {
283 MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout");
288 if (RedirectIO(Redirects[2], 2, ErrMsg)) {
296 if (::setsid() == -1) {
297 MakeErrMsg(ErrMsg,
"Could not detach process, ::setsid failed");
303 if (MemoryLimit != 0) {
304 SetMemoryLimits(MemoryLimit);
308 std::string PathStr = std::string(Program);
310 execve(PathStr.c_str(),
const_cast<char **
>(Argv),
311 const_cast<char **
>(Envp));
313 execv(PathStr.c_str(),
const_cast<char **
>(Argv));
320 _exit(errno == ENOENT ? 127 : 126);
338static pid_t(wait4)(pid_t pid,
int *
status,
int options,
struct rusage *usage);
339#elif !defined(__Fuchsia__)
349 struct rusage *usage);
352 struct rusage *usage) {
353 assert(pid > 0 &&
"Only expecting to handle actual PID values!");
354 assert((options & ~WNOHANG) == 0 &&
"Expecting WNOHANG at most!");
355 assert(usage &&
"Expecting usage collection!");
358 if (!(options & WNOHANG))
359 return ::wait4(pid, status, options, usage);
363 siginfo_t WaitIdInfo;
364 WaitIdInfo.si_pid = 0;
366 waitid(P_PID, pid, &WaitIdInfo, WNOWAIT | WEXITED | options);
368 if (WaitIdRetVal == -1 || WaitIdInfo.si_pid == 0)
371 assert(WaitIdInfo.si_pid == pid);
376 return ::wait4(pid, status, options & ~WNOHANG, usage);
381 std::optional<unsigned> SecondsToWait,
383 std::optional<ProcessStatistics> *ProcStat,
385 struct sigaction Act, Old;
386 assert(PI.
Pid &&
"invalid pid to wait on, process not started?");
388 int WaitPidOptions = 0;
389 pid_t ChildPid = PI.
Pid;
390 bool WaitUntilTerminates =
false;
391 if (!SecondsToWait) {
392 WaitUntilTerminates =
true;
394 if (*SecondsToWait == 0)
395 WaitPidOptions = WNOHANG;
400 memset(&Act, 0,
sizeof(Act));
401 Act.sa_handler = TimeOutHandler;
402 sigemptyset(&Act.sa_mask);
403 sigaction(SIGALRM, &Act, &Old);
405 alarm(*SecondsToWait);
417 WaitResult.
Pid = sys::wait4(ChildPid, &status, WaitPidOptions, &
Info);
418 }
while (WaitUntilTerminates && WaitResult.
Pid == -1 && errno == EINTR);
421 if (WaitResult.
Pid != PI.
Pid) {
422 if (WaitResult.
Pid == 0) {
426 if (SecondsToWait && errno == EINTR && !Polling) {
428 kill(PI.
Pid, SIGKILL);
432 sigaction(SIGALRM, &Old,
nullptr);
437 if (wait(&status) != ChildPid)
438 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
444 }
else if (errno != EINTR) {
445 MakeErrMsg(ErrMsg,
"Error waiting for child process");
453 if (SecondsToWait && !WaitUntilTerminates) {
455 sigaction(SIGALRM, &Old,
nullptr);
463#if !defined(__HAIKU__) && !defined(__MVS__)
473 if (WIFEXITED(status)) {
474 result = WEXITSTATUS(status);
485 *ErrMsg =
"Program could not be executed";
489 }
else if (WIFSIGNALED(status)) {
493 if (WCOREDUMP(status))
494 *ErrMsg +=
" (core dumped)";
507 return std::error_code();
513 return std::error_code();
521 return std::error_code();
527 return std::error_code();
550 static long ArgMax = sysconf(_SC_ARG_MAX);
553 static long ArgMin = _POSIX_ARG_MAX;
556 long EffectiveArgMax = 128 * 1024;
558 if (EffectiveArgMax > ArgMax)
559 EffectiveArgMax = ArgMax;
560 else if (EffectiveArgMax < ArgMin)
561 EffectiveArgMax = ArgMin;
568 long HalfArgMax = EffectiveArgMax / 2;
570 size_t ArgLength = Program.
size() + 1;
577 if (Arg.size() >= (32 * 4096))
580 ArgLength += Arg.size() + 1;
581 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.
char * strsignal(int sig) asm("llvm_zos_strsignal")
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.