20 #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(Optional<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 posix_spawn_file_actions_addopen", Err);
144 static void TimeOutHandler(
int Sig) {
147 static void SetMemoryLimits(
unsigned size) {
148 #if HAVE_SYS_RESOURCE_H && HAVE_GETRLIMIT && HAVE_SETRLIMIT 150 __typeof__ (r.rlim_cur) limit = (__typeof__ (r.rlim_cur)) (size) * 1048576;
153 getrlimit (RLIMIT_DATA, &r);
155 setrlimit (RLIMIT_DATA, &r);
158 getrlimit (RLIMIT_RSS, &r);
160 setrlimit (RLIMIT_RSS, &r);
167 static std::vector<const char *>
168 toNullTerminatedCStringArray(ArrayRef<StringRef> Strings, StringSaver &Saver) {
169 std::vector<const char *>
Result;
170 for (StringRef S : Strings)
171 Result.push_back(Saver.save(S).data());
172 Result.push_back(
nullptr);
176 static bool Execute(ProcessInfo &PI, StringRef Program,
177 ArrayRef<StringRef>
Args,
Optional<ArrayRef<StringRef>> Env,
178 ArrayRef<Optional<StringRef>> Redirects,
179 unsigned MemoryLimit, std::string *ErrMsg) {
182 *ErrMsg = std::string(
"Executable \"") + Program.str() +
183 std::string(
"\" doesn't exist!");
188 StringSaver Saver(Allocator);
189 std::vector<const char *> ArgVector, EnvVector;
190 const char **Argv =
nullptr;
191 const char **Envp =
nullptr;
192 ArgVector = toNullTerminatedCStringArray(Args, Saver);
193 Argv = ArgVector.data();
195 EnvVector = toNullTerminatedCStringArray(*Env, Saver);
196 Envp = EnvVector.data();
201 #ifdef HAVE_POSIX_SPAWN 202 if (MemoryLimit == 0) {
203 posix_spawn_file_actions_t FileActionsStore;
204 posix_spawn_file_actions_t *FileActions =
nullptr;
209 std::string RedirectsStorage[3];
211 if (!Redirects.empty()) {
212 assert(Redirects.size() == 3);
213 std::string *RedirectsStr[3] = {
nullptr,
nullptr,
nullptr};
214 for (
int I = 0;
I < 3; ++
I) {
216 RedirectsStorage[
I] = *Redirects[
I];
217 RedirectsStr[
I] = &RedirectsStorage[
I];
221 FileActions = &FileActionsStore;
222 posix_spawn_file_actions_init(FileActions);
225 if (RedirectIO_PS(RedirectsStr[0], 0, ErrMsg, FileActions) ||
226 RedirectIO_PS(RedirectsStr[1], 1, ErrMsg, FileActions))
228 if (!Redirects[1] || !Redirects[2] || *Redirects[1] != *Redirects[2]) {
230 if (RedirectIO_PS(RedirectsStr[2], 2, ErrMsg, FileActions))
235 if (
int Err = posix_spawn_file_actions_adddup2(FileActions, 1, 2))
236 return !
MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout", Err);
241 #if !USE_NSGETENVIRON 242 Envp =
const_cast<const char **
>(environ);
245 Envp =
const_cast<const char **
>(*_NSGetEnviron());
248 constexpr
int maxRetries = 8;
254 Err = posix_spawn(&PID, Program.str().c_str(), FileActions,
255 nullptr,
const_cast<char **
>(Argv),
256 const_cast<char **>(Envp));
257 }
while (Err == EINTR && ++retries < maxRetries);
260 posix_spawn_file_actions_destroy(FileActions);
263 return !
MakeErrMsg(ErrMsg,
"posix_spawn failed", Err);
283 if (!Redirects.empty()) {
285 if (RedirectIO(Redirects[0], 0, ErrMsg)) {
return false; }
287 if (RedirectIO(Redirects[1], 1, ErrMsg)) {
return false; }
288 if (Redirects[1] && Redirects[2] && *Redirects[1] == *Redirects[2]) {
291 if (-1 == dup2(1,2)) {
292 MakeErrMsg(ErrMsg,
"Can't redirect stderr to stdout");
297 if (RedirectIO(Redirects[2], 2, ErrMsg)) {
return false; }
302 if (MemoryLimit!=0) {
303 SetMemoryLimits(MemoryLimit);
307 std::string PathStr = Program;
309 execve(PathStr.c_str(),
const_cast<char **
>(Argv),
310 const_cast<char **>(Envp));
312 execv(PathStr.c_str(),
const_cast<char **
>(Argv));
319 _exit(errno == ENOENT ? 127 : 126);
335 ProcessInfo
sys::Wait(
const ProcessInfo &PI,
unsigned SecondsToWait,
336 bool WaitUntilTerminates, std::string *ErrMsg) {
337 struct sigaction Act, Old;
338 assert(PI.Pid &&
"invalid pid to wait on, process not started?");
340 int WaitPidOptions = 0;
341 pid_t ChildPid = PI.Pid;
342 if (WaitUntilTerminates) {
344 }
else if (SecondsToWait) {
348 memset(&Act, 0,
sizeof(Act));
349 Act.sa_handler = TimeOutHandler;
350 sigemptyset(&Act.sa_mask);
351 sigaction(SIGALRM, &Act, &Old);
352 alarm(SecondsToWait);
353 }
else if (SecondsToWait == 0)
354 WaitPidOptions = WNOHANG;
358 ProcessInfo WaitResult;
361 WaitResult.Pid = waitpid(ChildPid, &status, WaitPidOptions);
362 }
while (WaitUntilTerminates && WaitResult.Pid == -1 && errno == EINTR);
364 if (WaitResult.Pid != PI.Pid) {
365 if (WaitResult.Pid == 0) {
369 if (SecondsToWait && errno == EINTR) {
371 kill(PI.Pid, SIGKILL);
375 sigaction(SIGALRM, &Old,
nullptr);
378 if (wait(&status) != ChildPid)
379 MakeErrMsg(ErrMsg,
"Child timed out but wouldn't die");
383 WaitResult.ReturnCode = -2;
385 }
else if (errno != EINTR) {
386 MakeErrMsg(ErrMsg,
"Error waiting for child process");
387 WaitResult.ReturnCode = -1;
394 if (SecondsToWait && !WaitUntilTerminates) {
396 sigaction(SIGALRM, &Old,
nullptr);
402 if (WIFEXITED(status)) {
403 result = WEXITSTATUS(status);
404 WaitResult.ReturnCode = result;
409 WaitResult.ReturnCode = -1;
414 *ErrMsg =
"Program could not be executed";
415 WaitResult.ReturnCode = -1;
418 }
else if (WIFSIGNALED(status)) {
420 *ErrMsg = strsignal(WTERMSIG(status));
422 if (WCOREDUMP(status))
423 *ErrMsg +=
" (core dumped)";
428 WaitResult.ReturnCode = -2;
435 return std::error_code();
440 return std::error_code();
461 ArrayRef<StringRef> Args) {
462 static long ArgMax = sysconf(_SC_ARG_MAX);
465 static long ArgMin = _POSIX_ARG_MAX;
468 long EffectiveArgMax = 128 * 1024;
470 if (EffectiveArgMax > ArgMax)
471 EffectiveArgMax = ArgMax;
472 else if (EffectiveArgMax < ArgMin)
473 EffectiveArgMax = ArgMin;
480 long HalfArgMax = EffectiveArgMax / 2;
482 size_t ArgLength = Program.size() + 1;
483 for (StringRef
Arg : Args) {
489 if (
Arg.size() >= (32 * 4096))
492 ArgLength +=
Arg.size() + 1;
493 if (ArgLength >
size_t(HalfArgMax)) {
bool can_execute(const Twine &Path)
Can we execute this file?
This class represents lattice values for constants.
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
std::error_code ChangeStdoutToBinary()
ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
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)
void SplitString(StringRef Source, SmallVectorImpl< StringRef > &OutFragments, StringRef Delimiters=" \\\)
SplitString - Split up the specified string according to the specified delimiters, appending the result fragments to the output list.
The file should be opened in text mode on platforms that make this distinction.
BumpPtrAllocatorImpl BumpPtrAllocator
The standard BumpPtrAllocator which just uses the default template parameters.
std::error_code status(const Twine &path, file_status &result, bool follow=true)
Get file status as if by POSIX stat().
Instrumentation for Order File
bool commandLineFitsWithinSystemLimits(StringRef Program, ArrayRef< StringRef > Args)
Return true if the given arguments fit within system-specific argument length limits.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
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)...
std::error_code ChangeStdinToBinary()
A raw_ostream that writes to a file descriptor.
static bool Execute(ProcessInfo &PI, StringRef Program, ArrayRef< StringRef > Args, Optional< ArrayRef< StringRef >> Env, ArrayRef< Optional< StringRef >> Redirects, unsigned MemoryLimit, std::string *ErrMsg)
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(const basic_file_status &status)
Does file exist?
constexpr char Args[]
Key for Kernel::Metadata::mArgs.