108334c51SBrooks Davis // Copyright 2014 The Kyua Authors.
208334c51SBrooks Davis // All rights reserved.
308334c51SBrooks Davis //
408334c51SBrooks Davis // Redistribution and use in source and binary forms, with or without
508334c51SBrooks Davis // modification, are permitted provided that the following conditions are
608334c51SBrooks Davis // met:
708334c51SBrooks Davis //
808334c51SBrooks Davis // * Redistributions of source code must retain the above copyright
908334c51SBrooks Davis // notice, this list of conditions and the following disclaimer.
1008334c51SBrooks Davis // * Redistributions in binary form must reproduce the above copyright
1108334c51SBrooks Davis // notice, this list of conditions and the following disclaimer in the
1208334c51SBrooks Davis // documentation and/or other materials provided with the distribution.
1308334c51SBrooks Davis // * Neither the name of Google Inc. nor the names of its contributors
1408334c51SBrooks Davis // may be used to endorse or promote products derived from this software
1508334c51SBrooks Davis // without specific prior written permission.
1608334c51SBrooks Davis //
1708334c51SBrooks Davis // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1808334c51SBrooks Davis // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1908334c51SBrooks Davis // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2008334c51SBrooks Davis // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2108334c51SBrooks Davis // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2208334c51SBrooks Davis // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2308334c51SBrooks Davis // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2408334c51SBrooks Davis // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2508334c51SBrooks Davis // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2608334c51SBrooks Davis // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2708334c51SBrooks Davis // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2808334c51SBrooks Davis
2908334c51SBrooks Davis #include "utils/process/operations.hpp"
3008334c51SBrooks Davis
3108334c51SBrooks Davis extern "C" {
3208334c51SBrooks Davis #include <sys/types.h>
3308334c51SBrooks Davis #include <sys/wait.h>
3408334c51SBrooks Davis
3508334c51SBrooks Davis #include <signal.h>
3608334c51SBrooks Davis #include <unistd.h>
3708334c51SBrooks Davis }
3808334c51SBrooks Davis
3908334c51SBrooks Davis #include <cerrno>
4008334c51SBrooks Davis #include <cstdlib>
4108334c51SBrooks Davis #include <cstring>
4208334c51SBrooks Davis #include <iostream>
4308334c51SBrooks Davis
4408334c51SBrooks Davis #include "utils/format/macros.hpp"
4508334c51SBrooks Davis #include "utils/fs/path.hpp"
4608334c51SBrooks Davis #include "utils/logging/macros.hpp"
4708334c51SBrooks Davis #include "utils/process/exceptions.hpp"
4808334c51SBrooks Davis #include "utils/process/system.hpp"
4908334c51SBrooks Davis #include "utils/process/status.hpp"
5008334c51SBrooks Davis #include "utils/sanity.hpp"
5108334c51SBrooks Davis #include "utils/signals/interrupts.hpp"
5208334c51SBrooks Davis
5308334c51SBrooks Davis namespace fs = utils::fs;
5408334c51SBrooks Davis namespace process = utils::process;
5508334c51SBrooks Davis namespace signals = utils::signals;
5608334c51SBrooks Davis
5708334c51SBrooks Davis
5808334c51SBrooks Davis /// Maximum number of arguments supported by exec.
5908334c51SBrooks Davis ///
6008334c51SBrooks Davis /// We need this limit to avoid having to allocate dynamic memory in the child
6108334c51SBrooks Davis /// process to construct the arguments list, which would have side-effects in
6208334c51SBrooks Davis /// the parent's memory if we use vfork().
6308334c51SBrooks Davis #define MAX_ARGS 128
6408334c51SBrooks Davis
6508334c51SBrooks Davis
6608334c51SBrooks Davis namespace {
6708334c51SBrooks Davis
6808334c51SBrooks Davis
6908334c51SBrooks Davis /// Exception-based, type-improved version of wait(2).
7008334c51SBrooks Davis ///
7108334c51SBrooks Davis /// \return The PID of the terminated process and its termination status.
7208334c51SBrooks Davis ///
7308334c51SBrooks Davis /// \throw process::system_error If the call to wait(2) fails.
7408334c51SBrooks Davis static process::status
safe_wait(void)7508334c51SBrooks Davis safe_wait(void)
7608334c51SBrooks Davis {
7708334c51SBrooks Davis LD("Waiting for any child process");
7808334c51SBrooks Davis int stat_loc;
7908334c51SBrooks Davis const pid_t pid = ::wait(&stat_loc);
8008334c51SBrooks Davis if (pid == -1) {
8108334c51SBrooks Davis const int original_errno = errno;
8208334c51SBrooks Davis throw process::system_error("Failed to wait for any child process",
8308334c51SBrooks Davis original_errno);
8408334c51SBrooks Davis }
8508334c51SBrooks Davis return process::status(pid, stat_loc);
8608334c51SBrooks Davis }
8708334c51SBrooks Davis
8808334c51SBrooks Davis
8908334c51SBrooks Davis /// Exception-based, type-improved version of waitpid(2).
9008334c51SBrooks Davis ///
9108334c51SBrooks Davis /// \param pid The identifier of the process to wait for.
9208334c51SBrooks Davis ///
9308334c51SBrooks Davis /// \return The termination status of the process.
9408334c51SBrooks Davis ///
9508334c51SBrooks Davis /// \throw process::system_error If the call to waitpid(2) fails.
9608334c51SBrooks Davis static process::status
safe_waitpid(const pid_t pid)9708334c51SBrooks Davis safe_waitpid(const pid_t pid)
9808334c51SBrooks Davis {
9908334c51SBrooks Davis LD(F("Waiting for pid=%s") % pid);
10008334c51SBrooks Davis int stat_loc;
10108334c51SBrooks Davis if (process::detail::syscall_waitpid(pid, &stat_loc, 0) == -1) {
10208334c51SBrooks Davis const int original_errno = errno;
10308334c51SBrooks Davis throw process::system_error(F("Failed to wait for PID %s") % pid,
10408334c51SBrooks Davis original_errno);
10508334c51SBrooks Davis }
10608334c51SBrooks Davis return process::status(pid, stat_loc);
10708334c51SBrooks Davis }
10808334c51SBrooks Davis
10908334c51SBrooks Davis
11008334c51SBrooks Davis } // anonymous namespace
11108334c51SBrooks Davis
11208334c51SBrooks Davis
11308334c51SBrooks Davis /// Executes an external binary and replaces the current process.
11408334c51SBrooks Davis ///
11508334c51SBrooks Davis /// This function must not use any of the logging features so that the output
11608334c51SBrooks Davis /// of the subprocess is not "polluted" by our own messages.
11708334c51SBrooks Davis ///
11808334c51SBrooks Davis /// This function must also not affect the global state of the current process
11908334c51SBrooks Davis /// as otherwise we would not be able to use vfork(). Only state stored in the
12008334c51SBrooks Davis /// stack can be touched.
12108334c51SBrooks Davis ///
12208334c51SBrooks Davis /// \param program The binary to execute.
12308334c51SBrooks Davis /// \param args The arguments to pass to the binary, without the program name.
12408334c51SBrooks Davis void
exec(const fs::path & program,const args_vector & args)12508334c51SBrooks Davis process::exec(const fs::path& program, const args_vector& args) throw()
12608334c51SBrooks Davis {
12708334c51SBrooks Davis try {
12808334c51SBrooks Davis exec_unsafe(program, args);
12908334c51SBrooks Davis } catch (const system_error& error) {
13008334c51SBrooks Davis // Error message already printed by exec_unsafe.
13108334c51SBrooks Davis std::abort();
13208334c51SBrooks Davis }
13308334c51SBrooks Davis }
13408334c51SBrooks Davis
13508334c51SBrooks Davis
13608334c51SBrooks Davis /// Executes an external binary and replaces the current process.
13708334c51SBrooks Davis ///
13808334c51SBrooks Davis /// This differs from process::exec() in that this function reports errors
13908334c51SBrooks Davis /// caused by the exec(2) system call to let the caller decide how to handle
14008334c51SBrooks Davis /// them.
14108334c51SBrooks Davis ///
14208334c51SBrooks Davis /// This function must not use any of the logging features so that the output
14308334c51SBrooks Davis /// of the subprocess is not "polluted" by our own messages.
14408334c51SBrooks Davis ///
14508334c51SBrooks Davis /// This function must also not affect the global state of the current process
14608334c51SBrooks Davis /// as otherwise we would not be able to use vfork(). Only state stored in the
14708334c51SBrooks Davis /// stack can be touched.
14808334c51SBrooks Davis ///
14908334c51SBrooks Davis /// \param program The binary to execute.
15008334c51SBrooks Davis /// \param args The arguments to pass to the binary, without the program name.
15108334c51SBrooks Davis ///
15208334c51SBrooks Davis /// \throw system_error If the exec(2) call fails.
15308334c51SBrooks Davis void
exec_unsafe(const fs::path & program,const args_vector & args)15408334c51SBrooks Davis process::exec_unsafe(const fs::path& program, const args_vector& args)
15508334c51SBrooks Davis {
15608334c51SBrooks Davis PRE(args.size() < MAX_ARGS);
15708334c51SBrooks Davis int original_errno = 0;
15808334c51SBrooks Davis try {
15908334c51SBrooks Davis const char* argv[MAX_ARGS + 1];
16008334c51SBrooks Davis
16108334c51SBrooks Davis argv[0] = program.c_str();
16208334c51SBrooks Davis for (args_vector::size_type i = 0; i < args.size(); i++)
16308334c51SBrooks Davis argv[1 + i] = args[i].c_str();
16408334c51SBrooks Davis argv[1 + args.size()] = NULL;
16508334c51SBrooks Davis
16608334c51SBrooks Davis const int ret = ::execv(program.c_str(),
16708334c51SBrooks Davis (char* const*)(unsigned long)(const void*)argv);
16808334c51SBrooks Davis original_errno = errno;
16908334c51SBrooks Davis INV(ret == -1);
17008334c51SBrooks Davis std::cerr << "Failed to execute " << program << ": "
17108334c51SBrooks Davis << std::strerror(original_errno) << "\n";
17208334c51SBrooks Davis } catch (const std::runtime_error& error) {
17308334c51SBrooks Davis std::cerr << "Failed to execute " << program << ": "
17408334c51SBrooks Davis << error.what() << "\n";
17508334c51SBrooks Davis std::abort();
17608334c51SBrooks Davis } catch (...) {
17708334c51SBrooks Davis std::cerr << "Failed to execute " << program << "; got unexpected "
17808334c51SBrooks Davis "exception during exec\n";
17908334c51SBrooks Davis std::abort();
18008334c51SBrooks Davis }
18108334c51SBrooks Davis
18208334c51SBrooks Davis // We must do this here to prevent our exception from being caught by the
18308334c51SBrooks Davis // generic handlers above.
18408334c51SBrooks Davis INV(original_errno != 0);
18508334c51SBrooks Davis throw system_error("Failed to execute " + program.str(), original_errno);
18608334c51SBrooks Davis }
18708334c51SBrooks Davis
18808334c51SBrooks Davis
18908334c51SBrooks Davis /// Forcibly kills a process group started by us.
19008334c51SBrooks Davis ///
19108334c51SBrooks Davis /// This function is safe to call from an signal handler context.
19208334c51SBrooks Davis ///
19308334c51SBrooks Davis /// Pretty much all of our subprocesses run in their own process group so that
19408334c51SBrooks Davis /// we can terminate them and thier children should we need to. Because of
19508334c51SBrooks Davis /// this, the very first thing our subprocesses do is create a new process group
19608334c51SBrooks Davis /// for themselves.
19708334c51SBrooks Davis ///
19808334c51SBrooks Davis /// The implication of the above is that simply issuing a killpg() call on the
19908334c51SBrooks Davis /// process group is racy: if the subprocess has not yet had a chance to prepare
20008334c51SBrooks Davis /// its own process group, then we will not be killing anything. To solve this,
20108334c51SBrooks Davis /// we must also kill() the process group leader itself, and we must do so after
20208334c51SBrooks Davis /// the call to killpg(). Doing this is safe because: 1) the process group must
20308334c51SBrooks Davis /// have the same ID as the PID of the process that created it; and 2) we have
20408334c51SBrooks Davis /// not yet issued a wait() call so we still own the PID.
20508334c51SBrooks Davis ///
20608334c51SBrooks Davis /// The sideffect of doing what we do here is that the process group leader may
20708334c51SBrooks Davis /// receive a signal twice. But we don't care because we are forcibly
20808334c51SBrooks Davis /// terminating the process group and none of the processes can controlledly
20908334c51SBrooks Davis /// react to SIGKILL.
21008334c51SBrooks Davis ///
21108334c51SBrooks Davis /// \param pgid PID or process group ID to terminate.
21208334c51SBrooks Davis void
terminate_group(const int pgid)21308334c51SBrooks Davis process::terminate_group(const int pgid)
21408334c51SBrooks Davis {
21508334c51SBrooks Davis (void)::killpg(pgid, SIGKILL);
21608334c51SBrooks Davis (void)::kill(pgid, SIGKILL);
21708334c51SBrooks Davis }
21808334c51SBrooks Davis
21908334c51SBrooks Davis
22008334c51SBrooks Davis /// Terminates the current process reproducing the given status.
22108334c51SBrooks Davis ///
22208334c51SBrooks Davis /// The caller process is abruptly terminated. In particular, no output streams
22308334c51SBrooks Davis /// are flushed, no destructors are called, and no atexit(2) handlers are run.
22408334c51SBrooks Davis ///
22508334c51SBrooks Davis /// \param status The status to "re-deliver" to the caller process.
22608334c51SBrooks Davis void
terminate_self_with(const status & status)22708334c51SBrooks Davis process::terminate_self_with(const status& status)
22808334c51SBrooks Davis {
22908334c51SBrooks Davis if (status.exited()) {
23008334c51SBrooks Davis ::_exit(status.exitstatus());
23108334c51SBrooks Davis } else {
23208334c51SBrooks Davis INV(status.signaled());
23308334c51SBrooks Davis (void)::kill(::getpid(), status.termsig());
23408334c51SBrooks Davis UNREACHABLE_MSG(F("Signal %s terminated %s but did not terminate "
23508334c51SBrooks Davis "ourselves") % status.termsig() % status.dead_pid());
23608334c51SBrooks Davis }
23708334c51SBrooks Davis }
23808334c51SBrooks Davis
23908334c51SBrooks Davis
24008334c51SBrooks Davis /// Blocks to wait for completion of a subprocess.
24108334c51SBrooks Davis ///
24208334c51SBrooks Davis /// \param pid Identifier of the process to wait for.
24308334c51SBrooks Davis ///
24408334c51SBrooks Davis /// \return The termination status of the child process that terminated.
24508334c51SBrooks Davis ///
24608334c51SBrooks Davis /// \throw process::system_error If the call to wait(2) fails.
24708334c51SBrooks Davis process::status
wait(const int pid)24808334c51SBrooks Davis process::wait(const int pid)
24908334c51SBrooks Davis {
25008334c51SBrooks Davis const process::status status = safe_waitpid(pid);
25108334c51SBrooks Davis {
25208334c51SBrooks Davis signals::interrupts_inhibiter inhibiter;
25308334c51SBrooks Davis signals::remove_pid_to_kill(pid);
25408334c51SBrooks Davis }
25508334c51SBrooks Davis return status;
25608334c51SBrooks Davis }
25708334c51SBrooks Davis
25808334c51SBrooks Davis
25908334c51SBrooks Davis /// Blocks to wait for completion of any subprocess.
26008334c51SBrooks Davis ///
26108334c51SBrooks Davis /// \return The termination status of the child process that terminated.
26208334c51SBrooks Davis ///
26308334c51SBrooks Davis /// \throw process::system_error If the call to wait(2) fails.
26408334c51SBrooks Davis process::status
wait_any(void)26508334c51SBrooks Davis process::wait_any(void)
26608334c51SBrooks Davis {
26708334c51SBrooks Davis const process::status status = safe_wait();
26808334c51SBrooks Davis {
26908334c51SBrooks Davis signals::interrupts_inhibiter inhibiter;
27008334c51SBrooks Davis signals::remove_pid_to_kill(status.dead_pid());
27108334c51SBrooks Davis }
27208334c51SBrooks Davis return status;
27308334c51SBrooks Davis }
274