blob: c833d0e6bd3b72fbacd92a182dc754466d2b2442 [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
51 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
52 printf("*** sigprocmask failed: %s\n", strerror(errno));
53 return false;
54 }
55
56 timespec ts;
Vishnu Nair6921f802017-11-22 09:17:23 -080057 ts.tv_sec = MSEC_TO_SEC(timeout_ms);
58 ts.tv_nsec = (timeout_ms % 1000) * 1000000;
Nandana Dutt263cf382018-09-26 11:22:02 +010059 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, nullptr, &ts));
Felipe Lemef0292972016-11-22 13:57:05 -080060 int saved_errno = errno;
Vishnu Nair6921f802017-11-22 09:17:23 -080061
Felipe Lemef0292972016-11-22 13:57:05 -080062 // Set the signals back the way they were.
Nandana Dutt263cf382018-09-26 11:22:02 +010063 if (sigprocmask(SIG_SETMASK, &old_mask, nullptr) == -1) {
Felipe Lemef0292972016-11-22 13:57:05 -080064 printf("*** sigprocmask failed: %s\n", strerror(errno));
65 if (ret == 0) {
66 return false;
67 }
68 }
69 if (ret == -1) {
70 errno = saved_errno;
71 if (errno == EAGAIN) {
72 errno = ETIMEDOUT;
73 } else {
74 printf("*** sigtimedwait failed: %s\n", strerror(errno));
75 }
76 return false;
77 }
78
79 pid_t child_pid = waitpid(pid, status, WNOHANG);
80 if (child_pid != pid) {
81 if (child_pid != -1) {
82 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
83 } else {
84 printf("*** waitpid failed: %s\n", strerror(errno));
85 }
86 return false;
87 }
88 return true;
89}
Felipe Leme47e9be22016-12-21 15:37:07 -080090} // unnamed namespace
Felipe Lemef0292972016-11-22 13:57:05 -080091
92CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
93CommandOptions CommandOptions::AS_ROOT = CommandOptions::WithTimeout(10).AsRoot().Build();
Felipe Lemef0292972016-11-22 13:57:05 -080094
Vishnu Nair6921f802017-11-22 09:17:23 -080095CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(int64_t timeout_ms) : values(timeout_ms) {
Felipe Lemef0292972016-11-22 13:57:05 -080096}
97
98CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
99 values.always_ = true;
100 return *this;
101}
102
103CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Nandana Dutt4b392be2018-11-02 16:17:05 +0000104 if (!PropertiesHelper::IsUnroot()) {
105 values.account_mode_ = SU_ROOT;
106 }
Felipe Lemef0292972016-11-22 13:57:05 -0800107 return *this;
108}
109
Yifan Hong48e83a12017-10-03 14:10:07 -0700110CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRootIfAvailable() {
Nandana Dutt4b392be2018-11-02 16:17:05 +0000111 if (!PropertiesHelper::IsUserBuild()) {
112 return AsRoot();
113 }
Yifan Hong48e83a12017-10-03 14:10:07 -0700114 return *this;
115}
116
Felipe Lemef0292972016-11-22 13:57:05 -0800117CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
118 values.account_mode_ = DROP_ROOT;
119 return *this;
120}
121
122CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
123 values.output_mode_ = REDIRECT_TO_STDERR;
124 return *this;
125}
126
Primiano Tuccifaaaafb2021-01-14 12:26:29 +0000127CommandOptions::CommandOptionsBuilder&
128CommandOptions::CommandOptionsBuilder::CloseAllFileDescriptorsOnExec() {
129 values.close_all_fds_on_exec_ = true;
130 return *this;
131}
132
Felipe Lemef0292972016-11-22 13:57:05 -0800133CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
134 const std::string& message) {
135 values.logging_message_ = message;
136 return *this;
137}
138
139CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
140 return CommandOptions(values);
141}
142
Vishnu Nair6921f802017-11-22 09:17:23 -0800143CommandOptions::CommandOptionsValues::CommandOptionsValues(int64_t timeout_ms)
144 : timeout_ms_(timeout_ms),
Felipe Lemef0292972016-11-22 13:57:05 -0800145 always_(false),
Primiano Tuccifaaaafb2021-01-14 12:26:29 +0000146 close_all_fds_on_exec_(false),
Felipe Lemef0292972016-11-22 13:57:05 -0800147 account_mode_(DONT_DROP_ROOT),
148 output_mode_(NORMAL_OUTPUT),
149 logging_message_("") {
150}
151
152CommandOptions::CommandOptions(const CommandOptionsValues& values) : values(values) {
153}
154
155int64_t CommandOptions::Timeout() const {
Vishnu Nair6921f802017-11-22 09:17:23 -0800156 return MSEC_TO_SEC(values.timeout_ms_);
157}
158
159int64_t CommandOptions::TimeoutInMs() const {
160 return values.timeout_ms_;
Felipe Lemef0292972016-11-22 13:57:05 -0800161}
162
163bool CommandOptions::Always() const {
164 return values.always_;
165}
166
Primiano Tuccifaaaafb2021-01-14 12:26:29 +0000167bool CommandOptions::ShouldCloseAllFileDescriptorsOnExec() const {
168 return values.close_all_fds_on_exec_;
169}
170
Felipe Lemef0292972016-11-22 13:57:05 -0800171PrivilegeMode CommandOptions::PrivilegeMode() const {
172 return values.account_mode_;
173}
174
175OutputMode CommandOptions::OutputMode() const {
176 return values.output_mode_;
177}
178
179std::string CommandOptions::LoggingMessage() const {
180 return values.logging_message_;
181}
182
Vishnu Nair6921f802017-11-22 09:17:23 -0800183CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(int64_t timeout_sec) {
184 return CommandOptions::CommandOptionsBuilder(SEC_TO_MSEC(timeout_sec));
185}
186
187CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeoutInMs(int64_t timeout_ms) {
188 return CommandOptions::CommandOptionsBuilder(timeout_ms);
Felipe Lemef0292972016-11-22 13:57:05 -0800189}
190
191std::string PropertiesHelper::build_type_ = "";
192int PropertiesHelper::dry_run_ = -1;
Nandana Dutt4b392be2018-11-02 16:17:05 +0000193int PropertiesHelper::unroot_ = -1;
Rhed Jao1c855122020-07-16 17:37:39 +0800194int PropertiesHelper::parallel_run_ = -1;
Felipe Lemef0292972016-11-22 13:57:05 -0800195
196bool PropertiesHelper::IsUserBuild() {
197 if (build_type_.empty()) {
198 build_type_ = android::base::GetProperty("ro.build.type", "user");
199 }
200 return "user" == build_type_;
201}
202
203bool PropertiesHelper::IsDryRun() {
204 if (dry_run_ == -1) {
205 dry_run_ = android::base::GetBoolProperty("dumpstate.dry_run", false) ? 1 : 0;
206 }
207 return dry_run_ == 1;
208}
209
Nandana Dutt4b392be2018-11-02 16:17:05 +0000210bool PropertiesHelper::IsUnroot() {
211 if (unroot_ == -1) {
212 unroot_ = android::base::GetBoolProperty("dumpstate.unroot", false) ? 1 : 0;
213 }
214 return unroot_ == 1;
215}
216
Rhed Jao1c855122020-07-16 17:37:39 +0800217bool PropertiesHelper::IsParallelRun() {
218 if (parallel_run_ == -1) {
219 parallel_run_ = android::base::GetBoolProperty("dumpstate.parallel_run",
220 /* default_value = */true) ? 1 : 0;
221 }
222 return parallel_run_ == 1;
223}
224
Felipe Lemef0292972016-11-22 13:57:05 -0800225int DumpFileToFd(int out_fd, const std::string& title, const std::string& path) {
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100226 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
227 if (fd.get() < 0) {
Felipe Lemef0292972016-11-22 13:57:05 -0800228 int err = errno;
229 if (title.empty()) {
230 dprintf(out_fd, "*** Error dumping %s: %s\n", path.c_str(), strerror(err));
231 } else {
232 dprintf(out_fd, "*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(),
233 strerror(err));
234 }
235 fsync(out_fd);
236 return -1;
237 }
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100238 return DumpFileFromFdToFd(title, path, fd.get(), out_fd, PropertiesHelper::IsDryRun());
Felipe Lemef0292972016-11-22 13:57:05 -0800239}
240
241int RunCommandToFd(int fd, const std::string& title, const std::vector<std::string>& full_command,
242 const CommandOptions& options) {
243 if (full_command.empty()) {
244 MYLOGE("No arguments on RunCommandToFd(%s)\n", title.c_str());
245 return -1;
246 }
247
248 int size = full_command.size() + 1; // null terminated
249 int starting_index = 0;
250 if (options.PrivilegeMode() == SU_ROOT) {
251 starting_index = 2; // "su" "root"
252 size += starting_index;
253 }
254
255 std::vector<const char*> args;
256 args.resize(size);
257
258 std::string command_string;
259 if (options.PrivilegeMode() == SU_ROOT) {
260 args[0] = kSuPath;
261 command_string += kSuPath;
262 args[1] = "root";
263 command_string += " root ";
264 }
265 for (size_t i = 0; i < full_command.size(); i++) {
266 args[i + starting_index] = full_command[i].data();
267 command_string += args[i + starting_index];
268 if (i != full_command.size() - 1) {
269 command_string += " ";
270 }
271 }
272 args[size - 1] = nullptr;
273
274 const char* command = command_string.c_str();
275
276 if (options.PrivilegeMode() == SU_ROOT && PropertiesHelper::IsUserBuild()) {
277 dprintf(fd, "Skipping '%s' on user build.\n", command);
278 return 0;
279 }
280
281 if (!title.empty()) {
282 dprintf(fd, "------ %s (%s) ------\n", title.c_str(), command);
283 fsync(fd);
284 }
285
286 const std::string& logging_message = options.LoggingMessage();
287 if (!logging_message.empty()) {
288 MYLOGI(logging_message.c_str(), command_string.c_str());
289 }
290
Primiano Tuccifaaaafb2021-01-14 12:26:29 +0000291 bool silent = (options.OutputMode() == REDIRECT_TO_STDERR ||
292 options.ShouldCloseAllFileDescriptorsOnExec());
Felipe Lemef0292972016-11-22 13:57:05 -0800293 bool redirecting_to_fd = STDOUT_FILENO != fd;
294
295 if (PropertiesHelper::IsDryRun() && !options.Always()) {
296 if (!title.empty()) {
297 dprintf(fd, "\t(skipped on dry run)\n");
298 } else if (redirecting_to_fd) {
299 // There is no title, but we should still print a dry-run message
300 dprintf(fd, "%s: skipped on dry run\n", command_string.c_str());
301 }
302 fsync(fd);
303 return 0;
304 }
305
306 const char* path = args[0];
307
308 uint64_t start = Nanotime();
309 pid_t pid = fork();
310
311 /* handle error case */
312 if (pid < 0) {
313 if (!silent) dprintf(fd, "*** fork: %s\n", strerror(errno));
314 MYLOGE("*** fork: %s\n", strerror(errno));
315 return pid;
316 }
317
318 /* handle child case */
319 if (pid == 0) {
320 if (options.PrivilegeMode() == DROP_ROOT && !DropRootUser()) {
321 if (!silent) {
322 dprintf(fd, "*** failed to drop root before running %s: %s\n", command,
323 strerror(errno));
324 }
325 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
326 return -1;
327 }
328
Primiano Tuccifaaaafb2021-01-14 12:26:29 +0000329 if (options.ShouldCloseAllFileDescriptorsOnExec()) {
330 int devnull_fd = TEMP_FAILURE_RETRY(open("/dev/null", O_RDONLY));
331 TEMP_FAILURE_RETRY(dup2(devnull_fd, STDIN_FILENO));
332 close(devnull_fd);
333 devnull_fd = TEMP_FAILURE_RETRY(open("/dev/null", O_WRONLY));
334 TEMP_FAILURE_RETRY(dup2(devnull_fd, STDOUT_FILENO));
335 TEMP_FAILURE_RETRY(dup2(devnull_fd, STDERR_FILENO));
336 close(devnull_fd);
337 // This is to avoid leaking FDs that, accidentally, have not been
338 // marked as O_CLOEXEC. Leaking FDs across exec can cause failures
339 // when execing a process that has a SELinux auto_trans rule.
340 // Here we assume that the dumpstate process didn't open more than
341 // 1000 FDs. In theory we could iterate through /proc/self/fd/, but
342 // doing that in a fork-safe way is too complex and not worth it
343 // (opendir()/readdir() do heap allocations and take locks).
344 for (int i = 0; i < 1000; i++) {
345 if (i != STDIN_FILENO && i!= STDOUT_FILENO && i != STDERR_FILENO) {
346 close(i);
347 }
348 }
349 } else if (silent) {
Felipe Lemef0292972016-11-22 13:57:05 -0800350 // Redirects stdout to stderr
351 TEMP_FAILURE_RETRY(dup2(STDERR_FILENO, STDOUT_FILENO));
352 } else if (redirecting_to_fd) {
353 // Redirect stdout to fd
354 TEMP_FAILURE_RETRY(dup2(fd, STDOUT_FILENO));
355 close(fd);
356 }
357
358 /* make sure the child dies when dumpstate dies */
359 prctl(PR_SET_PDEATHSIG, SIGKILL);
360
361 /* just ignore SIGPIPE, will go down with parent's */
362 struct sigaction sigact;
363 memset(&sigact, 0, sizeof(sigact));
364 sigact.sa_handler = SIG_IGN;
Nandana Dutt263cf382018-09-26 11:22:02 +0100365 sigaction(SIGPIPE, &sigact, nullptr);
Felipe Lemef0292972016-11-22 13:57:05 -0800366
367 execvp(path, (char**)args.data());
368 // execvp's result will be handled after waitpid_with_timeout() below, but
369 // if it failed, it's safer to exit dumpstate.
370 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
371 // Must call _exit (instead of exit), otherwise it will corrupt the zip
372 // file.
373 _exit(EXIT_FAILURE);
374 }
375
376 /* handle parent case */
377 int status;
Vishnu Nair6921f802017-11-22 09:17:23 -0800378 bool ret = waitpid_with_timeout(pid, options.TimeoutInMs(), &status);
Felipe Lemef0292972016-11-22 13:57:05 -0800379 fsync(fd);
380
381 uint64_t elapsed = Nanotime() - start;
382 if (!ret) {
383 if (errno == ETIMEDOUT) {
384 if (!silent)
385 dprintf(fd, "*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
386 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
387 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
388 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
389 } else {
390 if (!silent)
391 dprintf(fd, "*** command '%s': Error after %.4fs (killing pid %d)\n", command,
392 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
393 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
394 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
395 }
396 kill(pid, SIGTERM);
Vishnu Nair6921f802017-11-22 09:17:23 -0800397 if (!waitpid_with_timeout(pid, 5000, nullptr)) {
Felipe Lemef0292972016-11-22 13:57:05 -0800398 kill(pid, SIGKILL);
Vishnu Nair6921f802017-11-22 09:17:23 -0800399 if (!waitpid_with_timeout(pid, 5000, nullptr)) {
Felipe Lemef0292972016-11-22 13:57:05 -0800400 if (!silent)
401 dprintf(fd, "could not kill command '%s' (pid %d) even with SIGKILL.\n",
402 command, pid);
403 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
404 }
405 }
406 return -1;
407 }
408
409 if (WIFSIGNALED(status)) {
410 if (!silent)
411 dprintf(fd, "*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
412 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
413 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
414 status = WEXITSTATUS(status);
415 if (!silent) dprintf(fd, "*** command '%s' failed: exit code %d\n", command, status);
416 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
417 }
418
419 return status;
420}
Ecco Park61ffcf72016-10-27 15:46:26 -0700421
Felipe Leme47e9be22016-12-21 15:37:07 -0800422} // namespace dumpstate
423} // namespace os
424} // namespace android