blob: 81baf855f0edcc7d8509344ec0ce2ee7a6f3b89e [file] [log] [blame]
Felipe Lemef0292972016-11-22 13:57:05 -08001/*
2 * Copyright (C) 2016 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 */
16
17#define LOG_TAG "dumpstate"
18
19#include "DumpstateUtil.h"
20
Ecco Park61ffcf72016-10-27 15:46:26 -070021#include <dirent.h>
Felipe Lemef0292972016-11-22 13:57:05 -080022#include <fcntl.h>
23#include <sys/prctl.h>
24#include <sys/wait.h>
25#include <unistd.h>
26
27#include <vector>
28
Ecco Park61ffcf72016-10-27 15:46:26 -070029#include <android-base/file.h>
Felipe Lemef0292972016-11-22 13:57:05 -080030#include <android-base/properties.h>
Ecco Park61ffcf72016-10-27 15:46:26 -070031#include <android-base/stringprintf.h>
32#include <android-base/strings.h>
Narayan Kamath6b9516c2017-10-27 11:15:51 +010033#include <android-base/unique_fd.h>
Jiyong Parkb22e65d2017-06-23 21:23:16 +090034#include <log/log.h>
Felipe Lemef0292972016-11-22 13:57:05 -080035
36#include "DumpstateInternal.h"
37
Felipe Leme47e9be22016-12-21 15:37:07 -080038namespace android {
39namespace os {
40namespace dumpstate {
41
42namespace {
43
Felipe Lemef0292972016-11-22 13:57:05 -080044static constexpr const char* kSuPath = "/system/xbin/su";
45
Vishnu Nair6921f802017-11-22 09:17:23 -080046static bool waitpid_with_timeout(pid_t pid, int timeout_ms, int* status) {
Felipe Lemef0292972016-11-22 13:57:05 -080047 sigset_t child_mask, old_mask;
48 sigemptyset(&child_mask);
49 sigaddset(&child_mask, SIGCHLD);
50
Tim Murray00ff3522022-02-17 10:01:19 -080051 // block SIGCHLD before we check if a process has exited
Felipe Lemef0292972016-11-22 13:57:05 -080052 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
53 printf("*** sigprocmask failed: %s\n", strerror(errno));
54 return false;
55 }
56
Tim Murray00ff3522022-02-17 10:01:19 -080057 // if the child has exited already, handle and reset signals before leaving
58 pid_t child_pid = waitpid(pid, status, WNOHANG);
59 if (child_pid != pid) {
60 if (child_pid > 0) {
61 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
62 sigprocmask(SIG_SETMASK, &old_mask, nullptr);
63 return false;
64 }
65 } else {
66 sigprocmask(SIG_SETMASK, &old_mask, nullptr);
67 return true;
68 }
69
70 // wait for a SIGCHLD
Felipe Lemef0292972016-11-22 13:57:05 -080071 timespec ts;
Vishnu Nair6921f802017-11-22 09:17:23 -080072 ts.tv_sec = MSEC_TO_SEC(timeout_ms);
73 ts.tv_nsec = (timeout_ms % 1000) * 1000000;
Nandana Dutt263cf382018-09-26 11:22:02 +010074 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
Felipe Lemef0292972016-11-22 13:57:05 -080075 int saved_errno = errno;
Vishnu Nair6921f802017-11-22 09:17:23 -080076
Felipe Lemef0292972016-11-22 13:57:05 -080077 // Set the signals back the way they were.
Nandana Dutt263cf382018-09-26 11:22:02 +010078 if (sigprocmask(SIG_SETMASK, &old_mask, nullptr) == -1) {
Felipe Lemef0292972016-11-22 13:57:05 -080079 printf("*** sigprocmask failed: %s\n", strerror(errno));
80 if (ret == 0) {
81 return false;
82 }
83 }
84 if (ret == -1) {
85 errno = saved_errno;
86 if (errno == EAGAIN) {
87 errno = ETIMEDOUT;
88 } else {
89 printf("*** sigtimedwait failed: %s\n", strerror(errno));
90 }
91 return false;
92 }
93
Tim Murray00ff3522022-02-17 10:01:19 -080094 child_pid = waitpid(pid, status, WNOHANG);
Felipe Lemef0292972016-11-22 13:57:05 -080095 if (child_pid != pid) {
96 if (child_pid != -1) {
97 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
98 } else {
99 printf("*** waitpid failed: %s\n", strerror(errno));
100 }
101 return false;
102 }
103 return true;
104}
Felipe Leme47e9be22016-12-21 15:37:07 -0800105} // unnamed namespace
Felipe Lemef0292972016-11-22 13:57:05 -0800106
107CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
108CommandOptions CommandOptions::AS_ROOT = CommandOptions::WithTimeout(10).AsRoot().Build();
Felipe Lemef0292972016-11-22 13:57:05 -0800109
Vishnu Nair6921f802017-11-22 09:17:23 -0800110CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(int64_t timeout_ms) : values(timeout_ms) {
Felipe Lemef0292972016-11-22 13:57:05 -0800111}
112
113CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
114 values.always_ = true;
115 return *this;
116}
117
118CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Nandana Dutt4b392be2018-11-02 16:17:05 +0000119 if (!PropertiesHelper::IsUnroot()) {
120 values.account_mode_ = SU_ROOT;
121 }
Felipe Lemef0292972016-11-22 13:57:05 -0800122 return *this;
123}
124
Yifan Hong48e83a12017-10-03 14:10:07 -0700125CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRootIfAvailable() {
Nandana Dutt4b392be2018-11-02 16:17:05 +0000126 if (!PropertiesHelper::IsUserBuild()) {
127 return AsRoot();
128 }
Yifan Hong48e83a12017-10-03 14:10:07 -0700129 return *this;
130}
131
Felipe Lemef0292972016-11-22 13:57:05 -0800132CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
133 values.account_mode_ = DROP_ROOT;
134 return *this;
135}
136
137CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
138 values.output_mode_ = REDIRECT_TO_STDERR;
139 return *this;
140}
141
Primiano Tuccifaaaafb2021-01-14 12:26:29 +0000142CommandOptions::CommandOptionsBuilder&
143CommandOptions::CommandOptionsBuilder::CloseAllFileDescriptorsOnExec() {
144 values.close_all_fds_on_exec_ = true;
145 return *this;
146}
147
Felipe Lemef0292972016-11-22 13:57:05 -0800148CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
149 const std::string& message) {
150 values.logging_message_ = message;
151 return *this;
152}
153
154CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
155 return CommandOptions(values);
156}
157
Vishnu Nair6921f802017-11-22 09:17:23 -0800158CommandOptions::CommandOptionsValues::CommandOptionsValues(int64_t timeout_ms)
159 : timeout_ms_(timeout_ms),
Felipe Lemef0292972016-11-22 13:57:05 -0800160 always_(false),
Primiano Tuccifaaaafb2021-01-14 12:26:29 +0000161 close_all_fds_on_exec_(false),
Felipe Lemef0292972016-11-22 13:57:05 -0800162 account_mode_(DONT_DROP_ROOT),
163 output_mode_(NORMAL_OUTPUT),
164 logging_message_("") {
165}
166
167CommandOptions::CommandOptions(const CommandOptionsValues& values) : values(values) {
168}
169
170int64_t CommandOptions::Timeout() const {
Vishnu Nair6921f802017-11-22 09:17:23 -0800171 return MSEC_TO_SEC(values.timeout_ms_);
172}
173
174int64_t CommandOptions::TimeoutInMs() const {
175 return values.timeout_ms_;
Felipe Lemef0292972016-11-22 13:57:05 -0800176}
177
178bool CommandOptions::Always() const {
179 return values.always_;
180}
181
Primiano Tuccifaaaafb2021-01-14 12:26:29 +0000182bool CommandOptions::ShouldCloseAllFileDescriptorsOnExec() const {
183 return values.close_all_fds_on_exec_;
184}
185
Felipe Lemef0292972016-11-22 13:57:05 -0800186PrivilegeMode CommandOptions::PrivilegeMode() const {
187 return values.account_mode_;
188}
189
190OutputMode CommandOptions::OutputMode() const {
191 return values.output_mode_;
192}
193
194std::string CommandOptions::LoggingMessage() const {
195 return values.logging_message_;
196}
197
Vishnu Nair6921f802017-11-22 09:17:23 -0800198CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(int64_t timeout_sec) {
199 return CommandOptions::CommandOptionsBuilder(SEC_TO_MSEC(timeout_sec));
200}
201
202CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeoutInMs(int64_t timeout_ms) {
203 return CommandOptions::CommandOptionsBuilder(timeout_ms);
Felipe Lemef0292972016-11-22 13:57:05 -0800204}
205
206std::string PropertiesHelper::build_type_ = "";
207int PropertiesHelper::dry_run_ = -1;
Nandana Dutt4b392be2018-11-02 16:17:05 +0000208int PropertiesHelper::unroot_ = -1;
Rhed Jao1c855122020-07-16 17:37:39 +0800209int PropertiesHelper::parallel_run_ = -1;
Felipe Lemef0292972016-11-22 13:57:05 -0800210
211bool PropertiesHelper::IsUserBuild() {
212 if (build_type_.empty()) {
213 build_type_ = android::base::GetProperty("ro.build.type", "user");
214 }
215 return "user" == build_type_;
216}
217
218bool PropertiesHelper::IsDryRun() {
219 if (dry_run_ == -1) {
220 dry_run_ = android::base::GetBoolProperty("dumpstate.dry_run", false) ? 1 : 0;
221 }
222 return dry_run_ == 1;
223}
224
Nandana Dutt4b392be2018-11-02 16:17:05 +0000225bool PropertiesHelper::IsUnroot() {
226 if (unroot_ == -1) {
227 unroot_ = android::base::GetBoolProperty("dumpstate.unroot", false) ? 1 : 0;
228 }
229 return unroot_ == 1;
230}
231
Rhed Jao1c855122020-07-16 17:37:39 +0800232bool PropertiesHelper::IsParallelRun() {
233 if (parallel_run_ == -1) {
234 parallel_run_ = android::base::GetBoolProperty("dumpstate.parallel_run",
235 /* default_value = */true) ? 1 : 0;
236 }
237 return parallel_run_ == 1;
238}
239
Felipe Lemef0292972016-11-22 13:57:05 -0800240int DumpFileToFd(int out_fd, const std::string& title, const std::string& path) {
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100241 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
242 if (fd.get() < 0) {
Felipe Lemef0292972016-11-22 13:57:05 -0800243 int err = errno;
244 if (title.empty()) {
245 dprintf(out_fd, "*** Error dumping %s: %s\n", path.c_str(), strerror(err));
246 } else {
247 dprintf(out_fd, "*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(),
248 strerror(err));
249 }
250 fsync(out_fd);
251 return -1;
252 }
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100253 return DumpFileFromFdToFd(title, path, fd.get(), out_fd, PropertiesHelper::IsDryRun());
Felipe Lemef0292972016-11-22 13:57:05 -0800254}
255
256int RunCommandToFd(int fd, const std::string& title, const std::vector<std::string>& full_command,
257 const CommandOptions& options) {
258 if (full_command.empty()) {
259 MYLOGE("No arguments on RunCommandToFd(%s)\n", title.c_str());
260 return -1;
261 }
262
263 int size = full_command.size() + 1; // null terminated
264 int starting_index = 0;
265 if (options.PrivilegeMode() == SU_ROOT) {
266 starting_index = 2; // "su" "root"
267 size += starting_index;
268 }
269
270 std::vector<const char*> args;
271 args.resize(size);
272
273 std::string command_string;
274 if (options.PrivilegeMode() == SU_ROOT) {
275 args[0] = kSuPath;
276 command_string += kSuPath;
277 args[1] = "root";
278 command_string += " root ";
279 }
280 for (size_t i = 0; i < full_command.size(); i++) {
281 args[i + starting_index] = full_command[i].data();
282 command_string += args[i + starting_index];
283 if (i != full_command.size() - 1) {
284 command_string += " ";
285 }
286 }
287 args[size - 1] = nullptr;
288
289 const char* command = command_string.c_str();
290
291 if (options.PrivilegeMode() == SU_ROOT && PropertiesHelper::IsUserBuild()) {
292 dprintf(fd, "Skipping '%s' on user build.\n", command);
293 return 0;
294 }
295
296 if (!title.empty()) {
297 dprintf(fd, "------ %s (%s) ------\n", title.c_str(), command);
298 fsync(fd);
299 }
300
301 const std::string& logging_message = options.LoggingMessage();
302 if (!logging_message.empty()) {
303 MYLOGI(logging_message.c_str(), command_string.c_str());
304 }
305
Primiano Tuccifaaaafb2021-01-14 12:26:29 +0000306 bool silent = (options.OutputMode() == REDIRECT_TO_STDERR ||
307 options.ShouldCloseAllFileDescriptorsOnExec());
Felipe Lemef0292972016-11-22 13:57:05 -0800308 bool redirecting_to_fd = STDOUT_FILENO != fd;
309
310 if (PropertiesHelper::IsDryRun() && !options.Always()) {
311 if (!title.empty()) {
312 dprintf(fd, "\t(skipped on dry run)\n");
313 } else if (redirecting_to_fd) {
314 // There is no title, but we should still print a dry-run message
315 dprintf(fd, "%s: skipped on dry run\n", command_string.c_str());
316 }
317 fsync(fd);
318 return 0;
319 }
320
321 const char* path = args[0];
322
323 uint64_t start = Nanotime();
324 pid_t pid = fork();
325
326 /* handle error case */
327 if (pid < 0) {
328 if (!silent) dprintf(fd, "*** fork: %s\n", strerror(errno));
329 MYLOGE("*** fork: %s\n", strerror(errno));
330 return pid;
331 }
332
333 /* handle child case */
334 if (pid == 0) {
335 if (options.PrivilegeMode() == DROP_ROOT && !DropRootUser()) {
336 if (!silent) {
337 dprintf(fd, "*** failed to drop root before running %s: %s\n", command,
338 strerror(errno));
339 }
340 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
341 return -1;
342 }
343
Primiano Tuccifaaaafb2021-01-14 12:26:29 +0000344 if (options.ShouldCloseAllFileDescriptorsOnExec()) {
345 int devnull_fd = TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
346 TEMP_FAILURE_RETRY(dup2(devnull_fd, STDIN_FILENO));
347 close(devnull_fd);
348 devnull_fd = TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY));
349 TEMP_FAILURE_RETRY(dup2(devnull_fd, STDOUT_FILENO));
350 TEMP_FAILURE_RETRY(dup2(devnull_fd, STDERR_FILENO));
351 close(devnull_fd);
352 // This is to avoid leaking FDs that, accidentally, have not been
353 // marked as O_CLOEXEC. Leaking FDs across exec can cause failures
354 // when execing a process that has a SELinux auto_trans rule.
355 // Here we assume that the dumpstate process didn't open more than
356 // 1000 FDs. In theory we could iterate through /proc/self/fd/, but
357 // doing that in a fork-safe way is too complex and not worth it
358 // (opendir()/readdir() do heap allocations and take locks).
359 for (int i = 0; i < 1000; i++) {
360 if (i != STDIN_FILENO && i!= STDOUT_FILENO && i != STDERR_FILENO) {
361 close(i);
362 }
363 }
364 } else if (silent) {
Felipe Lemef0292972016-11-22 13:57:05 -0800365 // Redirects stdout to stderr
366 TEMP_FAILURE_RETRY(dup2(STDERR_FILENO, STDOUT_FILENO));
367 } else if (redirecting_to_fd) {
368 // Redirect stdout to fd
369 TEMP_FAILURE_RETRY(dup2(fd, STDOUT_FILENO));
370 close(fd);
371 }
372
373 /* make sure the child dies when dumpstate dies */
374 prctl(PR_SET_PDEATHSIG, SIGKILL);
375
376 /* just ignore SIGPIPE, will go down with parent's */
377 struct sigaction sigact;
378 memset(&sigact, 0, sizeof(sigact));
379 sigact.sa_handler = SIG_IGN;
Nandana Dutt263cf382018-09-26 11:22:02 +0100380 sigaction(SIGPIPE, &sigact, nullptr);
Felipe Lemef0292972016-11-22 13:57:05 -0800381
382 execvp(path, (char**)args.data());
383 // execvp's result will be handled after waitpid_with_timeout() below, but
384 // if it failed, it's safer to exit dumpstate.
385 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
386 // Must call _exit (instead of exit), otherwise it will corrupt the zip
387 // file.
388 _exit(EXIT_FAILURE);
389 }
390
391 /* handle parent case */
392 int status;
Vishnu Nair6921f802017-11-22 09:17:23 -0800393 bool ret = waitpid_with_timeout(pid, options.TimeoutInMs(), &status);
Felipe Lemef0292972016-11-22 13:57:05 -0800394 fsync(fd);
395
396 uint64_t elapsed = Nanotime() - start;
397 if (!ret) {
398 if (errno == ETIMEDOUT) {
399 if (!silent)
400 dprintf(fd, "*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
401 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
402 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
403 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
404 } else {
405 if (!silent)
406 dprintf(fd, "*** command '%s': Error after %.4fs (killing pid %d)\n", command,
407 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
408 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
409 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
410 }
411 kill(pid, SIGTERM);
Vishnu Nair6921f802017-11-22 09:17:23 -0800412 if (!waitpid_with_timeout(pid, 5000, nullptr)) {
Felipe Lemef0292972016-11-22 13:57:05 -0800413 kill(pid, SIGKILL);
Vishnu Nair6921f802017-11-22 09:17:23 -0800414 if (!waitpid_with_timeout(pid, 5000, nullptr)) {
Felipe Lemef0292972016-11-22 13:57:05 -0800415 if (!silent)
416 dprintf(fd, "could not kill command '%s' (pid %d) even with SIGKILL.\n",
417 command, pid);
418 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
419 }
420 }
421 return -1;
422 }
423
424 if (WIFSIGNALED(status)) {
425 if (!silent)
426 dprintf(fd, "*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
427 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
428 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
429 status = WEXITSTATUS(status);
430 if (!silent) dprintf(fd, "*** command '%s' failed: exit code %d\n", command, status);
431 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
432 }
433
434 return status;
435}
Ecco Park61ffcf72016-10-27 15:46:26 -0700436
Felipe Leme47e9be22016-12-21 15:37:07 -0800437} // namespace dumpstate
438} // namespace os
439} // namespace android