21 #include "llvm/Config/config.h"
30 #if HAVE_SYS_RESOURCE_H
31 #include <sys/resource.h>
42 #ifdef HAVE_POSIX_SPAWN
45 #if defined(__APPLE__)
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
56 extern char **environ;
58 #include <crt_externs.h>
69 ArrayRef<StringRef> Paths) {
70 assert(!Name.empty() &&
"Must have a name!");
74 return std::string(Name);
76 SmallVector<StringRef, 16> EnvironmentPaths;
78 if (
const char *PathEnv = std::getenv(
"PATH")) {
80 Paths = EnvironmentPaths;
83 for (
auto Path : Paths) {
88 SmallString<128> FilePath(Path);
91 return std::string(FilePath.str());
96 static bool RedirectIO(
const StringRef *Path,
int FD, std::string*
ErrMsg) {
107 int InFD = open(File.c_str(), FD == 0 ? O_RDONLY : O_WRONLY|O_CREAT, 0666);
109 MakeErrMsg(ErrMsg,
"Cannot open file '" + File +
"' for "
110 + (FD == 0 ?
"input" :
"output"));
115 if (dup2(InFD, FD) == -1) {
124 #ifdef HAVE_POSIX_SPAWN
125 static bool RedirectIO_PS(
const std::string *Path,
int FD, std::string *ErrMsg,
126 posix_spawn_file_actions_t *FileActions) {
134 File = Path->c_str();
136 if (
int Err = posix_spawn_file_actions_addopen(
137 FileActions, FD, File,
138 FD == 0 ? O_RDONLY : O_WRONLY | O_CREAT, 0666))
139 return MakeErrMsg(ErrMsg,
"Cannot dup2", Err);
144 static void TimeOutHandler(
int Sig) {
147 static void SetMemoryLimits (
unsigned size)
149 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT
151 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
154 getrlimit (RLIMIT_DATA, &r);
156 setrlimit (RLIMIT_DATA, &r);
159 getrlimit (RLIMIT_RSS, &r);
161 setrlimit (RLIMIT_RSS, &r);
168 static bool Execute(ProcessInfo &PI, StringRef Program,
const char **args,
169 const char **envp,
const StringRef **redirects,
170 unsigned memoryLimit, std::string *ErrMsg) {
173 *ErrMsg = std::string(
"Executable \"") + Program.str() +
174 std::string(
"\" doesn't exist!");
180 #ifdef HAVE_POSIX_SPAWN
181 if (memoryLimit == 0) {
182 posix_spawn_file_actions_t FileActionsStore;
183 posix_spawn_file_actions_t *FileActions =
nullptr;
188 std::string RedirectsStorage[3];
191 std::string *RedirectsStr[3] = {
nullptr,
nullptr,
nullptr};
192 for (
int I = 0;
I < 3; ++
I) {
194 RedirectsStorage[
I] = *redirects[
I];
195 RedirectsStr[
I] = &RedirectsStorage[
I];
199 FileActions = &FileActionsStore;
200 posix_spawn_file_actions_init(FileActions);
203 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
204 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
206 if (redirects[1] ==
nullptr || redirects[2] ==
nullptr ||
207 *redirects[1] != *redirects[2]) {
209 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
214 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
215 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
220 #if !USE_NSGETENVIRON
221 envp =
const_cast<const char **
>(environ);
224 envp =
const_cast<const char **
>(*_NSGetEnviron());
230 int Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
231 nullptr,
const_cast<char **
>(args),
232 const_cast<char **>(envp));
235 posix_spawn_file_actions_destroy(FileActions);
238 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
259 if (RedirectIO(redirects[0], 0, ErrMsg)) {
return false; }
261 if (RedirectIO(redirects[1], 1, ErrMsg)) {
return false; }
262 if (redirects[1] && redirects[2] &&
263 *(redirects[1]) == *(redirects[2])) {
266 if (-1 == dup2(1,2)) {
267 MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout");
272 if (RedirectIO(redirects[2], 2, ErrMsg)) {
return false; }
277 if (memoryLimit!=0) {
278 SetMemoryLimits(memoryLimit);
282 std::string PathStr = Program;
284 execve(PathStr.c_str(),
285 const_cast<char **
>(args),
286 const_cast<char **>(envp));
288 execv(PathStr.c_str(),
289 const_cast<char **
>(args));
296 _exit(errno == ENOENT ? 127 : 126);
311 ProcessInfo
sys::Wait(
const ProcessInfo &PI,
unsigned SecondsToWait,
312 bool WaitUntilTerminates, std::string *ErrMsg) {
313 struct sigaction Act, Old;
314 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
316 int WaitPidOptions = 0;
317 pid_t ChildPid = PI.Pid;
318 if (WaitUntilTerminates) {
320 }
else if (SecondsToWait) {
324 memset(&Act, 0,
sizeof(Act));
325 Act.sa_handler = TimeOutHandler;
326 sigemptyset(&Act.sa_mask);
327 sigaction(SIGALRM, &Act, &Old);
328 alarm(SecondsToWait);
329 }
else if (SecondsToWait == 0)
330 WaitPidOptions = WNOHANG;
334 ProcessInfo WaitResult;
337 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
338 }
while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
340 if (WaitResult.Pid != PI.Pid) {
341 if (WaitResult.Pid == 0) {
345 if (SecondsToWait && errno == EINTR) {
347 kill(PI.Pid, SIGKILL);
351 sigaction(SIGALRM, &Old,
nullptr);
354 if (wait(&status) != ChildPid)
355 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
359 WaitResult.ReturnCode = -2;
361 }
else if (errno != EINTR) {
362 MakeErrMsg(ErrMsg,
"Error waiting for child process");
363 WaitResult.ReturnCode = -1;
370 if (SecondsToWait && !WaitUntilTerminates) {
372 sigaction(SIGALRM, &Old,
nullptr);
378 if (WIFEXITED(status)) {
379 result = WEXITSTATUS(status);
380 WaitResult.ReturnCode = result;
385 WaitResult.ReturnCode = -1;
390 *ErrMsg =
"Program could not be executed";
391 WaitResult.ReturnCode = -1;
394 }
else if (WIFSIGNALED(status)) {
396 *ErrMsg = strsignal(WTERMSIG(status));
398 if (WCOREDUMP(status))
399 *ErrMsg +=
" (core dumped)";
404 WaitResult.ReturnCode = -2;
411 return std::error_code();
416 return std::error_code();
437 static long ArgMax = sysconf(_SC_ARG_MAX);
444 long HalfArgMax = ArgMax / 2;
446 size_t ArgLength = Program.size() + 1;
447 for (ArrayRef<const char*>::iterator
I = Args.begin(),
E = Args.end();
449 size_t length = strlen(*
I);
456 if (length >= (32 * 4096))
459 ArgLength += length + 1;
460 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)
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
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.
bool exists(file_status status)
Does file exist?