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
exited_normally() const23 bool ProcessStatus::exited_normally() const {
24 return WIFEXITED(platform_defined);
25 }
26
get_exit_code() const27 int ProcessStatus::get_exit_code() const {
28 assert(exited_normally() && "Abnormal termination, no exit code");
29 return WEXITSTATUS(platform_defined);
30 }
31
get_fatal_signal() const32 int ProcessStatus::get_fatal_signal() const {
33 if (exited_normally())
34 return 0;
35 return WTERMSIG(platform_defined);
36 }
37
invoke_in_subprocess(FunctionCaller * func,unsigned timeout_ms)38 ProcessStatus invoke_in_subprocess(FunctionCaller *func, unsigned timeout_ms) {
39 std::unique_ptr<FunctionCaller> X(func);
40 int pipe_fds[2];
41 if (::pipe(pipe_fds) == -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(pipe_fds[1]);
56
57 struct pollfd poll_fd {
58 pipe_fds[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(&poll_fd, 1, timeout_ms) == -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 (!(poll_fd.revents & POLLHUP)) {
66 ::kill(pid, SIGKILL);
67 return ProcessStatus::timed_out_ps();
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 return {wstatus};
78 }
79
signal_as_string(int signum)80 const char *signal_as_string(int signum) { return ::strsignal(signum); }
81
82 } // namespace testutils
83 } // namespace __llvm_libc
84