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 <cassert>
11 #include <cstdlib>
12 #include <cstring>
13 #include <iostream>
14 #include <memory>
15 #include <poll.h>
16 #include <signal.h>
17 #include <sys/wait.h>
18 #include <unistd.h>
19
20 namespace __llvm_libc {
21 namespace testutils {
22
exitedNormally() const23 bool ProcessStatus::exitedNormally() const {
24 return WIFEXITED(PlatformDefined);
25 }
26
getExitCode() const27 int ProcessStatus::getExitCode() const {
28 assert(exitedNormally() && "Abnormal termination, no exit code");
29 return WEXITSTATUS(PlatformDefined);
30 }
31
getFatalSignal() const32 int ProcessStatus::getFatalSignal() const {
33 if (exitedNormally())
34 return 0;
35 return WTERMSIG(PlatformDefined);
36 }
37
invokeInSubprocess(FunctionCaller * Func,unsigned timeoutMS)38 ProcessStatus invokeInSubprocess(FunctionCaller *Func, unsigned timeoutMS) {
39 std::unique_ptr<FunctionCaller> X(Func);
40 int pipeFDs[2];
41 if (::pipe(pipeFDs) == -1)
42 return ProcessStatus::Error("pipe(2) failed");
43
44 // Don't copy the buffers into the child process and print twice.
45 std::cout.flush();
46 std::cerr.flush();
47 pid_t Pid = ::fork();
48 if (Pid == -1)
49 return ProcessStatus::Error("fork(2) failed");
50
51 if (!Pid) {
52 (*Func)();
53 std::exit(0);
54 }
55 ::close(pipeFDs[1]);
56
57 struct pollfd pollFD {
58 pipeFDs[0], 0, 0
59 };
60 // No events requested so this call will only return after the timeout or if
61 // the pipes peer was closed, signaling the process exited.
62 if (::poll(&pollFD, 1, timeoutMS) == -1)
63 return ProcessStatus::Error("poll(2) failed");
64 // If the pipe wasn't closed by the child yet then timeout has expired.
65 if (!(pollFD.revents & POLLHUP)) {
66 ::kill(Pid, SIGKILL);
67 return ProcessStatus::TimedOut();
68 }
69
70 int WStatus = 0;
71 // Wait on the pid of the subprocess here so it gets collected by the system
72 // and doesn't turn into a zombie.
73 pid_t status = ::waitpid(Pid, &WStatus, 0);
74 if (status == -1)
75 return ProcessStatus::Error("waitpid(2) failed");
76 assert(status == Pid);
77 (void)status;
78 return {WStatus};
79 }
80
signalAsString(int Signum)81 const char *signalAsString(int Signum) { return ::strsignal(Signum); }
82
83 } // namespace testutils
84 } // namespace __llvm_libc
85