xref: /llvm-project/libc/test/UnitTest/ExecuteFunctionUnix.cpp (revision 0efb376c20b220cddbbcf57f0c82ae048170ffd9)
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 "test/UnitTest/ExecuteFunction.h" // FunctionCaller
12 #include <assert.h>
13 #include <poll.h>
14 #include <signal.h>
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/wait.h>
19 #include <unistd.h>
20 
21 namespace LIBC_NAMESPACE_DECL {
22 namespace testutils {
23 
24 bool ProcessStatus::exited_normally() { return WIFEXITED(platform_defined); }
25 
26 int ProcessStatus::get_exit_code() {
27   assert(exited_normally() && "Abnormal termination, no exit code");
28   return WEXITSTATUS(platform_defined);
29 }
30 
31 int ProcessStatus::get_fatal_signal() {
32   if (exited_normally())
33     return 0;
34   return WTERMSIG(platform_defined);
35 }
36 
37 ProcessStatus invoke_in_subprocess(FunctionCaller *func, unsigned timeout_ms) {
38   int pipe_fds[2];
39   if (::pipe(pipe_fds) == -1)
40     return ProcessStatus::error("pipe(2) failed");
41 
42   // Don't copy the buffers into the child process and print twice.
43   ::fflush(stderr);
44   ::fflush(stdout);
45   pid_t pid = ::fork();
46   if (pid == -1)
47     return ProcessStatus::error("fork(2) failed");
48 
49   if (!pid) {
50     (*func)();
51     ::exit(0);
52   }
53   ::close(pipe_fds[1]);
54 
55   struct pollfd poll_fd {
56     pipe_fds[0], 0, 0
57   };
58   // No events requested so this call will only return after the timeout or if
59   // the pipes peer was closed, signaling the process exited.
60   if (::poll(&poll_fd, 1, timeout_ms) == -1)
61     return ProcessStatus::error("poll(2) failed");
62   // If the pipe wasn't closed by the child yet then timeout has expired.
63   if (!(poll_fd.revents & POLLHUP)) {
64     ::kill(pid, SIGKILL);
65     return ProcessStatus::timed_out_ps();
66   }
67 
68   int wstatus = 0;
69   // Wait on the pid of the subprocess here so it gets collected by the system
70   // and doesn't turn into a zombie.
71   pid_t status = ::waitpid(pid, &wstatus, 0);
72   if (status == -1)
73     return ProcessStatus::error("waitpid(2) failed");
74   assert(status == pid);
75   return {wstatus};
76 }
77 
78 const char *signal_as_string(int signum) { return ::strsignal(signum); }
79 
80 } // namespace testutils
81 } // namespace LIBC_NAMESPACE_DECL
82