blob: 44734dc59f32d942187a3c4e93bbe5a1ab436b2d [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 The Android Open Source Project
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15//
adlr@google.com3defe6a2009-12-04 20:57:17 +000016
Alex Deymo39910dc2015-11-09 17:04:30 -080017#include "update_engine/common/subprocess.h"
Darin Petkova0b9e772011-10-06 05:05:56 -070018
Alex Deymo29b81532015-07-09 11:51:49 -070019#include <fcntl.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000020#include <stdlib.h>
21#include <string.h>
Kenneth Watersa7fcafa2010-09-21 10:27:03 -070022#include <unistd.h>
Darin Petkova0b9e772011-10-06 05:05:56 -070023
Kelvin Zhang866d4702023-10-24 12:37:35 -070024#include <chrono>
Ben Chan02f7c1d2014-10-18 15:18:02 -070025#include <memory>
Darin Petkova0b9e772011-10-06 05:05:56 -070026#include <string>
Amin Hassania8859542018-03-07 16:24:43 -080027#include <utility>
adlr@google.com3defe6a2009-12-04 20:57:17 +000028#include <vector>
Darin Petkova0b9e772011-10-06 05:05:56 -070029
Alex Deymo29b81532015-07-09 11:51:49 -070030#include <base/bind.h>
Darin Petkova0b9e772011-10-06 05:05:56 -070031#include <base/logging.h>
Alex Deymo29b81532015-07-09 11:51:49 -070032#include <base/posix/eintr_wrapper.h>
Alex Vakulenko75039d72014-03-25 12:36:28 -070033#include <base/strings/string_util.h>
Kelvin Zhangb9a9aa22024-10-15 10:38:35 -070034#include <android-base/stringprintf.h>
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070035#include <brillo/secure_blob.h>
adlr@google.com3defe6a2009-12-04 20:57:17 +000036
Alex Deymo0d298542016-03-30 18:31:49 -070037#include "update_engine/common/utils.h"
38
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070039using brillo::MessageLoop;
adlr@google.com3defe6a2009-12-04 20:57:17 +000040using std::string;
Ben Chan02f7c1d2014-10-18 15:18:02 -070041using std::unique_ptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +000042using std::vector;
43
44namespace chromeos_update_engine {
45
Alex Deymo461b2592015-07-24 20:10:52 -070046namespace {
Darin Petkov6f03a3b2010-11-10 14:27:14 -080047
Alex Deymo109c28d2016-04-05 23:00:52 +000048bool SetupChild(const std::map<string, string>& env, uint32_t flags) {
Alex Deymo461b2592015-07-24 20:10:52 -070049 // Setup the environment variables.
50 clearenv();
Kelvin Zhang866d4702023-10-24 12:37:35 -070051 if (setpgid(0, 0) != 0) {
52 PLOG(ERROR) << "Failed to setpgid on subprocess " << getpid();
53 return false;
54 }
Alex Deymo461b2592015-07-24 20:10:52 -070055 for (const auto& key_value : env) {
56 setenv(key_value.first.c_str(), key_value.second.c_str(), 0);
57 }
Darin Petkov6f03a3b2010-11-10 14:27:14 -080058
Alex Deymo461b2592015-07-24 20:10:52 -070059 if ((flags & Subprocess::kRedirectStderrToStdout) != 0) {
60 if (HANDLE_EINTR(dup2(STDOUT_FILENO, STDERR_FILENO)) != STDERR_FILENO)
61 return false;
Alex Deymo29b81532015-07-09 11:51:49 -070062 }
Andrew de los Reyesc1d5c932011-04-20 17:15:47 -070063
Alex Deymo461b2592015-07-24 20:10:52 -070064 int fd = HANDLE_EINTR(open("/dev/null", O_RDONLY));
65 if (fd < 0)
66 return false;
67 if (HANDLE_EINTR(dup2(fd, STDIN_FILENO)) != STDIN_FILENO)
68 return false;
69 IGNORE_EINTR(close(fd));
70
71 return true;
adlr@google.com3defe6a2009-12-04 20:57:17 +000072}
73
Alex Deymo461b2592015-07-24 20:10:52 -070074// Helper function to launch a process with the given Subprocess::Flags.
75// This function only sets up and starts the process according to the |flags|.
76// The caller is responsible for watching the termination of the subprocess.
77// Return whether the process was successfully launched and fills in the |proc|
78// Process.
79bool LaunchProcess(const vector<string>& cmd,
80 uint32_t flags,
Alex Deymoe384bb22016-03-29 17:23:33 -070081 const vector<int>& output_pipes,
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -070082 brillo::Process* proc) {
Alex Deymo461b2592015-07-24 20:10:52 -070083 for (const string& arg : cmd)
84 proc->AddArg(arg);
85 proc->SetSearchPath((flags & Subprocess::kSearchPath) != 0);
86
87 // Create an environment for the child process with just the required PATHs.
88 std::map<string, string> env;
89 for (const char* key : {"LD_LIBRARY_PATH", "PATH"}) {
90 const char* value = getenv(key);
91 if (value)
92 env.emplace(key, value);
93 }
94
Alex Deymoe384bb22016-03-29 17:23:33 -070095 for (const int fd : output_pipes) {
96 proc->RedirectUsingPipe(fd, false);
97 }
98 proc->SetCloseUnusedFileDescriptors(true);
Alex Deymo461b2592015-07-24 20:10:52 -070099 proc->RedirectUsingPipe(STDOUT_FILENO, false);
Alex Deymo109c28d2016-04-05 23:00:52 +0000100 proc->SetPreExecCallback(base::Bind(&SetupChild, env, flags));
Alex Deymo461b2592015-07-24 20:10:52 -0700101
Amin Hassani3a4caa12019-11-06 11:12:28 -0800102 LOG(INFO) << "Running \"" << base::JoinString(cmd, " ") << "\"";
Alex Deymo461b2592015-07-24 20:10:52 -0700103 return proc->Start();
104}
105
106} // namespace
107
Alex Deymob7ca0962014-10-01 17:58:07 -0700108void Subprocess::Init(
Amin Hassanib2689592019-01-13 17:04:28 -0800109 brillo::AsynchronousSignalHandlerInterface* async_signal_handler) {
Alex Deymo461b2592015-07-24 20:10:52 -0700110 if (subprocess_singleton_ == this)
111 return;
112 CHECK(subprocess_singleton_ == nullptr);
113 subprocess_singleton_ = this;
114
Alex Deymob7ca0962014-10-01 17:58:07 -0700115 process_reaper_.Register(async_signal_handler);
Alex Deymo461b2592015-07-24 20:10:52 -0700116}
117
118Subprocess::~Subprocess() {
119 if (subprocess_singleton_ == this)
120 subprocess_singleton_ = nullptr;
Kenneth Watersa7fcafa2010-09-21 10:27:03 -0700121}
122
Alex Deymo29b81532015-07-09 11:51:49 -0700123void Subprocess::OnStdoutReady(SubprocessRecord* record) {
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800124 char buf[1024];
Alex Deymo0d298542016-03-30 18:31:49 -0700125 size_t bytes_read;
Alex Deymo29b81532015-07-09 11:51:49 -0700126 do {
Alex Deymo0d298542016-03-30 18:31:49 -0700127 bytes_read = 0;
128 bool eof;
129 bool ok = utils::ReadAll(
Kokoa Matsuda91aa2172024-10-16 16:01:04 +0900130 record->stdout_fd, buf, std::size(buf), &bytes_read, &eof);
Colin Crossd76a8ac2021-12-21 13:08:20 -0800131 record->stdout_str.append(buf, bytes_read);
Alex Deymo0d298542016-03-30 18:31:49 -0700132 if (!ok || eof) {
133 // There was either an error or an EOF condition, so we are done watching
134 // the file descriptor.
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900135 record->stdout_controller.reset();
Alex Deymo0d298542016-03-30 18:31:49 -0700136 return;
Alex Deymo29b81532015-07-09 11:51:49 -0700137 }
Alex Deymo0d298542016-03-30 18:31:49 -0700138 } while (bytes_read);
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800139}
140
Alex Deymo461b2592015-07-24 20:10:52 -0700141void Subprocess::ChildExitedCallback(const siginfo_t& info) {
142 auto pid_record = subprocess_records_.find(info.si_pid);
143 if (pid_record == subprocess_records_.end())
144 return;
145 SubprocessRecord* record = pid_record->second.get();
146
147 // Make sure we read any remaining process output and then close the pipe.
148 OnStdoutReady(record);
149
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900150 record->stdout_controller.reset();
Alex Deymo461b2592015-07-24 20:10:52 -0700151
Alex Deymo461b2592015-07-24 20:10:52 -0700152 // Don't print any log if the subprocess exited with exit code 0.
153 if (info.si_code != CLD_EXITED) {
Kelvin Zhang866d4702023-10-24 12:37:35 -0700154 LOG(INFO) << "Subprocess " << info.si_pid << " terminated with si_code "
155 << info.si_code;
Alex Deymo461b2592015-07-24 20:10:52 -0700156 } else if (info.si_status != 0) {
Kelvin Zhang866d4702023-10-24 12:37:35 -0700157 LOG(INFO) << "Subprocess " << info.si_pid
158 << " exited with si_status: " << info.si_status;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000159 }
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700160
Colin Crossd76a8ac2021-12-21 13:08:20 -0800161 if (!record->stdout_str.empty()) {
162 LOG(INFO) << "Subprocess output:\n" << record->stdout_str;
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700163 }
Alex Deymo461b2592015-07-24 20:10:52 -0700164 if (!record->callback.is_null()) {
Colin Crossd76a8ac2021-12-21 13:08:20 -0800165 record->callback.Run(info.si_status, record->stdout_str);
Andrew de los Reyes3270f742010-07-15 22:28:14 -0700166 }
Alex Deymoe384bb22016-03-29 17:23:33 -0700167 // Release and close all the pipes after calling the callback so our
168 // redirected pipes are still alive. Releasing the process first makes
169 // Reset(0) not attempt to kill the process, which is already a zombie at this
170 // point.
171 record->proc.Release();
172 record->proc.Reset(0);
173
Alex Deymo461b2592015-07-24 20:10:52 -0700174 subprocess_records_.erase(pid_record);
Alex Deymo29b81532015-07-09 11:51:49 -0700175}
176
Alex Deymo461b2592015-07-24 20:10:52 -0700177pid_t Subprocess::Exec(const vector<string>& cmd,
178 const ExecCallback& callback) {
Alex Deymo109c28d2016-04-05 23:00:52 +0000179 return ExecFlags(cmd, kRedirectStderrToStdout, {}, callback);
Alex Deymo461b2592015-07-24 20:10:52 -0700180}
Andrew de los Reyes08c4e272010-04-15 14:02:17 -0700181
Alex Deymo461b2592015-07-24 20:10:52 -0700182pid_t Subprocess::ExecFlags(const vector<string>& cmd,
183 uint32_t flags,
Alex Deymoe384bb22016-03-29 17:23:33 -0700184 const vector<int>& output_pipes,
Alex Deymo461b2592015-07-24 20:10:52 -0700185 const ExecCallback& callback) {
186 unique_ptr<SubprocessRecord> record(new SubprocessRecord(callback));
187
Alex Deymo109c28d2016-04-05 23:00:52 +0000188 if (!LaunchProcess(cmd, flags, output_pipes, &record->proc)) {
Alex Deymo461b2592015-07-24 20:10:52 -0700189 LOG(ERROR) << "Failed to launch subprocess";
Chris Masonec6c57a52010-09-23 13:06:14 -0700190 return 0;
191 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000192
Alex Deymo461b2592015-07-24 20:10:52 -0700193 pid_t pid = record->proc.pid();
Amin Hassanib2689592019-01-13 17:04:28 -0800194 CHECK(process_reaper_.WatchForChild(
195 FROM_HERE,
196 pid,
197 base::Bind(&Subprocess::ChildExitedCallback, base::Unretained(this))));
Darin Petkov6f03a3b2010-11-10 14:27:14 -0800198
Alex Deymo461b2592015-07-24 20:10:52 -0700199 record->stdout_fd = record->proc.GetPipe(STDOUT_FILENO);
Alex Deymo29b81532015-07-09 11:51:49 -0700200 // Capture the subprocess output. Make our end of the pipe non-blocking.
Alex Deymo461b2592015-07-24 20:10:52 -0700201 int fd_flags = fcntl(record->stdout_fd, F_GETFL, 0) | O_NONBLOCK;
Alex Deymo29b81532015-07-09 11:51:49 -0700202 if (HANDLE_EINTR(fcntl(record->stdout_fd, F_SETFL, fd_flags)) < 0) {
203 LOG(ERROR) << "Unable to set non-blocking I/O mode on fd "
204 << record->stdout_fd << ".";
205 }
206
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900207 record->stdout_controller = base::FileDescriptorWatcher::WatchReadable(
Alex Deymo29b81532015-07-09 11:51:49 -0700208 record->stdout_fd,
Hidehiko Abe493fecb2019-07-10 23:30:50 +0900209 base::BindRepeating(&Subprocess::OnStdoutReady, record.get()));
Alex Deymo29b81532015-07-09 11:51:49 -0700210
Alex Vakulenkoce8c8ee2016-04-08 08:59:26 -0700211 subprocess_records_[pid] = std::move(record);
Alex Deymo461b2592015-07-24 20:10:52 -0700212 return pid;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000213}
214
Kelvin Zhang866d4702023-10-24 12:37:35 -0700215bool WaitForProcessGroup(pid_t pid, std::chrono::milliseconds timeout) {
216 using std::chrono::system_clock;
217 auto start = system_clock::now();
218 do {
219 pid_t w = waitpid(-pid, nullptr, WNOHANG);
220 if (w < 0) {
221 // When all of the child process with this process group ID exits, waitpid
222 // will return ECHILD. Until that point, keep callilng waitpid() as there
223 // might be multiple child processes with the same process group id.
224 if (errno == ECHILD) {
225 LOG(INFO) << "All processes with process group id " << pid << " exited";
226 return true;
227 }
228 PLOG(ERROR) << "Waitpid returned " << w;
229 return false;
230 }
231 usleep(100);
232 } while ((system_clock::now() - start) <= timeout);
233 LOG(INFO) << "process group " << pid << " did not exit in " << timeout.count()
234 << " milliseconds";
235 return false;
236}
237
Alex Deymo461b2592015-07-24 20:10:52 -0700238void Subprocess::KillExec(pid_t pid) {
Kelvin Zhang866d4702023-10-24 12:37:35 -0700239 using namespace std::chrono_literals;
Alex Deymo461b2592015-07-24 20:10:52 -0700240 auto pid_record = subprocess_records_.find(pid);
241 if (pid_record == subprocess_records_.end())
Alex Deymo29b81532015-07-09 11:51:49 -0700242 return;
Alex Deymo461b2592015-07-24 20:10:52 -0700243 pid_record->second->callback.Reset();
Sen Jiang1d3b8632016-05-13 12:32:10 -0700244 // We don't care about output/return code, so we use SIGKILL here to ensure it
245 // will be killed, SIGTERM might lead to leaked subprocess.
Kelvin Zhang1e926312023-09-27 18:10:25 -0700246 CHECK_EQ(pid_record->second->proc.pid(), pid);
Kelvin Zhang866d4702023-10-24 12:37:35 -0700247 if (kill(-pid, SIGKILL) != 0) {
248 PLOG(WARNING) << "Failed to kill subprocess group " << pid;
Alex Deymod15c5462016-03-09 18:11:12 -0800249 }
Kelvin Zhang866d4702023-10-24 12:37:35 -0700250 WaitForProcessGroup(pid, 5000ms);
Alex Deymod15c5462016-03-09 18:11:12 -0800251 // Release the pid now so we don't try to kill it if Subprocess is destroyed
252 // before the corresponding ChildExitedCallback() is called.
253 pid_record->second->proc.Release();
Kelvin Zhang1e926312023-09-27 18:10:25 -0700254 if (subprocess_records_.count(pid)) {
255 siginfo_t info;
256 info.si_code = CLD_KILLED;
257 info.si_status = SIGKILL;
258 info.si_pid = pid;
259 ChildExitedCallback(info);
260 }
adlr@google.com3defe6a2009-12-04 20:57:17 +0000261}
262
Alex Deymoe384bb22016-03-29 17:23:33 -0700263int Subprocess::GetPipeFd(pid_t pid, int fd) const {
264 auto pid_record = subprocess_records_.find(pid);
265 if (pid_record == subprocess_records_.end())
266 return -1;
267 return pid_record->second->proc.GetPipe(fd);
268}
269
Alex Deymof329b932014-10-30 01:37:48 -0700270bool Subprocess::SynchronousExec(const vector<string>& cmd,
Darin Petkov85d02b72011-05-17 13:25:51 -0700271 int* return_code,
Colin Crossd76a8ac2021-12-21 13:08:20 -0800272 string* stdout_str,
273 string* stderr_str) {
Amin Hassani3a4caa12019-11-06 11:12:28 -0800274 // The default for |SynchronousExec| is to use |kSearchPath| since the code
275 // relies on that.
Colin Crossd76a8ac2021-12-21 13:08:20 -0800276 return SynchronousExecFlags(
277 cmd, kSearchPath, return_code, stdout_str, stderr_str);
Alex Deymo461b2592015-07-24 20:10:52 -0700278}
279
280bool Subprocess::SynchronousExecFlags(const vector<string>& cmd,
281 uint32_t flags,
282 int* return_code,
Colin Crossd76a8ac2021-12-21 13:08:20 -0800283 string* stdout_str,
284 string* stderr_str) {
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700285 brillo::ProcessImpl proc;
Amin Hassani3a4caa12019-11-06 11:12:28 -0800286 if (!LaunchProcess(cmd, flags, {STDERR_FILENO}, &proc)) {
Alex Deymo461b2592015-07-24 20:10:52 -0700287 LOG(ERROR) << "Failed to launch subprocess";
288 return false;
289 }
290
Colin Crossd76a8ac2021-12-21 13:08:20 -0800291 if (stdout_str) {
292 stdout_str->clear();
Alex Deymo461b2592015-07-24 20:10:52 -0700293 }
Colin Crossd76a8ac2021-12-21 13:08:20 -0800294 if (stderr_str) {
295 stderr_str->clear();
Amin Hassani3a4caa12019-11-06 11:12:28 -0800296 }
Alex Deymo461b2592015-07-24 20:10:52 -0700297
Amin Hassani3a4caa12019-11-06 11:12:28 -0800298 // Read from both stdout and stderr individually.
299 int stdout_fd = proc.GetPipe(STDOUT_FILENO);
300 int stderr_fd = proc.GetPipe(STDERR_FILENO);
Alex Deymo461b2592015-07-24 20:10:52 -0700301 vector<char> buffer(32 * 1024);
Amin Hassani3a4caa12019-11-06 11:12:28 -0800302 bool stdout_closed = false, stderr_closed = false;
303 while (!stdout_closed || !stderr_closed) {
304 if (!stdout_closed) {
305 int rc = HANDLE_EINTR(read(stdout_fd, buffer.data(), buffer.size()));
306 if (rc <= 0) {
307 stdout_closed = true;
308 if (rc < 0)
309 PLOG(ERROR) << "Reading from child's stdout";
Colin Crossd76a8ac2021-12-21 13:08:20 -0800310 } else if (stdout_str != nullptr) {
311 stdout_str->append(buffer.data(), rc);
Amin Hassani3a4caa12019-11-06 11:12:28 -0800312 }
313 }
314
315 if (!stderr_closed) {
316 int rc = HANDLE_EINTR(read(stderr_fd, buffer.data(), buffer.size()));
317 if (rc <= 0) {
318 stderr_closed = true;
319 if (rc < 0)
320 PLOG(ERROR) << "Reading from child's stderr";
Colin Crossd76a8ac2021-12-21 13:08:20 -0800321 } else if (stderr_str != nullptr) {
322 stderr_str->append(buffer.data(), rc);
Amin Hassani3a4caa12019-11-06 11:12:28 -0800323 }
Alex Deymo461b2592015-07-24 20:10:52 -0700324 }
325 }
Amin Hassani3a4caa12019-11-06 11:12:28 -0800326
Alex Deymo461b2592015-07-24 20:10:52 -0700327 // At this point, the subprocess already closed the output, so we only need to
328 // wait for it to finish.
329 int proc_return_code = proc.Wait();
330 if (return_code)
331 *return_code = proc_return_code;
Alex Vakulenko3f39d5c2015-10-13 09:27:13 -0700332 return proc_return_code != brillo::Process::kErrorExitStatus;
Darin Petkov85d02b72011-05-17 13:25:51 -0700333}
334
Amin Hassania8859542018-03-07 16:24:43 -0800335void Subprocess::FlushBufferedLogsAtExit() {
336 if (!subprocess_records_.empty()) {
337 LOG(INFO) << "We are exiting, but there are still in flight subprocesses!";
338 for (auto& pid_record : subprocess_records_) {
339 SubprocessRecord* record = pid_record.second.get();
340 // Make sure we read any remaining process output.
341 OnStdoutReady(record);
Colin Crossd76a8ac2021-12-21 13:08:20 -0800342 if (!record->stdout_str.empty()) {
Amin Hassania8859542018-03-07 16:24:43 -0800343 LOG(INFO) << "Subprocess(" << pid_record.first << ") output:\n"
Colin Crossd76a8ac2021-12-21 13:08:20 -0800344 << record->stdout_str;
Amin Hassania8859542018-03-07 16:24:43 -0800345 }
346 }
347 }
348}
349
Alex Vakulenko88b591f2014-08-28 16:48:57 -0700350Subprocess* Subprocess::subprocess_singleton_ = nullptr;
adlr@google.com3defe6a2009-12-04 20:57:17 +0000351
352} // namespace chromeos_update_engine