FuzzerUtilDarwin.cpp revision 353358
1326943Sdim//===- FuzzerUtilDarwin.cpp - Misc utils ----------------------------------===//
2326943Sdim//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6326943Sdim//
7326943Sdim//===----------------------------------------------------------------------===//
8326943Sdim// Misc utils for Darwin.
9326943Sdim//===----------------------------------------------------------------------===//
10326943Sdim#include "FuzzerDefs.h"
11326943Sdim#if LIBFUZZER_APPLE
12326943Sdim#include "FuzzerCommand.h"
13326943Sdim#include "FuzzerIO.h"
14326943Sdim#include <mutex>
15326943Sdim#include <signal.h>
16326943Sdim#include <spawn.h>
17326943Sdim#include <stdlib.h>
18326943Sdim#include <string.h>
19326943Sdim#include <sys/wait.h>
20326943Sdim
21326943Sdim// There is no header for this on macOS so declare here
22326943Sdimextern "C" char **environ;
23326943Sdim
24326943Sdimnamespace fuzzer {
25326943Sdim
26326943Sdimstatic std::mutex SignalMutex;
27326943Sdim// Global variables used to keep track of how signal handling should be
28326943Sdim// restored. They should **not** be accessed without holding `SignalMutex`.
29326943Sdimstatic int ActiveThreadCount = 0;
30326943Sdimstatic struct sigaction OldSigIntAction;
31326943Sdimstatic struct sigaction OldSigQuitAction;
32326943Sdimstatic sigset_t OldBlockedSignalsSet;
33326943Sdim
34326943Sdim// This is a reimplementation of Libc's `system()`. On Darwin the Libc
35326943Sdim// implementation contains a mutex which prevents it from being used
36326943Sdim// concurrently. This implementation **can** be used concurrently. It sets the
37326943Sdim// signal handlers when the first thread enters and restores them when the last
38326943Sdim// thread finishes execution of the function and ensures this is not racey by
39326943Sdim// using a mutex.
40326943Sdimint ExecuteCommand(const Command &Cmd) {
41326943Sdim  std::string CmdLine = Cmd.toString();
42326943Sdim  posix_spawnattr_t SpawnAttributes;
43326943Sdim  if (posix_spawnattr_init(&SpawnAttributes))
44326943Sdim    return -1;
45326943Sdim  // Block and ignore signals of the current process when the first thread
46326943Sdim  // enters.
47326943Sdim  {
48326943Sdim    std::lock_guard<std::mutex> Lock(SignalMutex);
49326943Sdim    if (ActiveThreadCount == 0) {
50326943Sdim      static struct sigaction IgnoreSignalAction;
51326943Sdim      sigset_t BlockedSignalsSet;
52326943Sdim      memset(&IgnoreSignalAction, 0, sizeof(IgnoreSignalAction));
53326943Sdim      IgnoreSignalAction.sa_handler = SIG_IGN;
54326943Sdim
55326943Sdim      if (sigaction(SIGINT, &IgnoreSignalAction, &OldSigIntAction) == -1) {
56326943Sdim        Printf("Failed to ignore SIGINT\n");
57326943Sdim        (void)posix_spawnattr_destroy(&SpawnAttributes);
58326943Sdim        return -1;
59326943Sdim      }
60326943Sdim      if (sigaction(SIGQUIT, &IgnoreSignalAction, &OldSigQuitAction) == -1) {
61326943Sdim        Printf("Failed to ignore SIGQUIT\n");
62326943Sdim        // Try our best to restore the signal handlers.
63326943Sdim        (void)sigaction(SIGINT, &OldSigIntAction, NULL);
64326943Sdim        (void)posix_spawnattr_destroy(&SpawnAttributes);
65326943Sdim        return -1;
66326943Sdim      }
67326943Sdim
68326943Sdim      (void)sigemptyset(&BlockedSignalsSet);
69326943Sdim      (void)sigaddset(&BlockedSignalsSet, SIGCHLD);
70326943Sdim      if (sigprocmask(SIG_BLOCK, &BlockedSignalsSet, &OldBlockedSignalsSet) ==
71326943Sdim          -1) {
72326943Sdim        Printf("Failed to block SIGCHLD\n");
73326943Sdim        // Try our best to restore the signal handlers.
74326943Sdim        (void)sigaction(SIGQUIT, &OldSigQuitAction, NULL);
75326943Sdim        (void)sigaction(SIGINT, &OldSigIntAction, NULL);
76326943Sdim        (void)posix_spawnattr_destroy(&SpawnAttributes);
77326943Sdim        return -1;
78326943Sdim      }
79326943Sdim    }
80326943Sdim    ++ActiveThreadCount;
81326943Sdim  }
82326943Sdim
83326943Sdim  // NOTE: Do not introduce any new `return` statements past this
84326943Sdim  // point. It is important that `ActiveThreadCount` always be decremented
85326943Sdim  // when leaving this function.
86326943Sdim
87326943Sdim  // Make sure the child process uses the default handlers for the
88326943Sdim  // following signals rather than inheriting what the parent has.
89326943Sdim  sigset_t DefaultSigSet;
90326943Sdim  (void)sigemptyset(&DefaultSigSet);
91326943Sdim  (void)sigaddset(&DefaultSigSet, SIGQUIT);
92326943Sdim  (void)sigaddset(&DefaultSigSet, SIGINT);
93326943Sdim  (void)posix_spawnattr_setsigdefault(&SpawnAttributes, &DefaultSigSet);
94326943Sdim  // Make sure the child process doesn't block SIGCHLD
95326943Sdim  (void)posix_spawnattr_setsigmask(&SpawnAttributes, &OldBlockedSignalsSet);
96326943Sdim  short SpawnFlags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
97326943Sdim  (void)posix_spawnattr_setflags(&SpawnAttributes, SpawnFlags);
98326943Sdim
99326943Sdim  pid_t Pid;
100326943Sdim  char **Environ = environ; // Read from global
101326943Sdim  const char *CommandCStr = CmdLine.c_str();
102326943Sdim  char *const Argv[] = {
103326943Sdim    strdup("sh"),
104326943Sdim    strdup("-c"),
105326943Sdim    strdup(CommandCStr),
106326943Sdim    NULL
107326943Sdim  };
108326943Sdim  int ErrorCode = 0, ProcessStatus = 0;
109326943Sdim  // FIXME: We probably shouldn't hardcode the shell path.
110326943Sdim  ErrorCode = posix_spawn(&Pid, "/bin/sh", NULL, &SpawnAttributes,
111326943Sdim                          Argv, Environ);
112326943Sdim  (void)posix_spawnattr_destroy(&SpawnAttributes);
113326943Sdim  if (!ErrorCode) {
114326943Sdim    pid_t SavedPid = Pid;
115326943Sdim    do {
116326943Sdim      // Repeat until call completes uninterrupted.
117326943Sdim      Pid = waitpid(SavedPid, &ProcessStatus, /*options=*/0);
118326943Sdim    } while (Pid == -1 && errno == EINTR);
119326943Sdim    if (Pid == -1) {
120326943Sdim      // Fail for some other reason.
121326943Sdim      ProcessStatus = -1;
122326943Sdim    }
123326943Sdim  } else if (ErrorCode == ENOMEM || ErrorCode == EAGAIN) {
124326943Sdim    // Fork failure.
125326943Sdim    ProcessStatus = -1;
126326943Sdim  } else {
127326943Sdim    // Shell execution failure.
128326943Sdim    ProcessStatus = W_EXITCODE(127, 0);
129326943Sdim  }
130326943Sdim  for (unsigned i = 0, n = sizeof(Argv) / sizeof(Argv[0]); i < n; ++i)
131326943Sdim    free(Argv[i]);
132326943Sdim
133326943Sdim  // Restore the signal handlers of the current process when the last thread
134326943Sdim  // using this function finishes.
135326943Sdim  {
136326943Sdim    std::lock_guard<std::mutex> Lock(SignalMutex);
137326943Sdim    --ActiveThreadCount;
138326943Sdim    if (ActiveThreadCount == 0) {
139326943Sdim      bool FailedRestore = false;
140326943Sdim      if (sigaction(SIGINT, &OldSigIntAction, NULL) == -1) {
141326943Sdim        Printf("Failed to restore SIGINT handling\n");
142326943Sdim        FailedRestore = true;
143326943Sdim      }
144326943Sdim      if (sigaction(SIGQUIT, &OldSigQuitAction, NULL) == -1) {
145326943Sdim        Printf("Failed to restore SIGQUIT handling\n");
146326943Sdim        FailedRestore = true;
147326943Sdim      }
148326943Sdim      if (sigprocmask(SIG_BLOCK, &OldBlockedSignalsSet, NULL) == -1) {
149326943Sdim        Printf("Failed to unblock SIGCHLD\n");
150326943Sdim        FailedRestore = true;
151326943Sdim      }
152326943Sdim      if (FailedRestore)
153326943Sdim        ProcessStatus = -1;
154326943Sdim    }
155326943Sdim  }
156326943Sdim  return ProcessStatus;
157326943Sdim}
158326943Sdim
159326943Sdim} // namespace fuzzer
160326943Sdim
161326943Sdim#endif // LIBFUZZER_APPLE
162