1 //===-- ExecuteFunction implementation for Unix-like Systems --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "ExecuteFunction.h" 10 #include "llvm/Support/raw_ostream.h" 11 #include <cassert> 12 #include <cstdlib> 13 #include <memory> 14 #include <poll.h> 15 #include <signal.h> 16 #include <sys/wait.h> 17 #include <unistd.h> 18 19 namespace __llvm_libc { 20 namespace testutils { 21 22 bool ProcessStatus::exitedNormally() const { 23 return WIFEXITED(PlatformDefined); 24 } 25 26 int ProcessStatus::getExitCode() const { 27 assert(exitedNormally() && "Abnormal termination, no exit code"); 28 return WEXITSTATUS(PlatformDefined); 29 } 30 31 int ProcessStatus::getFatalSignal() const { 32 if (exitedNormally()) 33 return 0; 34 return WTERMSIG(PlatformDefined); 35 } 36 37 ProcessStatus invokeInSubprocess(FunctionCaller *Func, unsigned timeoutMS) { 38 std::unique_ptr<FunctionCaller> X(Func); 39 int pipeFDs[2]; 40 if (::pipe(pipeFDs) == -1) 41 return ProcessStatus::Error("pipe(2) failed"); 42 43 // Don't copy the buffers into the child process and print twice. 44 llvm::outs().flush(); 45 llvm::errs().flush(); 46 pid_t Pid = ::fork(); 47 if (Pid == -1) 48 return ProcessStatus::Error("fork(2) failed"); 49 50 if (!Pid) { 51 (*Func)(); 52 std::exit(0); 53 } 54 ::close(pipeFDs[1]); 55 56 struct pollfd pollFD { 57 pipeFDs[0], 0, 0 58 }; 59 // No events requested so this call will only return after the timeout or if 60 // the pipes peer was closed, signaling the process exited. 61 if (::poll(&pollFD, 1, timeoutMS) == -1) 62 return ProcessStatus::Error("poll(2) failed"); 63 // If the pipe wasn't closed by the child yet then timeout has expired. 64 if (!(pollFD.revents & POLLHUP)) { 65 ::kill(Pid, SIGKILL); 66 return ProcessStatus::TimedOut(); 67 } 68 69 int WStatus = 0; 70 // Wait on the pid of the subprocess here so it gets collected by the system 71 // and doesn't turn into a zombie. 72 pid_t status = ::waitpid(Pid, &WStatus, 0); 73 if (status == -1) 74 return ProcessStatus::Error("waitpid(2) failed"); 75 assert(status == Pid); 76 (void)status; 77 return {WStatus}; 78 } 79 80 const char *signalAsString(int Signum) { return ::strsignal(Signum); } 81 82 } // namespace testutils 83 } // namespace __llvm_libc 84