21 #include "llvm/Config/config.h"
30 #if HAVE_SYS_RESOURCE_H
31 #include <sys/resource.h>
42 #ifdef HAVE_POSIX_SPAWN
44 #define _RESTRICT_KYWD
48 #if defined(__APPLE__)
49 #include <TargetConditionals.h>
52 #if defined(__APPLE__) && !(defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE)
53 #define USE_NSGETENVIRON 1
55 #define USE_NSGETENVIRON 0
59 extern char **environ;
61 #include <crt_externs.h>
72 ArrayRef<StringRef> Paths) {
73 assert(!Name.empty() &&
"Must have a name!");
77 return std::string(Name);
79 SmallVector<StringRef, 16> EnvironmentPaths;
81 if (
const char *PathEnv = std::getenv(
"PATH")) {
83 Paths = EnvironmentPaths;
86 for (
auto Path : Paths) {
91 SmallString<128> FilePath(Path);
94 return std::string(FilePath.str());
99 static bool RedirectIO(
const StringRef *Path,
int FD, std::string* ErrMsg) {
110 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
112 MakeErrMsg(ErrMsg,
"Cannot open file '" + File +
"' for "
113 + (FD == 0 ?
"input" :
"output"));
118 if (dup2(InFD, FD) == -1) {
127 #ifdef HAVE_POSIX_SPAWN
128 static bool RedirectIO_PS(
const std::string *Path,
int FD, std::string *ErrMsg,
129 posix_spawn_file_actions_t *FileActions) {
137 File = Path->c_str();
139 if (
int Err = posix_spawn_file_actions_addopen(
140 FileActions, FD, File,
141 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
142 return MakeErrMsg(ErrMsg,
"Cannot dup2", Err);
147 static void TimeOutHandler(
int Sig) {
150 static void SetMemoryLimits (
unsigned size)
152 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
154 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
157 getrlimit (RLIMIT_DATA, &r);
159 setrlimit (RLIMIT_DATA, &r);
162 getrlimit (RLIMIT_RSS, &r);
164 setrlimit (RLIMIT_RSS, &r);
166 #ifdef RLIMIT_AS // e.g. NetBSD doesn't have it.
169 #if !LLVM_MEMORY_SANITIZER_BUILD && !LLVM_ADDRESS_SANITIZER_BUILD
171 getrlimit (RLIMIT_AS, &r);
173 setrlimit (RLIMIT_AS, &r);
181 static bool Execute(ProcessInfo &PI, StringRef Program,
const char **args,
182 const char **envp,
const StringRef **redirects,
183 unsigned memoryLimit, std::string *ErrMsg) {
186 *ErrMsg = std::string(
"Executable \"") + Program.str() +
187 std::string(
"\" doesn't exist!");
193 #ifdef HAVE_POSIX_SPAWN
194 if (memoryLimit == 0) {
195 posix_spawn_file_actions_t FileActionsStore;
196 posix_spawn_file_actions_t *FileActions =
nullptr;
201 std::string RedirectsStorage[3];
204 std::string *RedirectsStr[3] = {
nullptr,
nullptr,
nullptr};
205 for (
int I = 0;
I < 3; ++
I) {
207 RedirectsStorage[
I] = *redirects[
I];
208 RedirectsStr[
I] = &RedirectsStorage[
I];
212 FileActions = &FileActionsStore;
213 posix_spawn_file_actions_init(FileActions);
216 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
217 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
219 if (redirects[1] ==
nullptr || redirects[2] ==
nullptr ||
220 *redirects[1] != *redirects[2]) {
222 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
227 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
228 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
233 #if !USE_NSGETENVIRON
234 envp =
const_cast<const char **
>(environ);
237 envp =
const_cast<const char **
>(*_NSGetEnviron());
243 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
244 nullptr,
const_cast<char **
>(args),
245 const_cast<char **>(envp));
248 posix_spawn_file_actions_destroy(FileActions);
251 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
272 if (RedirectIO(redirects[0], 0, ErrMsg)) {
return false; }
274 if (RedirectIO(redirects[1], 1, ErrMsg)) {
return false; }
275 if (redirects[1] && redirects[2] &&
276 *(redirects[1]) == *(redirects[2])) {
279 if (-1 == dup2(1,2)) {
280 MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout");
285 if (RedirectIO(redirects[2], 2, ErrMsg)) {
return false; }
290 if (memoryLimit!=0) {
291 SetMemoryLimits(memoryLimit);
295 std::string PathStr = Program;
297 execve(PathStr.c_str(),
298 const_cast<char **
>(args),
299 const_cast<char **>(envp));
301 execv(PathStr.c_str(),
302 const_cast<char **
>(args));
309 _exit(errno == ENOENT ? 127 : 126);
324 ProcessInfo
sys::Wait(
const ProcessInfo &PI,
unsigned SecondsToWait,
325 bool WaitUntilTerminates, std::string *ErrMsg) {
326 struct sigaction Act, Old;
327 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
329 int WaitPidOptions = 0;
330 pid_t ChildPid = PI.Pid;
331 if (WaitUntilTerminates) {
333 }
else if (SecondsToWait) {
337 memset(&Act, 0,
sizeof(Act));
338 Act.sa_handler = TimeOutHandler;
339 sigemptyset(&Act.sa_mask);
340 sigaction(SIGALRM, &Act, &Old);
341 alarm(SecondsToWait);
342 }
else if (SecondsToWait == 0)
343 WaitPidOptions = WNOHANG;
347 ProcessInfo WaitResult;
350 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
351 }
while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
353 if (WaitResult.Pid != PI.Pid) {
354 if (WaitResult.Pid == 0) {
358 if (SecondsToWait && errno == EINTR) {
360 kill(PI.Pid, SIGKILL);
364 sigaction(SIGALRM, &Old,
nullptr);
367 if (wait(&status) != ChildPid)
368 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
372 WaitResult.ReturnCode = -2;
374 }
else if (errno != EINTR) {
375 MakeErrMsg(ErrMsg,
"Error waiting for child process");
376 WaitResult.ReturnCode = -1;
383 if (SecondsToWait && !WaitUntilTerminates) {
385 sigaction(SIGALRM, &Old,
nullptr);
391 if (WIFEXITED(status)) {
392 result = WEXITSTATUS(status);
393 WaitResult.ReturnCode = result;
398 WaitResult.ReturnCode = -1;
403 *ErrMsg =
"Program could not be executed";
404 WaitResult.ReturnCode = -1;
407 }
else if (WIFSIGNALED(status)) {
409 *ErrMsg = strsignal(WTERMSIG(status));
411 if (WCOREDUMP(status))
412 *ErrMsg +=
" (core dumped)";
417 WaitResult.ReturnCode = -2;
424 return std::error_code();
429 return std::error_code();
450 static long ArgMax = sysconf(_SC_ARG_MAX);
457 long HalfArgMax = ArgMax / 2;
459 size_t ArgLength = Program.size() + 1;
460 for (ArrayRef<const char*>::iterator
I = Args.begin(),
E = Args.end();
462 ArgLength += strlen(*
I) + 1;
463 if (ArgLength >
size_t(HalfArgMax)) {
bool can_execute(const Twine &Path)
Can we execute this file?
std::error_code ChangeStdoutToBinary()
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
std::string StrError()
Returns a string representation of the errno value, using whatever thread-safe variant of strerror() ...
std::error_code make_error_code(BitcodeError E)
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
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, appending the result fragments to the output list.
static bool Execute(ProcessInfo &PI, StringRef Program, const char **args, const char **env, const StringRef **Redirects, unsigned memoryLimit, std::string *ErrMsg)
bool commandLineFitsWithinSystemLimits(StringRef Program, ArrayRef< const char * > Args)
Return true if the given arguments fit within system-specific argument length limits.
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.
bool MakeErrMsg(std::string *ErrMsg, const std::string &prefix)
WindowsEncodingMethod
File encoding options when writing contents that a non-UTF8 tool will read (on Windows systems)...
The file should be opened in text mode on platforms that make this distinction.
std::error_code ChangeStdinToBinary()
A raw_ostream that writes to a file descriptor.
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths=None)
Find the first executable file Name in Paths.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
ProcessInfo Wait(const ProcessInfo &PI, unsigned SecondsToWait, bool WaitUntilTerminates, std::string *ErrMsg=nullptr)
This function waits for the process specified by PI to finish.
std::error_code status(const Twine &path, file_status &result)
Get file status as if by POSIX stat().
bool exists(file_status status)
Does file exist?