blob: c41cca415f7156a7dda4a8ebde24ec500e6fb437 [file] [log] [blame]
Colin Crossf45fa6b2012-03-26 12:38:26 -07001/*
2 * Copyright (C) 2008 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#include <dirent.h>
18#include <errno.h>
19#include <fcntl.h>
Felipe Lemee184f662016-10-27 10:04:47 -070020#include <libgen.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070021#include <limits.h>
22#include <poll.h>
23#include <signal.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Felipe Lemecf6a8b42016-03-11 10:38:19 -080028#include <sys/capability.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070029#include <sys/inotify.h>
Felipe Lemee184f662016-10-27 10:04:47 -070030#include <sys/klog.h>
31#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070032#include <sys/stat.h>
33#include <sys/time.h>
34#include <sys/wait.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070035#include <time.h>
36#include <unistd.h>
Felipe Lemee184f662016-10-27 10:04:47 -070037#include <string>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080038#include <vector>
Colin Crossf45fa6b2012-03-26 12:38:26 -070039
Felipe Leme71bbfc52015-11-23 14:14:51 -080040#define LOG_TAG "dumpstate"
Mark Salyzyn261a7332016-05-24 12:38:40 -070041
Mark Salyzyn290f4b92016-05-16 08:33:59 -070042#include <android-base/file.h>
Felipe Leme96c2bbb2016-09-26 09:21:21 -070043#include <android-base/properties.h>
Felipe Leme2b9b06c2016-10-14 09:13:06 -070044#include <android-base/stringprintf.h>
Jeff Brownbf7f4922012-06-07 16:40:01 -070045#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080046#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070047#include <cutils/properties.h>
48#include <cutils/sockets.h>
49#include <private/android_filesystem_config.h>
50
Robert Craig95798372013-04-04 06:33:10 -040051#include <selinux/android.h>
52
Colin Crossf45fa6b2012-03-26 12:38:26 -070053#include "dumpstate.h"
54
Felipe Lemefd8affa2016-09-30 17:38:57 -070055#define SU_PATH "/system/xbin/su"
56
Jeff Brown1dc94e32014-09-11 14:15:27 -070057static const int64_t NANOS_PER_SEC = 1000000000;
58
Felipe Leme61884122016-06-13 09:23:30 -070059static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
60
Felipe Lemee844a9d2016-09-21 15:01:39 -070061// TODO: temporary variables and functions used during C++ refactoring
62static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme9a523ae2016-10-20 15:10:33 -070063static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -070064 const CommandOptions& options = CommandOptions::DEFAULT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -070065 return ds.RunCommand(title, full_command, options);
Felipe Leme678727a2016-09-21 17:22:11 -070066}
Felipe Leme4c2d6632016-09-28 14:32:00 -070067static bool IsDryRun() {
68 return Dumpstate::GetInstance().IsDryRun();
69}
Felipe Lemed80e6b62016-10-03 13:08:14 -070070static void UpdateProgress(int delta) {
71 ds.UpdateProgress(delta);
72}
Felipe Lemee844a9d2016-09-21 15:01:39 -070073
Jeff Brownbf7f4922012-06-07 16:40:01 -070074/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070075// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070076static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080077 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080078 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070079 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070080 "/system/bin/mediacodec", // media.codec
81 "/system/bin/mediadrmserver",
82 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070083 "/system/bin/mediaserver",
84 "/system/bin/sdcard",
85 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070086 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070087 NULL,
88};
89
Felipe Lemee844a9d2016-09-21 15:01:39 -070090/* Most simple commands have 10 as timeout, so 5 is a good estimate */
91static const int WEIGHT_FILE = 5;
92
Felipe Leme30dbfa12016-09-02 12:43:26 -070093CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
94CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
95CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
96CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
97CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
98
Felipe Leme9a523ae2016-10-20 15:10:33 -070099CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : values(timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700100}
101
102CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700103 values.always_ = true;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700104 return *this;
105}
106
107CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700108 values.root_mode_ = SU_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700109 return *this;
110}
111
112CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700113 values.root_mode_ = DROP_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700114 return *this;
115}
116
117CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700118 values.stdout_mode_ = REDIRECT_TO_STDERR;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700119 return *this;
120}
121
122CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
123 const std::string& message) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700124 values.logging_message_ = message;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700125 return *this;
126}
127
128CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700129 return CommandOptions(values);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700130}
131
132CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700133 : timeout_(timeout),
134 always_(false),
Felipe Leme9a523ae2016-10-20 15:10:33 -0700135 root_mode_(DONT_DROP_ROOT),
136 stdout_mode_(NORMAL_STDOUT),
137 logging_message_("") {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700138}
139
Felipe Leme9a523ae2016-10-20 15:10:33 -0700140CommandOptions::CommandOptions(const CommandOptionsValues& values) : values(values) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700141}
142
143long CommandOptions::Timeout() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700144 return values.timeout_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700145}
146
147bool CommandOptions::Always() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700148 return values.always_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700149}
150
151RootMode CommandOptions::RootMode() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700152 return values.root_mode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700153}
154
155StdoutMode CommandOptions::StdoutMode() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700156 return values.stdout_mode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700157}
158
159std::string CommandOptions::LoggingMessage() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700160 return values.logging_message_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700161}
162
163CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
164 return CommandOptions::CommandOptionsBuilder(timeout);
165}
166
Felipe Lemed071c682016-10-20 16:48:00 -0700167Dumpstate::Dumpstate(const std::string& version, bool dry_run, const std::string& build_type)
168 : version_(version), now_(time(nullptr)), dry_run_(dry_run), build_type_(build_type) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700169}
170
171Dumpstate& Dumpstate::GetInstance() {
Felipe Lemed071c682016-10-20 16:48:00 -0700172 static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT),
173 android::base::GetBoolProperty("dumpstate.dry_run", false),
Felipe Lemed80e6b62016-10-03 13:08:14 -0700174 android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Leme9a523ae2016-10-20 15:10:33 -0700175 return singleton_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700176}
177
Felipe Leme678727a2016-09-21 17:22:11 -0700178DurationReporter::DurationReporter(const std::string& title) : DurationReporter(title, stdout) {
179}
Felipe Leme608385d2016-02-01 10:35:38 -0800180
Felipe Leme678727a2016-09-21 17:22:11 -0700181DurationReporter::DurationReporter(const std::string& title, FILE* out) : title_(title), out_(out) {
182 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700183 started_ = DurationReporter::Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800184 }
185}
186
187DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700188 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700189 uint64_t elapsed = DurationReporter::Nanotime() - started_;
Felipe Leme78f2c862015-12-21 09:55:22 -0800190 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700191 if (out_ != nullptr) {
192 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
Felipe Leme678727a2016-09-21 17:22:11 -0700193 (float)elapsed / NANOS_PER_SEC, title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800194 } else {
Felipe Leme678727a2016-09-21 17:22:11 -0700195 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800196 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800197 }
198}
199
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700200uint64_t DurationReporter::DurationReporter::Nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800201 struct timespec ts;
202 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800203 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800204}
205
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700206bool Dumpstate::IsDryRun() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700207 return dry_run_;
Felipe Leme4c2d6632016-09-28 14:32:00 -0700208}
209
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700210bool Dumpstate::IsUserBuild() const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700211 return "user" == build_type_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700212}
213
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700214std::string Dumpstate::GetPath(const std::string& suffix) const {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700215 return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700216 name_.c_str(), suffix.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700217}
218
John Spurlock5ecd4be2014-01-29 14:14:40 -0500219void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700220 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700221
John Spurlock5ecd4be2014-01-29 14:14:40 -0500222 DIR *d;
223 struct dirent *de;
224
225 if (header) printf("\n------ %s ------\n", header);
226 func(0);
227
228 if (!(d = opendir("/data/system/users"))) {
229 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
230 return;
231 }
232
233 while ((de = readdir(d))) {
234 int userid;
235 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
236 continue;
237 }
238 func(userid);
239 }
240
241 closedir(d);
242}
243
Colin Cross0c22e8b2012-11-02 15:46:56 -0700244static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700245 DIR *d;
246 struct dirent *de;
247
248 if (!(d = opendir("/proc"))) {
249 printf("Failed to open /proc (%s)\n", strerror(errno));
250 return;
251 }
252
Felipe Leme635ca312016-01-05 14:23:02 -0800253 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700254 while ((de = readdir(d))) {
255 int pid;
256 int fd;
257 char cmdpath[255];
258 char cmdline[255];
259
260 if (!(pid = atoi(de->d_name))) {
261 continue;
262 }
263
Colin Crossf45fa6b2012-03-26 12:38:26 -0700264 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800265
266 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
267 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
268 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700269 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800270 if (cmdline[0]) {
271 helper(pid, cmdline, arg);
272 continue;
273 }
274 }
275
276 // if no cmdline, a kernel thread has comm
277 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
278 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
279 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
280 close(fd);
281 if (cmdline[1]) {
282 cmdline[0] = '[';
283 size_t len = strcspn(cmdline, "\f\b\r\n");
284 cmdline[len] = ']';
285 cmdline[len+1] = '\0';
286 }
287 }
288 if (!cmdline[0]) {
289 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700290 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700291 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700292 }
293
294 closedir(d);
295}
296
Colin Cross0c22e8b2012-11-02 15:46:56 -0700297static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800298 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700299 func(pid, cmdline);
300}
301
302void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700303 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700304
Felipe Leme515eb0d2015-12-14 15:09:56 -0800305 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700306}
307
308static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
309 DIR *d;
310 struct dirent *de;
311 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800312 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700313
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700314 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700315
316 if (!(d = opendir(taskpath))) {
317 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
318 return;
319 }
320
321 func(pid, pid, cmdline);
322
323 while ((de = readdir(d))) {
324 int tid;
325 int fd;
326 char commpath[255];
327 char comm[255];
328
329 if (!(tid = atoi(de->d_name))) {
330 continue;
331 }
332
333 if (tid == pid)
334 continue;
335
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700336 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800337 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700338 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700339 strcpy(comm, "N/A");
340 } else {
341 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800342 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700343 close(fd);
344
345 c = strrchr(comm, '\n');
346 if (c) {
347 *c = '\0';
348 }
349 }
350 func(pid, tid, comm);
351 }
352
353 closedir(d);
354}
355
356void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700357 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700358
Felipe Leme8620bb42015-11-10 11:04:45 -0800359 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700360}
361
362void show_wchan(int pid, int tid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700363 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700364
Colin Crossf45fa6b2012-03-26 12:38:26 -0700365 char path[255];
366 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800367 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700368 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700369
370 memset(buffer, 0, sizeof(buffer));
371
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700372 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700373 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700374 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
375 return;
376 }
377
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800378 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
379 save_errno = errno;
380 close(fd);
381
382 if (ret < 0) {
383 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
384 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700385 }
386
Colin Cross0c22e8b2012-11-02 15:46:56 -0700387 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
388 pid == tid ? 0 : 3, "", name);
389
390 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700391
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800392 return;
393}
394
395// print time in centiseconds
396static void snprcent(char *buffer, size_t len, size_t spc,
397 unsigned long long time) {
398 static long hz; // cache discovered hz
399
400 if (hz <= 0) {
401 hz = sysconf(_SC_CLK_TCK);
402 if (hz <= 0) {
403 hz = 1000;
404 }
405 }
406
407 // convert to centiseconds
408 time = (time * 100 + (hz / 2)) / hz;
409
410 char str[16];
411
412 snprintf(str, sizeof(str), " %llu.%02u",
413 time / 100, (unsigned)(time % 100));
414 size_t offset = strlen(buffer);
415 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
416 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
417}
418
419// print permille as a percent
420static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
421 char str[16];
422
423 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
424 size_t offset = strlen(buffer);
425 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
426 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
427}
428
429void show_showtime(int pid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700430 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700431
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800432 char path[255];
433 char buffer[1023];
434 int fd, ret, save_errno;
435
436 memset(buffer, 0, sizeof(buffer));
437
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700438 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800439 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
440 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
441 return;
442 }
443
444 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
445 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700446 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800447
448 if (ret < 0) {
449 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
450 return;
451 }
452
453 // field 14 is utime
454 // field 15 is stime
455 // field 42 is iotime
456 unsigned long long utime = 0, stime = 0, iotime = 0;
457 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800458 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
459 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
460 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
461 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800462 &utime, &stime, &iotime) != 3) {
463 return;
464 }
465
466 unsigned long long total = utime + stime;
467 if (!total) {
468 return;
469 }
470
471 unsigned permille = (iotime * 1000 + (total / 2)) / total;
472 if (permille > 1000) {
473 permille = 1000;
474 }
475
476 // try to beautify and stabilize columns at <80 characters
477 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
478 if ((name[0] != '[') || utime) {
479 snprcent(buffer, sizeof(buffer), 57, utime);
480 }
481 snprcent(buffer, sizeof(buffer), 65, stime);
482 if ((name[0] != '[') || iotime) {
483 snprcent(buffer, sizeof(buffer), 73, iotime);
484 }
485 if (iotime) {
486 snprdec(buffer, sizeof(buffer), 79, permille);
487 }
488 puts(buffer); // adds a trailing newline
489
Colin Crossf45fa6b2012-03-26 12:38:26 -0700490 return;
491}
492
493void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800494 const char *title = "KERNEL LOG (dmesg)";
495 DurationReporter duration_reporter(title);
496 printf("------ %s ------\n", title);
497
Felipe Leme4c2d6632016-09-28 14:32:00 -0700498 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700499
Elliott Hughes5f87b312012-09-17 11:43:40 -0700500 /* Get size of kernel buffer */
501 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700502 if (size <= 0) {
503 printf("Unexpected klogctl return value: %d\n\n", size);
504 return;
505 }
506 char *buf = (char *) malloc(size + 1);
507 if (buf == NULL) {
508 printf("memory allocation failed\n\n");
509 return;
510 }
511 int retval = klogctl(KLOG_READ_ALL, buf, size);
512 if (retval < 0) {
513 printf("klogctl failure\n\n");
514 free(buf);
515 return;
516 }
517 buf[retval] = '\0';
518 printf("%s\n\n", buf);
519 free(buf);
520 return;
521}
522
523void do_showmap(int pid, const char *name) {
524 char title[255];
525 char arg[255];
526
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700527 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
528 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700529 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700530}
531
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700532// TODO: when converted to a Dumpstate function, it should be const
Felipe Leme678727a2016-09-21 17:22:11 -0700533static int _dump_file_from_fd(const std::string& title, const char* path, int fd) {
534 if (!title.empty()) {
535 printf("------ %s (%s", title.c_str(), path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800536
Colin Crossf45fa6b2012-03-26 12:38:26 -0700537 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800538 // Only show the modification time of non-device files.
539 size_t path_len = strlen(path);
540 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
541 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
542 (path_len < 3 || memcmp(path, "/d/", 3)) &&
543 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700544 char stamp[80];
545 time_t mtime = st.st_mtime;
546 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
547 printf(": %s", stamp);
548 }
549 printf(") ------\n");
550 }
551
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800552 bool newline = false;
553 fd_set read_set;
554 struct timeval tm;
555 while (1) {
556 FD_ZERO(&read_set);
557 FD_SET(fd, &read_set);
558 /* Timeout if no data is read for 30 seconds. */
559 tm.tv_sec = 30;
560 tm.tv_usec = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700561 uint64_t elapsed = DurationReporter::Nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800562 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
563 if (ret == -1) {
564 printf("*** %s: select failed: %s\n", path, strerror(errno));
565 newline = true;
566 break;
567 } else if (ret == 0) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700568 elapsed = DurationReporter::Nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800569 printf("*** %s: Timed out after %.3fs\n", path,
570 (float) elapsed / NANOS_PER_SEC);
571 newline = true;
572 break;
573 } else {
574 char buffer[65536];
575 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
576 if (bytes_read > 0) {
577 fwrite(buffer, bytes_read, 1, stdout);
578 newline = (buffer[bytes_read-1] == '\n');
579 } else {
580 if (bytes_read == -1) {
581 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
582 newline = true;
583 }
584 break;
585 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700586 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700587 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700588 UpdateProgress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700589 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700590
Colin Crossf45fa6b2012-03-26 12:38:26 -0700591 if (!newline) printf("\n");
Felipe Leme678727a2016-09-21 17:22:11 -0700592 if (!title.empty()) printf("\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700593 return 0;
594}
595
Felipe Leme678727a2016-09-21 17:22:11 -0700596int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700597 DurationReporter duration_reporter(title);
Felipe Lemecef02982016-10-03 17:22:22 -0700598 if (IsDryRun()) {
599 if (!title.empty()) {
600 printf("------ %s (%s) ------\n", title.c_str(), path.c_str());
601 printf("\t(skipped on dry run)\n");
602 }
603 UpdateProgress(WEIGHT_FILE);
604 return 0;
605 }
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700606 return JustDumpFile(title, path);
607}
Felipe Lemecef02982016-10-03 17:22:22 -0700608
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700609int Dumpstate::JustDumpFile(const std::string& title, const std::string& path) const {
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700610 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800611 if (fd < 0) {
612 int err = errno;
Felipe Lemecef02982016-10-03 17:22:22 -0700613 if (title.empty()) {
614 printf("*** Error dumping %s: %s\n", path.c_str(), strerror(err));
615 } else {
616 printf("*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(), strerror(err));
617 }
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800618 return -1;
619 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700620 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800621}
622
Felipe Leme71a74ac2016-03-17 15:43:25 -0700623int read_file_as_long(const char *path, long int *output) {
624 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
625 if (fd < 0) {
626 int err = errno;
627 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
628 return -1;
629 }
630 char buffer[50];
631 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
632 if (bytes_read == -1) {
633 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
634 return -2;
635 }
636 if (bytes_read == 0) {
637 MYLOGE("File %s is empty\n", path);
638 return -3;
639 }
640 *output = atoi(buffer);
641 return 0;
642}
643
Mark Salyzyn326842f2015-04-30 09:49:41 -0700644/* calls skip to gate calling dump_from_fd recursively
645 * in the specified directory. dump_from_fd defaults to
646 * dump_file_from_fd above when set to NULL. skip defaults
647 * to false when set to NULL. dump_from_fd will always be
648 * called with title NULL.
649 */
Felipe Leme678727a2016-09-21 17:22:11 -0700650int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
651 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800652 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700653 DIR *dirp;
654 struct dirent *d;
655 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800656 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700657 int fd, retval = 0;
658
Felipe Leme678727a2016-09-21 17:22:11 -0700659 if (!title.empty()) {
660 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700661 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700662 if (IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700663
664 if (dir[strlen(dir) - 1] == '/') {
665 ++slash;
666 }
667 dirp = opendir(dir);
668 if (dirp == NULL) {
669 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800670 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700671 return retval;
672 }
673
674 if (!dump_from_fd) {
675 dump_from_fd = dump_file_from_fd;
676 }
677 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
678 if ((d->d_name[0] == '.')
679 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
680 || (d->d_name[1] == '\0'))) {
681 continue;
682 }
683 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
684 (d->d_type == DT_DIR) ? "/" : "");
685 if (!newpath) {
686 retval = -errno;
687 continue;
688 }
689 if (skip && (*skip)(newpath)) {
690 continue;
691 }
692 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700693 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700694 if (ret < 0) {
695 retval = ret;
696 }
697 continue;
698 }
699 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
700 if (fd < 0) {
701 retval = fd;
702 printf("*** %s: %s\n", newpath, strerror(errno));
703 continue;
704 }
705 (*dump_from_fd)(NULL, newpath, fd);
706 }
707 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700708 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700709 printf("\n");
710 }
711 return retval;
712}
713
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800714/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
715 * it's possible to avoid issues where opening the file itself can get
716 * stuck.
717 */
718int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700719 if (IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700720
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800721 int flags = fcntl(fd, F_GETFL);
722 if (flags == -1) {
723 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800724 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800725 return -1;
726 } else if (!(flags & O_NONBLOCK)) {
727 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800728 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800729 return -1;
730 }
731 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700732}
733
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800734bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
735 sigset_t child_mask, old_mask;
736 sigemptyset(&child_mask);
737 sigaddset(&child_mask, SIGCHLD);
738
739 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
740 printf("*** sigprocmask failed: %s\n", strerror(errno));
741 return false;
742 }
743
744 struct timespec ts;
745 ts.tv_sec = timeout_seconds;
746 ts.tv_nsec = 0;
747 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
748 int saved_errno = errno;
749 // Set the signals back the way they were.
750 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
751 printf("*** sigprocmask failed: %s\n", strerror(errno));
752 if (ret == 0) {
753 return false;
754 }
755 }
756 if (ret == -1) {
757 errno = saved_errno;
758 if (errno == EAGAIN) {
759 errno = ETIMEDOUT;
760 } else {
761 printf("*** sigtimedwait failed: %s\n", strerror(errno));
762 }
763 return false;
764 }
765
766 pid_t child_pid = waitpid(pid, status, WNOHANG);
767 if (child_pid != pid) {
768 if (child_pid != -1) {
769 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
770 } else {
771 printf("*** waitpid failed: %s\n", strerror(errno));
772 }
773 return false;
774 }
775 return true;
776}
777
Felipe Leme9a523ae2016-10-20 15:10:33 -0700778int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
Felipe Leme678727a2016-09-21 17:22:11 -0700779 const CommandOptions& options) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700780 if (full_command.empty()) {
Felipe Leme678727a2016-09-21 17:22:11 -0700781 MYLOGE("No arguments on command '%s'\n", title.c_str());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700782 return -1;
783 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800784
Felipe Leme9a523ae2016-10-20 15:10:33 -0700785 int size = full_command.size() + 1; // null terminated
786 int starting_index = 0;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700787 if (options.RootMode() == SU_ROOT) {
Felipe Leme9a523ae2016-10-20 15:10:33 -0700788 starting_index = 2; // "su" "root"
789 size += starting_index;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700790 }
791
Felipe Leme6ad9c062016-09-28 11:58:36 -0700792 std::vector<const char*> args;
793 args.resize(size);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700794
Felipe Leme9a523ae2016-10-20 15:10:33 -0700795 std::string command_string;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700796 if (options.RootMode() == SU_ROOT) {
797 args[0] = SU_PATH;
Felipe Leme9a523ae2016-10-20 15:10:33 -0700798 command_string += SU_PATH;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700799 args[1] = "root";
Felipe Leme9a523ae2016-10-20 15:10:33 -0700800 command_string += " root ";
Felipe Leme30dbfa12016-09-02 12:43:26 -0700801 }
Felipe Leme9a523ae2016-10-20 15:10:33 -0700802 int i = starting_index;
803 for (auto arg = full_command.begin(); arg != full_command.end(); ++arg) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700804 args[i++] = arg->c_str();
Felipe Leme9a523ae2016-10-20 15:10:33 -0700805 command_string += arg->c_str();
806 if (arg != full_command.end() - 1) {
807 command_string += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800808 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800809 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700810 args[i] = nullptr;
811 const char* path = args[0];
Felipe Leme9a523ae2016-10-20 15:10:33 -0700812 const char* command = command_string.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700813
Felipe Leme6ad9c062016-09-28 11:58:36 -0700814 if (options.RootMode() == SU_ROOT && ds.IsUserBuild()) {
815 printf("Skipping '%s' on user build.\n", command);
816 return 0;
817 }
818
Felipe Leme678727a2016-09-21 17:22:11 -0700819 if (!title.empty()) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700820 printf("------ %s (%s) ------\n", title.c_str(), command);
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700821 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700822
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800823 fflush(stdout);
Felipe Leme9a523ae2016-10-20 15:10:33 -0700824 DurationReporter duration_reporter(title);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700825
Felipe Leme9a523ae2016-10-20 15:10:33 -0700826 const std::string& logging_message = options.LoggingMessage();
827 if (!logging_message.empty()) {
828 MYLOGI(logging_message.c_str(), command_string.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800829 }
830
Felipe Leme4c2d6632016-09-28 14:32:00 -0700831 if (IsDryRun() && !options.Always()) {
832 if (!title.empty()) {
833 printf("\t(skipped on dry run)\n");
834 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700835 UpdateProgress(options.Timeout());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700836 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700837 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800838
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700839 int status = JustRunCommand(command, path, args, options);
Felipe Lemeea160d12016-03-24 11:29:44 -0700840
Felipe Leme30dbfa12016-09-02 12:43:26 -0700841 /* TODO: for now we're simplifying the progress calculation by using the
842 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
843 * where its weight should be much higher proportionally to its timeout.
844 * Ideally, it should use a options.EstimatedDuration() instead...*/
845 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800846
Felipe Leme2b9b06c2016-10-14 09:13:06 -0700847 if (weight > 0) {
848 UpdateProgress(weight);
849 }
850
851 return status;
852}
853
854int Dumpstate::JustRunCommand(const char* command, const char* path, std::vector<const char*>& args,
855 const CommandOptions& options) const {
856 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
857
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700858 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700859 pid_t pid = fork();
860
861 /* handle error case */
862 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700863 if (!silent) printf("*** fork: %s\n", strerror(errno));
864 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700865 return pid;
866 }
867
868 /* handle child case */
869 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700870 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
871 if (!silent)
872 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700873 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700874 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800875 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700876
Felipe Leme29c39712016-04-01 10:02:00 -0700877 if (silent) {
878 // Redirect stderr to stdout
879 dup2(STDERR_FILENO, STDOUT_FILENO);
880 }
881
John Michelaue7b6cf12013-03-07 15:35:35 -0600882 /* make sure the child dies when dumpstate dies */
883 prctl(PR_SET_PDEATHSIG, SIGKILL);
884
Andres Morales2e671bb2014-08-21 12:38:22 -0700885 /* just ignore SIGPIPE, will go down with parent's */
886 struct sigaction sigact;
887 memset(&sigact, 0, sizeof(sigact));
888 sigact.sa_handler = SIG_IGN;
889 sigaction(SIGPIPE, &sigact, NULL);
890
Felipe Leme6ad9c062016-09-28 11:58:36 -0700891 execvp(path, (char**)args.data());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700892 // execvp's result will be handled after waitpid_with_timeout() below, but
893 // if it failed, it's safer to exit dumpstate.
894 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700895 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700896 // Must call _exit (instead of exit), otherwise it will corrupt the zip
897 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700898 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700899 }
900
901 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800902 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700903 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700904 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800905 if (!ret) {
906 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700907 if (!silent)
908 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
909 (float)elapsed / NANOS_PER_SEC, pid);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700910 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
Felipe Leme30dbfa12016-09-02 12:43:26 -0700911 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800912 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700913 if (!silent)
914 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
915 (float)elapsed / NANOS_PER_SEC, pid);
916 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
917 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800918 }
919 kill(pid, SIGTERM);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700920 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800921 kill(pid, SIGKILL);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700922 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700923 if (!silent)
924 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
925 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700926 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700927 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700928 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800929 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700930 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800931
932 if (WIFSIGNALED(status)) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700933 if (!silent)
934 printf("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
935 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800936 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700937 status = WEXITSTATUS(status);
938 if (!silent) printf("*** command '%s' failed: exit code %d\n", command, status);
939 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800940 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800941
942 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700943}
944
Felipe Leme9a523ae2016-10-20 15:10:33 -0700945void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
Felipe Leme678727a2016-09-21 17:22:11 -0700946 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700947 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
948 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme9a523ae2016-10-20 15:10:33 -0700949 dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700950 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700951}
952
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800953bool drop_root_user() {
954 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
Felipe Leme26c41572016-10-06 14:34:43 -0700955 MYLOGD("drop_root_user(): already running as Shell\n");
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800956 return true;
957 }
958 /* ensure we will keep capabilities when we drop root */
959 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
960 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
961 return false;
962 }
963
964 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700965 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
966 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800967 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
968 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
969 return false;
970 }
971 if (setgid(AID_SHELL) != 0) {
972 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
973 return false;
974 }
975 if (setuid(AID_SHELL) != 0) {
976 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
977 return false;
978 }
979
980 struct __user_cap_header_struct capheader;
981 struct __user_cap_data_struct capdata[2];
982 memset(&capheader, 0, sizeof(capheader));
983 memset(&capdata, 0, sizeof(capdata));
984 capheader.version = _LINUX_CAPABILITY_VERSION_3;
985 capheader.pid = 0;
986
Wei Liuf87959e2016-08-26 14:51:42 -0700987 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
988 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
989 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
990 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800991 capdata[0].inheritable = 0;
992 capdata[1].inheritable = 0;
993
994 if (capset(&capheader, &capdata[0]) < 0) {
995 MYLOGE("capset failed: %s\n", strerror(errno));
996 return false;
997 }
998
999 return true;
1000}
1001
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001002void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -07001003 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
1004
1005 am.insert(am.end(), args.begin(), args.end());
1006
Felipe Leme678727a2016-09-21 17:22:11 -07001007 RunCommand("", am, CommandOptions::WithTimeout(20)
1008 .Log("Sending broadcast: '%s'\n")
1009 .Always()
1010 .DropRoot()
1011 .RedirectStderr()
1012 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001013}
1014
Colin Crossf45fa6b2012-03-26 12:38:26 -07001015size_t num_props = 0;
1016static char* props[2000];
1017
1018static void print_prop(const char *key, const char *name, void *user) {
1019 (void) user;
1020 if (num_props < sizeof(props) / sizeof(props[0])) {
1021 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
1022 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
1023 props[num_props++] = strdup(buf);
1024 }
1025}
1026
1027static int compare_prop(const void *a, const void *b) {
1028 return strcmp(*(char * const *) a, *(char * const *) b);
1029}
1030
1031/* prints all the system properties */
1032void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001033 const char* title = "SYSTEM PROPERTIES";
1034 DurationReporter duration_reporter(title);
1035 printf("------ %s ------\n", title);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001036 if (IsDryRun()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001037 size_t i;
1038 num_props = 0;
1039 property_list(print_prop, NULL);
1040 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1041
Colin Crossf45fa6b2012-03-26 12:38:26 -07001042 for (i = 0; i < num_props; ++i) {
1043 fputs(props[i], stdout);
1044 free(props[i]);
1045 }
1046 printf("\n");
1047}
1048
Felipe Leme2628e9e2016-04-12 16:36:51 -07001049int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001050 int s = android_get_control_socket(service);
1051 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001052 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001053 exit(1);
1054 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001055 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001056 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001057 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001058 exit(1);
1059 }
1060
1061 struct sockaddr addr;
1062 socklen_t alen = sizeof(addr);
1063 int fd = accept(s, &addr, &alen);
1064 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001065 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001066 exit(1);
1067 }
1068
Felipe Leme2628e9e2016-04-12 16:36:51 -07001069 return fd;
1070}
1071
1072/* redirect output to a service control socket */
1073void redirect_to_socket(FILE *redirect, const char *service) {
1074 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001075 fflush(redirect);
1076 dup2(fd, fileno(redirect));
1077 close(fd);
1078}
1079
Felipe Leme2628e9e2016-04-12 16:36:51 -07001080// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001081void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001082 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001083
1084 /* skip initial slash */
1085 if (chp[0] == '/')
1086 chp++;
1087
1088 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001089 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001090 while (chp && chp[0]) {
1091 chp = strchr(chp, '/');
1092 if (chp) {
1093 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001094 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001095 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001096 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001097 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001098 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001099 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001100 }
1101 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001102 *chp++ = '/';
1103 }
1104 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001105}
1106
Felipe Leme0f3fb202016-06-10 17:10:53 -07001107void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001108 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001109
Felipe Leme0f3fb202016-06-10 17:10:53 -07001110 int fd = TEMP_FAILURE_RETRY(open(path,
1111 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001112 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001113 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001114 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001115 exit(1);
1116 }
1117
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001118 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001119 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001120}
1121
Felipe Leme0f3fb202016-06-10 17:10:53 -07001122void redirect_to_file(FILE *redirect, char *path) {
1123 _redirect_to_file(redirect, path, O_TRUNC);
1124}
1125
1126void redirect_to_existing_file(FILE *redirect, char *path) {
1127 _redirect_to_file(redirect, path, O_APPEND);
1128}
1129
Jeff Brownbf7f4922012-06-07 16:40:01 -07001130static bool should_dump_native_traces(const char* path) {
1131 for (const char** p = native_processes_to_dump; *p; p++) {
1132 if (!strcmp(*p, path)) {
1133 return true;
1134 }
1135 }
1136 return false;
1137}
1138
1139/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1140const char *dump_traces() {
Felipe Lemee184f662016-10-27 10:04:47 -07001141 DurationReporter duration_reporter("DUMP TRACES");
Felipe Lemed402e7d2016-08-03 09:22:27 -07001142
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001143 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001144
Felipe Lemee184f662016-10-27 10:04:47 -07001145 std::string traces_path = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1146 if (traces_path.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001147
1148 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Lemee184f662016-10-27 10:04:47 -07001149 std::string anrtraces_path = traces_path + ".anr";
1150 if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
1151 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001152 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001153 }
1154
Colin Crossf45fa6b2012-03-26 12:38:26 -07001155 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Lemee184f662016-10-27 10:04:47 -07001156 int fd = TEMP_FAILURE_RETRY(open(traces_path.c_str(),
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001157 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1158 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001159 if (fd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001160 MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001161 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001162 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001163 int chmod_ret = fchmod(fd, 0666);
1164 if (chmod_ret < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001165 MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001166 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001167 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001168 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001169
Felipe Leme8620bb42015-11-10 11:04:45 -08001170 /* Variables below must be initialized before 'goto' statements */
1171 int dalvik_found = 0;
1172 int ifd, wfd = -1;
1173
Colin Crossf45fa6b2012-03-26 12:38:26 -07001174 /* walk /proc and kill -QUIT all Dalvik processes */
1175 DIR *proc = opendir("/proc");
1176 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001177 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001178 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001179 }
1180
1181 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001182 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001183 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001184 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001185 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001186 }
1187
Felipe Lemee184f662016-10-27 10:04:47 -07001188 wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001189 if (wfd < 0) {
Felipe Lemee184f662016-10-27 10:04:47 -07001190 MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001191 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001192 }
1193
1194 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001195 while ((d = readdir(proc))) {
1196 int pid = atoi(d->d_name);
1197 if (pid <= 0) continue;
1198
Jeff Brownbf7f4922012-06-07 16:40:01 -07001199 char path[PATH_MAX];
1200 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001201 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001202 ssize_t len = readlink(path, data, sizeof(data) - 1);
1203 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001204 continue;
1205 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001206 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001207
Colin Cross0d6180f2014-07-16 19:00:46 -07001208 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001209 /* skip zygote -- it won't dump its stack anyway */
1210 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001211 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001212 len = read(cfd, data, sizeof(data) - 1);
1213 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001214 if (len <= 0) {
1215 continue;
1216 }
1217 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001218 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001219 continue;
1220 }
1221
1222 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001223 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001224 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001225 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001226 continue;
1227 }
1228
1229 /* wait for the writable-close notification from inotify */
1230 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001231 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001232 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001233 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001234 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001235 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001236 } else {
1237 struct inotify_event ie;
1238 read(ifd, &ie, sizeof(ie));
1239 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001240
1241 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001242 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001243 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001244 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1245 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001246 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001247 } else if (should_dump_native_traces(data)) {
1248 /* dump native process if appropriate */
1249 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001250 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001251 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001252 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001253 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001254
1255 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1256 if (timeout_failures == 3) {
1257 dprintf(fd, "too many stack dump failures, skipping...\n");
1258 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1259 dprintf(fd, "dumping failed, likely due to a timeout\n");
1260 timeout_failures++;
1261 } else {
1262 timeout_failures = 0;
1263 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001264 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1265 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001266 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001267 }
1268 }
1269
Colin Crossf45fa6b2012-03-26 12:38:26 -07001270 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001271 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001272 }
1273
Felipe Lemee184f662016-10-27 10:04:47 -07001274 static std::string dumptraces_path = android::base::StringPrintf(
1275 "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
1276 if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
1277 MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
1278 strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001279 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001280 }
Felipe Lemee184f662016-10-27 10:04:47 -07001281 result = dumptraces_path.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001282
1283 /* replace the saved [ANR] traces.txt file */
Felipe Lemee184f662016-10-27 10:04:47 -07001284 rename(anrtraces_path.c_str(), traces_path.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001285
1286error_close_ifd:
1287 close(ifd);
1288error_close_fd:
1289 close(fd);
1290 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001291}
1292
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001293void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001294 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme4c2d6632016-09-28 14:32:00 -07001295 if (IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001296 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001297 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001298 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001299 if (!fp) {
1300 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1301 return;
1302 }
1303 char table[16];
1304 // Each line has an integer (the table number), a space, and a string (the table name). We only
1305 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1306 // Add a fixed max limit so this doesn't go awry.
1307 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001308 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1309 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001310 }
1311 fclose(fp);
1312}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001313
Felipe Leme71bbfc52015-11-23 14:14:51 -08001314// TODO: make this function thread safe if sections are generated in parallel.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001315void Dumpstate::UpdateProgress(int delta) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001316 if (!update_progress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001317
Felipe Lemed80e6b62016-10-03 13:08:14 -07001318 progress_ += delta;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001319
1320 char key[PROPERTY_KEY_MAX];
1321 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001322
1323 // adjusts max on the fly
Felipe Leme9a523ae2016-10-20 15:10:33 -07001324 if (progress_ > weight_total_) {
1325 int new_total = weight_total_ * 1.2;
1326 MYLOGD("Adjusting total weight from %d to %d\n", weight_total_, new_total);
1327 weight_total_ = new_total;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001328 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
Felipe Leme9a523ae2016-10-20 15:10:33 -07001329 snprintf(value, sizeof(value), "%d", weight_total_);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001330 int status = property_set(key, value);
Felipe Lemee844a9d2016-09-21 15:01:39 -07001331 if (status != 0) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001332 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001333 key, value, status);
1334 }
1335 }
1336
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001337 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
Felipe Lemed80e6b62016-10-03 13:08:14 -07001338 snprintf(value, sizeof(value), "%d", progress_);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001339
Felipe Lemed80e6b62016-10-03 13:08:14 -07001340 if (progress_ % 100 == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001341 // We don't want to spam logcat, so only log multiples of 100.
Felipe Leme9a523ae2016-10-20 15:10:33 -07001342 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weight_total_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001343 } else {
1344 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1345 // directly for debuggging.
Felipe Leme9a523ae2016-10-20 15:10:33 -07001346 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weight_total_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001347 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001348
Felipe Leme9a523ae2016-10-20 15:10:33 -07001349 if (control_socket_fd_ >= 0) {
1350 dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress_, weight_total_);
1351 fsync(control_socket_fd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001352 }
1353
Felipe Leme71bbfc52015-11-23 14:14:51 -08001354 int status = property_set(key, value);
1355 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001356 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001357 key, value, status);
1358 }
1359}
Felipe Lemee338bf62015-12-07 14:03:50 -08001360
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001361void Dumpstate::TakeScreenshot(const std::string& path) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001362 const std::string& real_path = path.empty() ? screenshot_path_ : path;
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001363 int status =
Felipe Leme9a523ae2016-10-20 15:10:33 -07001364 RunCommand("", {"/system/bin/screencap", "-p", real_path},
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001365 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1366 if (status == 0) {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001367 MYLOGD("Screenshot saved on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001368 } else {
Felipe Leme9a523ae2016-10-20 15:10:33 -07001369 MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001370 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001371}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001372
Felipe Leme0c80cf02016-01-05 13:25:34 -08001373void vibrate(FILE* vibrator, int ms) {
1374 fprintf(vibrator, "%d\n", ms);
1375 fflush(vibrator);
1376}
1377
1378bool is_dir(const char* pathname) {
1379 struct stat info;
1380 if (stat(pathname, &info) == -1) {
1381 return false;
1382 }
1383 return S_ISDIR(info.st_mode);
1384}
1385
1386time_t get_mtime(int fd, time_t default_mtime) {
1387 struct stat info;
1388 if (fstat(fd, &info) == -1) {
1389 return default_mtime;
1390 }
1391 return info.st_mtime;
1392}
1393
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001394void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001395 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001396 struct hex {
1397 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001398 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001399 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1400 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1401 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1402 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1403
1404 std::string buffer;
1405 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1406 return;
1407 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001408
1409 printf("------ %s Extended CSD ------\n", ext_csd_path);
1410
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001411 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1412 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001413 return;
1414 }
1415
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001416 int ext_csd_rev = 0;
1417 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1418 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1419 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1420 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001421 return;
1422 }
1423
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001424 static const char *ver_str[] = {
1425 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1426 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001427 printf("rev 1.%d (MMC %s)\n",
1428 ext_csd_rev,
1429 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1430 ver_str[ext_csd_rev] :
1431 "Unknown");
1432 if (ext_csd_rev < 7) {
1433 printf("\n");
1434 return;
1435 }
1436
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001437 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1438 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001439 return;
1440 }
1441
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001442 int ext_pre_eol_info = 0;
1443 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1444 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1445 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1446 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001447 return;
1448 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001449
1450 static const char *eol_str[] = {
1451 "Undefined",
1452 "Normal",
1453 "Warning (consumed 80% of reserve)",
1454 "Urgent (consumed 90% of reserve)"
1455 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001456 printf("PRE_EOL_INFO %d (MMC %s)\n",
1457 ext_pre_eol_info,
1458 eol_str[(ext_pre_eol_info < (int)
1459 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1460 ext_pre_eol_info : 0]);
1461
1462 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1463 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001464 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001465 int ext_device_life_time_est;
1466 static const char *est_str[] = {
1467 "Undefined",
1468 "0-10% of device lifetime used",
1469 "10-20% of device lifetime used",
1470 "20-30% of device lifetime used",
1471 "30-40% of device lifetime used",
1472 "40-50% of device lifetime used",
1473 "50-60% of device lifetime used",
1474 "60-70% of device lifetime used",
1475 "70-80% of device lifetime used",
1476 "80-90% of device lifetime used",
1477 "90-100% of device lifetime used",
1478 "Exceeded the maximum estimated device lifetime",
1479 };
1480
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001481 if (buffer.length() < (lifetime + sizeof(hex))) {
1482 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001483 break;
1484 }
1485
1486 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001487 sub = buffer.substr(lifetime, sizeof(hex));
1488 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1489 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001490 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001491 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1492 sizeof(hex)) + 'A',
1493 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001494 continue;
1495 }
1496 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001497 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1498 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001499 ext_device_life_time_est,
1500 est_str[(ext_device_life_time_est < (int)
1501 (sizeof(est_str) / sizeof(est_str[0]))) ?
1502 ext_device_life_time_est : 0]);
1503 }
1504
1505 printf("\n");
1506}