1*b0d29bc4SBrooks Davis // Copyright 2014 The Kyua Authors.
2*b0d29bc4SBrooks Davis // All rights reserved.
3*b0d29bc4SBrooks Davis //
4*b0d29bc4SBrooks Davis // Redistribution and use in source and binary forms, with or without
5*b0d29bc4SBrooks Davis // modification, are permitted provided that the following conditions are
6*b0d29bc4SBrooks Davis // met:
7*b0d29bc4SBrooks Davis //
8*b0d29bc4SBrooks Davis // * Redistributions of source code must retain the above copyright
9*b0d29bc4SBrooks Davis // notice, this list of conditions and the following disclaimer.
10*b0d29bc4SBrooks Davis // * Redistributions in binary form must reproduce the above copyright
11*b0d29bc4SBrooks Davis // notice, this list of conditions and the following disclaimer in the
12*b0d29bc4SBrooks Davis // documentation and/or other materials provided with the distribution.
13*b0d29bc4SBrooks Davis // * Neither the name of Google Inc. nor the names of its contributors
14*b0d29bc4SBrooks Davis // may be used to endorse or promote products derived from this software
15*b0d29bc4SBrooks Davis // without specific prior written permission.
16*b0d29bc4SBrooks Davis //
17*b0d29bc4SBrooks Davis // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18*b0d29bc4SBrooks Davis // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19*b0d29bc4SBrooks Davis // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20*b0d29bc4SBrooks Davis // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21*b0d29bc4SBrooks Davis // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22*b0d29bc4SBrooks Davis // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23*b0d29bc4SBrooks Davis // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24*b0d29bc4SBrooks Davis // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25*b0d29bc4SBrooks Davis // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26*b0d29bc4SBrooks Davis // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27*b0d29bc4SBrooks Davis // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28*b0d29bc4SBrooks Davis
29*b0d29bc4SBrooks Davis #include "utils/process/operations.hpp"
30*b0d29bc4SBrooks Davis
31*b0d29bc4SBrooks Davis extern "C" {
32*b0d29bc4SBrooks Davis #include <sys/types.h>
33*b0d29bc4SBrooks Davis #include <sys/wait.h>
34*b0d29bc4SBrooks Davis
35*b0d29bc4SBrooks Davis #include <signal.h>
36*b0d29bc4SBrooks Davis #include <unistd.h>
37*b0d29bc4SBrooks Davis }
38*b0d29bc4SBrooks Davis
39*b0d29bc4SBrooks Davis #include <cerrno>
40*b0d29bc4SBrooks Davis #include <cstdlib>
41*b0d29bc4SBrooks Davis #include <cstring>
42*b0d29bc4SBrooks Davis #include <iostream>
43*b0d29bc4SBrooks Davis
44*b0d29bc4SBrooks Davis #include "utils/format/macros.hpp"
45*b0d29bc4SBrooks Davis #include "utils/fs/path.hpp"
46*b0d29bc4SBrooks Davis #include "utils/logging/macros.hpp"
47*b0d29bc4SBrooks Davis #include "utils/process/exceptions.hpp"
48*b0d29bc4SBrooks Davis #include "utils/process/system.hpp"
49*b0d29bc4SBrooks Davis #include "utils/process/status.hpp"
50*b0d29bc4SBrooks Davis #include "utils/sanity.hpp"
51*b0d29bc4SBrooks Davis #include "utils/signals/interrupts.hpp"
52*b0d29bc4SBrooks Davis
53*b0d29bc4SBrooks Davis namespace fs = utils::fs;
54*b0d29bc4SBrooks Davis namespace process = utils::process;
55*b0d29bc4SBrooks Davis namespace signals = utils::signals;
56*b0d29bc4SBrooks Davis
57*b0d29bc4SBrooks Davis
58*b0d29bc4SBrooks Davis /// Maximum number of arguments supported by exec.
59*b0d29bc4SBrooks Davis ///
60*b0d29bc4SBrooks Davis /// We need this limit to avoid having to allocate dynamic memory in the child
61*b0d29bc4SBrooks Davis /// process to construct the arguments list, which would have side-effects in
62*b0d29bc4SBrooks Davis /// the parent's memory if we use vfork().
63*b0d29bc4SBrooks Davis #define MAX_ARGS 128
64*b0d29bc4SBrooks Davis
65*b0d29bc4SBrooks Davis
66*b0d29bc4SBrooks Davis namespace {
67*b0d29bc4SBrooks Davis
68*b0d29bc4SBrooks Davis
69*b0d29bc4SBrooks Davis /// Exception-based, type-improved version of wait(2).
70*b0d29bc4SBrooks Davis ///
71*b0d29bc4SBrooks Davis /// \return The PID of the terminated process and its termination status.
72*b0d29bc4SBrooks Davis ///
73*b0d29bc4SBrooks Davis /// \throw process::system_error If the call to wait(2) fails.
74*b0d29bc4SBrooks Davis static process::status
safe_wait(void)75*b0d29bc4SBrooks Davis safe_wait(void)
76*b0d29bc4SBrooks Davis {
77*b0d29bc4SBrooks Davis LD("Waiting for any child process");
78*b0d29bc4SBrooks Davis int stat_loc;
79*b0d29bc4SBrooks Davis const pid_t pid = ::wait(&stat_loc);
80*b0d29bc4SBrooks Davis if (pid == -1) {
81*b0d29bc4SBrooks Davis const int original_errno = errno;
82*b0d29bc4SBrooks Davis throw process::system_error("Failed to wait for any child process",
83*b0d29bc4SBrooks Davis original_errno);
84*b0d29bc4SBrooks Davis }
85*b0d29bc4SBrooks Davis return process::status(pid, stat_loc);
86*b0d29bc4SBrooks Davis }
87*b0d29bc4SBrooks Davis
88*b0d29bc4SBrooks Davis
89*b0d29bc4SBrooks Davis /// Exception-based, type-improved version of waitpid(2).
90*b0d29bc4SBrooks Davis ///
91*b0d29bc4SBrooks Davis /// \param pid The identifier of the process to wait for.
92*b0d29bc4SBrooks Davis ///
93*b0d29bc4SBrooks Davis /// \return The termination status of the process.
94*b0d29bc4SBrooks Davis ///
95*b0d29bc4SBrooks Davis /// \throw process::system_error If the call to waitpid(2) fails.
96*b0d29bc4SBrooks Davis static process::status
safe_waitpid(const pid_t pid)97*b0d29bc4SBrooks Davis safe_waitpid(const pid_t pid)
98*b0d29bc4SBrooks Davis {
99*b0d29bc4SBrooks Davis LD(F("Waiting for pid=%s") % pid);
100*b0d29bc4SBrooks Davis int stat_loc;
101*b0d29bc4SBrooks Davis if (process::detail::syscall_waitpid(pid, &stat_loc, 0) == -1) {
102*b0d29bc4SBrooks Davis const int original_errno = errno;
103*b0d29bc4SBrooks Davis throw process::system_error(F("Failed to wait for PID %s") % pid,
104*b0d29bc4SBrooks Davis original_errno);
105*b0d29bc4SBrooks Davis }
106*b0d29bc4SBrooks Davis return process::status(pid, stat_loc);
107*b0d29bc4SBrooks Davis }
108*b0d29bc4SBrooks Davis
109*b0d29bc4SBrooks Davis
110*b0d29bc4SBrooks Davis } // anonymous namespace
111*b0d29bc4SBrooks Davis
112*b0d29bc4SBrooks Davis
113*b0d29bc4SBrooks Davis /// Executes an external binary and replaces the current process.
114*b0d29bc4SBrooks Davis ///
115*b0d29bc4SBrooks Davis /// This function must not use any of the logging features so that the output
116*b0d29bc4SBrooks Davis /// of the subprocess is not "polluted" by our own messages.
117*b0d29bc4SBrooks Davis ///
118*b0d29bc4SBrooks Davis /// This function must also not affect the global state of the current process
119*b0d29bc4SBrooks Davis /// as otherwise we would not be able to use vfork(). Only state stored in the
120*b0d29bc4SBrooks Davis /// stack can be touched.
121*b0d29bc4SBrooks Davis ///
122*b0d29bc4SBrooks Davis /// \param program The binary to execute.
123*b0d29bc4SBrooks Davis /// \param args The arguments to pass to the binary, without the program name.
124*b0d29bc4SBrooks Davis void
exec(const fs::path & program,const args_vector & args)125*b0d29bc4SBrooks Davis process::exec(const fs::path& program, const args_vector& args) throw()
126*b0d29bc4SBrooks Davis {
127*b0d29bc4SBrooks Davis try {
128*b0d29bc4SBrooks Davis exec_unsafe(program, args);
129*b0d29bc4SBrooks Davis } catch (const system_error& error) {
130*b0d29bc4SBrooks Davis // Error message already printed by exec_unsafe.
131*b0d29bc4SBrooks Davis std::abort();
132*b0d29bc4SBrooks Davis }
133*b0d29bc4SBrooks Davis }
134*b0d29bc4SBrooks Davis
135*b0d29bc4SBrooks Davis
136*b0d29bc4SBrooks Davis /// Executes an external binary and replaces the current process.
137*b0d29bc4SBrooks Davis ///
138*b0d29bc4SBrooks Davis /// This differs from process::exec() in that this function reports errors
139*b0d29bc4SBrooks Davis /// caused by the exec(2) system call to let the caller decide how to handle
140*b0d29bc4SBrooks Davis /// them.
141*b0d29bc4SBrooks Davis ///
142*b0d29bc4SBrooks Davis /// This function must not use any of the logging features so that the output
143*b0d29bc4SBrooks Davis /// of the subprocess is not "polluted" by our own messages.
144*b0d29bc4SBrooks Davis ///
145*b0d29bc4SBrooks Davis /// This function must also not affect the global state of the current process
146*b0d29bc4SBrooks Davis /// as otherwise we would not be able to use vfork(). Only state stored in the
147*b0d29bc4SBrooks Davis /// stack can be touched.
148*b0d29bc4SBrooks Davis ///
149*b0d29bc4SBrooks Davis /// \param program The binary to execute.
150*b0d29bc4SBrooks Davis /// \param args The arguments to pass to the binary, without the program name.
151*b0d29bc4SBrooks Davis ///
152*b0d29bc4SBrooks Davis /// \throw system_error If the exec(2) call fails.
153*b0d29bc4SBrooks Davis void
exec_unsafe(const fs::path & program,const args_vector & args)154*b0d29bc4SBrooks Davis process::exec_unsafe(const fs::path& program, const args_vector& args)
155*b0d29bc4SBrooks Davis {
156*b0d29bc4SBrooks Davis PRE(args.size() < MAX_ARGS);
157*b0d29bc4SBrooks Davis int original_errno = 0;
158*b0d29bc4SBrooks Davis try {
159*b0d29bc4SBrooks Davis const char* argv[MAX_ARGS + 1];
160*b0d29bc4SBrooks Davis
161*b0d29bc4SBrooks Davis argv[0] = program.c_str();
162*b0d29bc4SBrooks Davis for (args_vector::size_type i = 0; i < args.size(); i++)
163*b0d29bc4SBrooks Davis argv[1 + i] = args[i].c_str();
164*b0d29bc4SBrooks Davis argv[1 + args.size()] = NULL;
165*b0d29bc4SBrooks Davis
166*b0d29bc4SBrooks Davis const int ret = ::execv(program.c_str(),
167*b0d29bc4SBrooks Davis (char* const*)(unsigned long)(const void*)argv);
168*b0d29bc4SBrooks Davis original_errno = errno;
169*b0d29bc4SBrooks Davis INV(ret == -1);
170*b0d29bc4SBrooks Davis std::cerr << "Failed to execute " << program << ": "
171*b0d29bc4SBrooks Davis << std::strerror(original_errno) << "\n";
172*b0d29bc4SBrooks Davis } catch (const std::runtime_error& error) {
173*b0d29bc4SBrooks Davis std::cerr << "Failed to execute " << program << ": "
174*b0d29bc4SBrooks Davis << error.what() << "\n";
175*b0d29bc4SBrooks Davis std::abort();
176*b0d29bc4SBrooks Davis } catch (...) {
177*b0d29bc4SBrooks Davis std::cerr << "Failed to execute " << program << "; got unexpected "
178*b0d29bc4SBrooks Davis "exception during exec\n";
179*b0d29bc4SBrooks Davis std::abort();
180*b0d29bc4SBrooks Davis }
181*b0d29bc4SBrooks Davis
182*b0d29bc4SBrooks Davis // We must do this here to prevent our exception from being caught by the
183*b0d29bc4SBrooks Davis // generic handlers above.
184*b0d29bc4SBrooks Davis INV(original_errno != 0);
185*b0d29bc4SBrooks Davis throw system_error("Failed to execute " + program.str(), original_errno);
186*b0d29bc4SBrooks Davis }
187*b0d29bc4SBrooks Davis
188*b0d29bc4SBrooks Davis
189*b0d29bc4SBrooks Davis /// Forcibly kills a process group started by us.
190*b0d29bc4SBrooks Davis ///
191*b0d29bc4SBrooks Davis /// This function is safe to call from an signal handler context.
192*b0d29bc4SBrooks Davis ///
193*b0d29bc4SBrooks Davis /// Pretty much all of our subprocesses run in their own process group so that
194*b0d29bc4SBrooks Davis /// we can terminate them and thier children should we need to. Because of
195*b0d29bc4SBrooks Davis /// this, the very first thing our subprocesses do is create a new process group
196*b0d29bc4SBrooks Davis /// for themselves.
197*b0d29bc4SBrooks Davis ///
198*b0d29bc4SBrooks Davis /// The implication of the above is that simply issuing a killpg() call on the
199*b0d29bc4SBrooks Davis /// process group is racy: if the subprocess has not yet had a chance to prepare
200*b0d29bc4SBrooks Davis /// its own process group, then we will not be killing anything. To solve this,
201*b0d29bc4SBrooks Davis /// we must also kill() the process group leader itself, and we must do so after
202*b0d29bc4SBrooks Davis /// the call to killpg(). Doing this is safe because: 1) the process group must
203*b0d29bc4SBrooks Davis /// have the same ID as the PID of the process that created it; and 2) we have
204*b0d29bc4SBrooks Davis /// not yet issued a wait() call so we still own the PID.
205*b0d29bc4SBrooks Davis ///
206*b0d29bc4SBrooks Davis /// The sideffect of doing what we do here is that the process group leader may
207*b0d29bc4SBrooks Davis /// receive a signal twice. But we don't care because we are forcibly
208*b0d29bc4SBrooks Davis /// terminating the process group and none of the processes can controlledly
209*b0d29bc4SBrooks Davis /// react to SIGKILL.
210*b0d29bc4SBrooks Davis ///
211*b0d29bc4SBrooks Davis /// \param pgid PID or process group ID to terminate.
212*b0d29bc4SBrooks Davis void
terminate_group(const int pgid)213*b0d29bc4SBrooks Davis process::terminate_group(const int pgid)
214*b0d29bc4SBrooks Davis {
215*b0d29bc4SBrooks Davis (void)::killpg(pgid, SIGKILL);
216*b0d29bc4SBrooks Davis (void)::kill(pgid, SIGKILL);
217*b0d29bc4SBrooks Davis }
218*b0d29bc4SBrooks Davis
219*b0d29bc4SBrooks Davis
220*b0d29bc4SBrooks Davis /// Terminates the current process reproducing the given status.
221*b0d29bc4SBrooks Davis ///
222*b0d29bc4SBrooks Davis /// The caller process is abruptly terminated. In particular, no output streams
223*b0d29bc4SBrooks Davis /// are flushed, no destructors are called, and no atexit(2) handlers are run.
224*b0d29bc4SBrooks Davis ///
225*b0d29bc4SBrooks Davis /// \param status The status to "re-deliver" to the caller process.
226*b0d29bc4SBrooks Davis void
terminate_self_with(const status & status)227*b0d29bc4SBrooks Davis process::terminate_self_with(const status& status)
228*b0d29bc4SBrooks Davis {
229*b0d29bc4SBrooks Davis if (status.exited()) {
230*b0d29bc4SBrooks Davis ::_exit(status.exitstatus());
231*b0d29bc4SBrooks Davis } else {
232*b0d29bc4SBrooks Davis INV(status.signaled());
233*b0d29bc4SBrooks Davis (void)::kill(::getpid(), status.termsig());
234*b0d29bc4SBrooks Davis UNREACHABLE_MSG(F("Signal %s terminated %s but did not terminate "
235*b0d29bc4SBrooks Davis "ourselves") % status.termsig() % status.dead_pid());
236*b0d29bc4SBrooks Davis }
237*b0d29bc4SBrooks Davis }
238*b0d29bc4SBrooks Davis
239*b0d29bc4SBrooks Davis
240*b0d29bc4SBrooks Davis /// Blocks to wait for completion of a subprocess.
241*b0d29bc4SBrooks Davis ///
242*b0d29bc4SBrooks Davis /// \param pid Identifier of the process to wait for.
243*b0d29bc4SBrooks Davis ///
244*b0d29bc4SBrooks Davis /// \return The termination status of the child process that terminated.
245*b0d29bc4SBrooks Davis ///
246*b0d29bc4SBrooks Davis /// \throw process::system_error If the call to wait(2) fails.
247*b0d29bc4SBrooks Davis process::status
wait(const int pid)248*b0d29bc4SBrooks Davis process::wait(const int pid)
249*b0d29bc4SBrooks Davis {
250*b0d29bc4SBrooks Davis const process::status status = safe_waitpid(pid);
251*b0d29bc4SBrooks Davis {
252*b0d29bc4SBrooks Davis signals::interrupts_inhibiter inhibiter;
253*b0d29bc4SBrooks Davis signals::remove_pid_to_kill(pid);
254*b0d29bc4SBrooks Davis }
255*b0d29bc4SBrooks Davis return status;
256*b0d29bc4SBrooks Davis }
257*b0d29bc4SBrooks Davis
258*b0d29bc4SBrooks Davis
259*b0d29bc4SBrooks Davis /// Blocks to wait for completion of any subprocess.
260*b0d29bc4SBrooks Davis ///
261*b0d29bc4SBrooks Davis /// \return The termination status of the child process that terminated.
262*b0d29bc4SBrooks Davis ///
263*b0d29bc4SBrooks Davis /// \throw process::system_error If the call to wait(2) fails.
264*b0d29bc4SBrooks Davis process::status
wait_any(void)265*b0d29bc4SBrooks Davis process::wait_any(void)
266*b0d29bc4SBrooks Davis {
267*b0d29bc4SBrooks Davis const process::status status = safe_wait();
268*b0d29bc4SBrooks Davis {
269*b0d29bc4SBrooks Davis signals::interrupts_inhibiter inhibiter;
270*b0d29bc4SBrooks Davis signals::remove_pid_to_kill(status.dead_pid());
271*b0d29bc4SBrooks Davis }
272*b0d29bc4SBrooks Davis return status;
273*b0d29bc4SBrooks Davis }
274