Path: blob/main/contrib/kyua/utils/process/operations.cpp
48199 views
// Copyright 2014 The Kyua Authors.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above copyright10// notice, this list of conditions and the following disclaimer in the11// documentation and/or other materials provided with the distribution.12// * Neither the name of Google Inc. nor the names of its contributors13// may be used to endorse or promote products derived from this software14// without specific prior written permission.15//16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2728#include "utils/process/operations.hpp"2930extern "C" {31#include <sys/types.h>32#include <sys/wait.h>3334#include <signal.h>35#include <unistd.h>36}3738#include <cerrno>39#include <cstdlib>40#include <cstring>41#include <iostream>4243#include "utils/format/macros.hpp"44#include "utils/fs/path.hpp"45#include "utils/logging/macros.hpp"46#include "utils/process/exceptions.hpp"47#include "utils/process/system.hpp"48#include "utils/process/status.hpp"49#include "utils/sanity.hpp"50#include "utils/signals/interrupts.hpp"5152namespace fs = utils::fs;53namespace process = utils::process;54namespace signals = utils::signals;555657/// Maximum number of arguments supported by exec.58///59/// We need this limit to avoid having to allocate dynamic memory in the child60/// process to construct the arguments list, which would have side-effects in61/// the parent's memory if we use vfork().62#define MAX_ARGS 128636465namespace {666768/// Exception-based, type-improved version of wait(2).69///70/// \return The PID of the terminated process and its termination status.71///72/// \throw process::system_error If the call to wait(2) fails.73static process::status74safe_wait(void)75{76LD("Waiting for any child process");77int stat_loc;78const pid_t pid = ::wait(&stat_loc);79if (pid == -1) {80const int original_errno = errno;81throw process::system_error("Failed to wait for any child process",82original_errno);83}84return process::status(pid, stat_loc);85}868788/// Exception-based, type-improved version of waitpid(2).89///90/// \param pid The identifier of the process to wait for.91///92/// \return The termination status of the process.93///94/// \throw process::system_error If the call to waitpid(2) fails.95static process::status96safe_waitpid(const pid_t pid)97{98LD(F("Waiting for pid=%s") % pid);99int stat_loc;100if (process::detail::syscall_waitpid(pid, &stat_loc, 0) == -1) {101const int original_errno = errno;102throw process::system_error(F("Failed to wait for PID %s") % pid,103original_errno);104}105return process::status(pid, stat_loc);106}107108109} // anonymous namespace110111112/// Executes an external binary and replaces the current process.113///114/// This function must not use any of the logging features so that the output115/// of the subprocess is not "polluted" by our own messages.116///117/// This function must also not affect the global state of the current process118/// as otherwise we would not be able to use vfork(). Only state stored in the119/// stack can be touched.120///121/// \param program The binary to execute.122/// \param args The arguments to pass to the binary, without the program name.123void124process::exec(const fs::path& program, const args_vector& args) throw()125{126try {127exec_unsafe(program, args);128} catch (const system_error& error) {129// Error message already printed by exec_unsafe.130std::abort();131}132}133134135/// Executes an external binary and replaces the current process.136///137/// This differs from process::exec() in that this function reports errors138/// caused by the exec(2) system call to let the caller decide how to handle139/// them.140///141/// This function must not use any of the logging features so that the output142/// of the subprocess is not "polluted" by our own messages.143///144/// This function must also not affect the global state of the current process145/// as otherwise we would not be able to use vfork(). Only state stored in the146/// stack can be touched.147///148/// \param program The binary to execute.149/// \param args The arguments to pass to the binary, without the program name.150///151/// \throw system_error If the exec(2) call fails.152void153process::exec_unsafe(const fs::path& program, const args_vector& args)154{155PRE(args.size() < MAX_ARGS);156int original_errno = 0;157try {158const char* argv[MAX_ARGS + 1];159160argv[0] = program.c_str();161for (args_vector::size_type i = 0; i < args.size(); i++)162argv[1 + i] = args[i].c_str();163argv[1 + args.size()] = NULL;164165const int ret = ::execv(program.c_str(),166(char* const*)(unsigned long)(const void*)argv);167original_errno = errno;168INV(ret == -1);169std::cerr << "Failed to execute " << program << ": "170<< std::strerror(original_errno) << "\n";171} catch (const std::runtime_error& error) {172std::cerr << "Failed to execute " << program << ": "173<< error.what() << "\n";174std::abort();175} catch (...) {176std::cerr << "Failed to execute " << program << "; got unexpected "177"exception during exec\n";178std::abort();179}180181// We must do this here to prevent our exception from being caught by the182// generic handlers above.183INV(original_errno != 0);184throw system_error("Failed to execute " + program.str(), original_errno);185}186187188/// Forcibly kills a process group started by us.189///190/// This function is safe to call from an signal handler context.191///192/// Pretty much all of our subprocesses run in their own process group so that193/// we can terminate them and thier children should we need to. Because of194/// this, the very first thing our subprocesses do is create a new process group195/// for themselves.196///197/// The implication of the above is that simply issuing a killpg() call on the198/// process group is racy: if the subprocess has not yet had a chance to prepare199/// its own process group, then we will not be killing anything. To solve this,200/// we must also kill() the process group leader itself, and we must do so after201/// the call to killpg(). Doing this is safe because: 1) the process group must202/// have the same ID as the PID of the process that created it; and 2) we have203/// not yet issued a wait() call so we still own the PID.204///205/// The sideffect of doing what we do here is that the process group leader may206/// receive a signal twice. But we don't care because we are forcibly207/// terminating the process group and none of the processes can controlledly208/// react to SIGKILL.209///210/// \param pgid PID or process group ID to terminate.211void212process::terminate_group(const int pgid)213{214(void)::killpg(pgid, SIGKILL);215(void)::kill(pgid, SIGKILL);216}217218219/// Terminates the current process reproducing the given status.220///221/// The caller process is abruptly terminated. In particular, no output streams222/// are flushed, no destructors are called, and no atexit(2) handlers are run.223///224/// \param status The status to "re-deliver" to the caller process.225void226process::terminate_self_with(const status& status)227{228if (status.exited()) {229::_exit(status.exitstatus());230} else {231INV(status.signaled());232(void)::kill(::getpid(), status.termsig());233UNREACHABLE_MSG(F("Signal %s terminated %s but did not terminate "234"ourselves") % status.termsig() % status.dead_pid());235}236}237238239/// Blocks to wait for completion of a subprocess.240///241/// \param pid Identifier of the process to wait for.242///243/// \return The termination status of the child process that terminated.244///245/// \throw process::system_error If the call to wait(2) fails.246process::status247process::wait(const int pid)248{249const process::status status = safe_waitpid(pid);250{251signals::interrupts_inhibiter inhibiter;252signals::remove_pid_to_kill(pid);253}254return status;255}256257258/// Blocks to wait for completion of any subprocess.259///260/// \return The termination status of the child process that terminated.261///262/// \throw process::system_error If the call to wait(2) fails.263process::status264process::wait_any(void)265{266const process::status status = safe_wait();267{268signals::interrupts_inhibiter inhibiter;269signals::remove_pid_to_kill(status.dead_pid());270}271return status;272}273274275