blob: eeaa5a3de0eb1d5226b5edf9fe3bb5cf318d4a50 [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
127CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
128 const std::string& message) {
129 values.logging_message_ = message;
130 return *this;
131}
132
133CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
134 return CommandOptions(values);
135}
136
Vishnu Nair6921f802017-11-22 09:17:23 -0800137CommandOptions::CommandOptionsValues::CommandOptionsValues(int64_t timeout_ms)
138 : timeout_ms_(timeout_ms),
Felipe Lemef0292972016-11-22 13:57:05 -0800139 always_(false),
140 account_mode_(DONT_DROP_ROOT),
141 output_mode_(NORMAL_OUTPUT),
142 logging_message_("") {
143}
144
145CommandOptions::CommandOptions(const CommandOptionsValues& values) : values(values) {
146}
147
148int64_t CommandOptions::Timeout() const {
Vishnu Nair6921f802017-11-22 09:17:23 -0800149 return MSEC_TO_SEC(values.timeout_ms_);
150}
151
152int64_t CommandOptions::TimeoutInMs() const {
153 return values.timeout_ms_;
Felipe Lemef0292972016-11-22 13:57:05 -0800154}
155
156bool CommandOptions::Always() const {
157 return values.always_;
158}
159
160PrivilegeMode CommandOptions::PrivilegeMode() const {
161 return values.account_mode_;
162}
163
164OutputMode CommandOptions::OutputMode() const {
165 return values.output_mode_;
166}
167
168std::string CommandOptions::LoggingMessage() const {
169 return values.logging_message_;
170}
171
Vishnu Nair6921f802017-11-22 09:17:23 -0800172CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(int64_t timeout_sec) {
173 return CommandOptions::CommandOptionsBuilder(SEC_TO_MSEC(timeout_sec));
174}
175
176CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeoutInMs(int64_t timeout_ms) {
177 return CommandOptions::CommandOptionsBuilder(timeout_ms);
Felipe Lemef0292972016-11-22 13:57:05 -0800178}
179
180std::string PropertiesHelper::build_type_ = "";
181int PropertiesHelper::dry_run_ = -1;
Nandana Dutt4b392be2018-11-02 16:17:05 +0000182int PropertiesHelper::unroot_ = -1;
Rhed Jao1c855122020-07-16 17:37:39 +0800183int PropertiesHelper::parallel_run_ = -1;
Felipe Lemef0292972016-11-22 13:57:05 -0800184
185bool PropertiesHelper::IsUserBuild() {
186 if (build_type_.empty()) {
187 build_type_ = android::base::GetProperty("ro.build.type", "user");
188 }
189 return "user" == build_type_;
190}
191
192bool PropertiesHelper::IsDryRun() {
193 if (dry_run_ == -1) {
194 dry_run_ = android::base::GetBoolProperty("dumpstate.dry_run", false) ? 1 : 0;
195 }
196 return dry_run_ == 1;
197}
198
Nandana Dutt4b392be2018-11-02 16:17:05 +0000199bool PropertiesHelper::IsUnroot() {
200 if (unroot_ == -1) {
201 unroot_ = android::base::GetBoolProperty("dumpstate.unroot", false) ? 1 : 0;
202 }
203 return unroot_ == 1;
204}
205
Rhed Jao1c855122020-07-16 17:37:39 +0800206bool PropertiesHelper::IsParallelRun() {
207 if (parallel_run_ == -1) {
208 parallel_run_ = android::base::GetBoolProperty("dumpstate.parallel_run",
209 /* default_value = */true) ? 1 : 0;
210 }
211 return parallel_run_ == 1;
212}
213
Felipe Lemef0292972016-11-22 13:57:05 -0800214int DumpFileToFd(int out_fd, const std::string& title, const std::string& path) {
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100215 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC)));
216 if (fd.get() < 0) {
Felipe Lemef0292972016-11-22 13:57:05 -0800217 int err = errno;
218 if (title.empty()) {
219 dprintf(out_fd, "*** Error dumping %s: %s\n", path.c_str(), strerror(err));
220 } else {
221 dprintf(out_fd, "*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(),
222 strerror(err));
223 }
224 fsync(out_fd);
225 return -1;
226 }
Narayan Kamath6b9516c2017-10-27 11:15:51 +0100227 return DumpFileFromFdToFd(title, path, fd.get(), out_fd, PropertiesHelper::IsDryRun());
Felipe Lemef0292972016-11-22 13:57:05 -0800228}
229
230int RunCommandToFd(int fd, const std::string& title, const std::vector<std::string>& full_command,
231 const CommandOptions& options) {
232 if (full_command.empty()) {
233 MYLOGE("No arguments on RunCommandToFd(%s)\n", title.c_str());
234 return -1;
235 }
236
237 int size = full_command.size() + 1; // null terminated
238 int starting_index = 0;
239 if (options.PrivilegeMode() == SU_ROOT) {
240 starting_index = 2; // "su" "root"
241 size += starting_index;
242 }
243
244 std::vector<const char*> args;
245 args.resize(size);
246
247 std::string command_string;
248 if (options.PrivilegeMode() == SU_ROOT) {
249 args[0] = kSuPath;
250 command_string += kSuPath;
251 args[1] = "root";
252 command_string += " root ";
253 }
254 for (size_t i = 0; i < full_command.size(); i++) {
255 args[i + starting_index] = full_command[i].data();
256 command_string += args[i + starting_index];
257 if (i != full_command.size() - 1) {
258 command_string += " ";
259 }
260 }
261 args[size - 1] = nullptr;
262
263 const char* command = command_string.c_str();
264
265 if (options.PrivilegeMode() == SU_ROOT && PropertiesHelper::IsUserBuild()) {
266 dprintf(fd, "Skipping '%s' on user build.\n", command);
267 return 0;
268 }
269
270 if (!title.empty()) {
271 dprintf(fd, "------ %s (%s) ------\n", title.c_str(), command);
272 fsync(fd);
273 }
274
275 const std::string& logging_message = options.LoggingMessage();
276 if (!logging_message.empty()) {
277 MYLOGI(logging_message.c_str(), command_string.c_str());
278 }
279
280 bool silent = (options.OutputMode() == REDIRECT_TO_STDERR);
281 bool redirecting_to_fd = STDOUT_FILENO != fd;
282
283 if (PropertiesHelper::IsDryRun() && !options.Always()) {
284 if (!title.empty()) {
285 dprintf(fd, "\t(skipped on dry run)\n");
286 } else if (redirecting_to_fd) {
287 // There is no title, but we should still print a dry-run message
288 dprintf(fd, "%s: skipped on dry run\n", command_string.c_str());
289 }
290 fsync(fd);
291 return 0;
292 }
293
294 const char* path = args[0];
295
296 uint64_t start = Nanotime();
297 pid_t pid = fork();
298
299 /* handle error case */
300 if (pid < 0) {
301 if (!silent) dprintf(fd, "*** fork: %s\n", strerror(errno));
302 MYLOGE("*** fork: %s\n", strerror(errno));
303 return pid;
304 }
305
306 /* handle child case */
307 if (pid == 0) {
308 if (options.PrivilegeMode() == DROP_ROOT && !DropRootUser()) {
309 if (!silent) {
310 dprintf(fd, "*** failed to drop root before running %s: %s\n", command,
311 strerror(errno));
312 }
313 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
314 return -1;
315 }
316
317 if (silent) {
318 // Redirects stdout to stderr
319 TEMP_FAILURE_RETRY(dup2(STDERR_FILENO, STDOUT_FILENO));
320 } else if (redirecting_to_fd) {
321 // Redirect stdout to fd
322 TEMP_FAILURE_RETRY(dup2(fd, STDOUT_FILENO));
323 close(fd);
324 }
325
326 /* make sure the child dies when dumpstate dies */
327 prctl(PR_SET_PDEATHSIG, SIGKILL);
328
329 /* just ignore SIGPIPE, will go down with parent's */
330 struct sigaction sigact;
331 memset(&sigact, 0, sizeof(sigact));
332 sigact.sa_handler = SIG_IGN;
Nandana Dutt263cf382018-09-26 11:22:02 +0100333 sigaction(SIGPIPE, &sigact, nullptr);
Felipe Lemef0292972016-11-22 13:57:05 -0800334
335 execvp(path, (char**)args.data());
336 // execvp's result will be handled after waitpid_with_timeout() below, but
337 // if it failed, it's safer to exit dumpstate.
338 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
339 // Must call _exit (instead of exit), otherwise it will corrupt the zip
340 // file.
341 _exit(EXIT_FAILURE);
342 }
343
344 /* handle parent case */
345 int status;
Vishnu Nair6921f802017-11-22 09:17:23 -0800346 bool ret = waitpid_with_timeout(pid, options.TimeoutInMs(), &status);
Felipe Lemef0292972016-11-22 13:57:05 -0800347 fsync(fd);
348
349 uint64_t elapsed = Nanotime() - start;
350 if (!ret) {
351 if (errno == ETIMEDOUT) {
352 if (!silent)
353 dprintf(fd, "*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
354 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
355 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
356 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
357 } else {
358 if (!silent)
359 dprintf(fd, "*** command '%s': Error after %.4fs (killing pid %d)\n", command,
360 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
361 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
362 static_cast<float>(elapsed) / NANOS_PER_SEC, pid);
363 }
364 kill(pid, SIGTERM);
Vishnu Nair6921f802017-11-22 09:17:23 -0800365 if (!waitpid_with_timeout(pid, 5000, nullptr)) {
Felipe Lemef0292972016-11-22 13:57:05 -0800366 kill(pid, SIGKILL);
Vishnu Nair6921f802017-11-22 09:17:23 -0800367 if (!waitpid_with_timeout(pid, 5000, nullptr)) {
Felipe Lemef0292972016-11-22 13:57:05 -0800368 if (!silent)
369 dprintf(fd, "could not kill command '%s' (pid %d) even with SIGKILL.\n",
370 command, pid);
371 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
372 }
373 }
374 return -1;
375 }
376
377 if (WIFSIGNALED(status)) {
378 if (!silent)
379 dprintf(fd, "*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
380 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
381 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
382 status = WEXITSTATUS(status);
383 if (!silent) dprintf(fd, "*** command '%s' failed: exit code %d\n", command, status);
384 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
385 }
386
387 return status;
388}
Ecco Park61ffcf72016-10-27 15:46:26 -0700389
Felipe Leme47e9be22016-12-21 15:37:07 -0800390} // namespace dumpstate
391} // namespace os
392} // namespace android