xref: /aosp_15_r20/external/llvm-libc/test/UnitTest/ExecuteFunctionUnix.cpp (revision 71db0c75aadcf003ffe3238005f61d7618a3fead)
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 "src/__support/macros/config.h"
11 #include <cassert>
12 #include <cstdlib>
13 #include <cstring>
14 #include <iostream>
15 #include <memory>
16 #include <poll.h>
17 #include <signal.h>
18 #include <sys/wait.h>
19 #include <unistd.h>
20 
21 namespace LIBC_NAMESPACE_DECL {
22 namespace testutils {
23 
exited_normally()24 bool ProcessStatus::exited_normally() { return WIFEXITED(platform_defined); }
25 
get_exit_code()26 int ProcessStatus::get_exit_code() {
27   assert(exited_normally() && "Abnormal termination, no exit code");
28   return WEXITSTATUS(platform_defined);
29 }
30 
get_fatal_signal()31 int ProcessStatus::get_fatal_signal() {
32   if (exited_normally())
33     return 0;
34   return WTERMSIG(platform_defined);
35 }
36 
invoke_in_subprocess(FunctionCaller * func,unsigned timeout_ms)37 ProcessStatus invoke_in_subprocess(FunctionCaller *func, unsigned timeout_ms) {
38   std::unique_ptr<FunctionCaller> X(func);
39   int pipe_fds[2];
40   if (::pipe(pipe_fds) == -1)
41     return ProcessStatus::error("pipe(2) failed");
42 
43   // Don't copy the buffers into the child process and print twice.
44   std::cout.flush();
45   std::cerr.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(pipe_fds[1]);
55 
56   struct pollfd poll_fd {
57     pipe_fds[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(&poll_fd, 1, timeout_ms) == -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 (!(poll_fd.revents & POLLHUP)) {
65     ::kill(pid, SIGKILL);
66     return ProcessStatus::timed_out_ps();
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   return {wstatus};
77 }
78 
signal_as_string(int signum)79 const char *signal_as_string(int signum) { return ::strsignal(signum); }
80 
81 } // namespace testutils
82 } // namespace LIBC_NAMESPACE_DECL
83