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