brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.5 KiB · ab18f7a Raw
91 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9#include "ExecuteFunction.h"10#include "src/__support/macros/config.h"11#include "test/UnitTest/ExecuteFunction.h" // FunctionCaller12#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 21namespace LIBC_NAMESPACE_DECL {22namespace testutils {23 24bool ProcessStatus::exited_normally() { return WIFEXITED(platform_defined); }25 26int ProcessStatus::get_exit_code() {27  assert(exited_normally() && "Abnormal termination, no exit code");28  return WEXITSTATUS(platform_defined);29}30 31int ProcessStatus::get_fatal_signal() {32  if (exited_normally())33    return 0;34  return WTERMSIG(platform_defined);35}36 37ProcessStatus invoke_in_subprocess(FunctionCaller *func, int timeout_ms) {38  int pipe_fds[2];39  if (::pipe(pipe_fds) == -1) {40    delete func;41    return ProcessStatus::error("pipe(2) failed");42  }43 44  // Don't copy the buffers into the child process and print twice.45  ::fflush(stderr);46  ::fflush(stdout);47  pid_t pid = ::fork();48  if (pid == -1) {49    delete func;50    return ProcessStatus::error("fork(2) failed");51  }52 53  if (!pid) {54    (*func)();55    delete func;56    ::exit(0);57  }58  ::close(pipe_fds[1]);59 60  pollfd poll_fd{pipe_fds[0], POLLIN, 0};61  // No events requested so this call will only return after the timeout or if62  // the pipes peer was closed, signaling the process exited.63  if (::poll(&poll_fd, 1, timeout_ms) == -1) {64    delete func;65    return ProcessStatus::error("poll(2) failed");66  }67  // If the pipe wasn't closed by the child yet then timeout has expired.68  if (!(poll_fd.revents & POLLHUP)) {69    ::kill(pid, SIGKILL);70    delete func;71    return ProcessStatus::timed_out_ps();72  }73 74  int wstatus = 0;75  // Wait on the pid of the subprocess here so it gets collected by the system76  // and doesn't turn into a zombie.77  pid_t status = ::waitpid(pid, &wstatus, 0);78  if (status == -1) {79    delete func;80    return ProcessStatus::error("waitpid(2) failed");81  }82  assert(status == pid);83  delete func;84  return {wstatus};85}86 87const char *signal_as_string(int signum) { return ::strsignal(signum); }88 89} // namespace testutils90} // namespace LIBC_NAMESPACE_DECL91