blob: 641d80cf3f7d531feb56a758c4ee313cc4a8a7ff [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>
20#include <limits.h>
21#include <poll.h>
22#include <signal.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <stdlib.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080026#include <string>
Colin Crossf45fa6b2012-03-26 12:38:26 -070027#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>
30#include <sys/stat.h>
31#include <sys/time.h>
32#include <sys/wait.h>
33#include <sys/klog.h>
34#include <time.h>
35#include <unistd.h>
Felipe Leme36b3f6f2015-11-19 15:41:04 -080036#include <vector>
John Michelaue7b6cf12013-03-07 15:35:35 -060037#include <sys/prctl.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070038
Felipe Leme71bbfc52015-11-23 14:14:51 -080039#define LOG_TAG "dumpstate"
Mark Salyzyn261a7332016-05-24 12:38:40 -070040
Mark Salyzyn290f4b92016-05-16 08:33:59 -070041#include <android-base/file.h>
Felipe Leme96c2bbb2016-09-26 09:21:21 -070042#include <android-base/properties.h>
Jeff Brownbf7f4922012-06-07 16:40:01 -070043#include <cutils/debugger.h>
Felipe Leme71bbfc52015-11-23 14:14:51 -080044#include <cutils/log.h>
Colin Crossf45fa6b2012-03-26 12:38:26 -070045#include <cutils/properties.h>
46#include <cutils/sockets.h>
47#include <private/android_filesystem_config.h>
48
Robert Craig95798372013-04-04 06:33:10 -040049#include <selinux/android.h>
50
Colin Crossf45fa6b2012-03-26 12:38:26 -070051#include "dumpstate.h"
52
Jeff Brown1dc94e32014-09-11 14:15:27 -070053static const int64_t NANOS_PER_SEC = 1000000000;
54
Felipe Leme61884122016-06-13 09:23:30 -070055static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
56
Felipe Lemee844a9d2016-09-21 15:01:39 -070057// TODO: temporary variables and functions used during C++ refactoring
58static Dumpstate& ds = Dumpstate::GetInstance();
59
Jeff Brownbf7f4922012-06-07 16:40:01 -070060/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070061// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070062static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080063 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080064 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070065 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070066 "/system/bin/mediacodec", // media.codec
67 "/system/bin/mediadrmserver",
68 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070069 "/system/bin/mediaserver",
70 "/system/bin/sdcard",
71 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070072 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070073 NULL,
74};
75
Felipe Lemee844a9d2016-09-21 15:01:39 -070076/* Most simple commands have 10 as timeout, so 5 is a good estimate */
77static const int WEIGHT_FILE = 5;
78
Felipe Leme30dbfa12016-09-02 12:43:26 -070079CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
80CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
81CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
82CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
83CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
84
Felipe Lemeb0f669d2016-09-26 18:26:11 -070085CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : values_(timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -070086}
87
88CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -070089 values_.always_ = true;
Felipe Leme30dbfa12016-09-02 12:43:26 -070090 return *this;
91}
92
93CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -070094 values_.rootMode_ = SU_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -070095 return *this;
96}
97
98CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -070099 values_.rootMode_ = DROP_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700100 return *this;
101}
102
103CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700104 values_.stdoutMode_ = REDIRECT_TO_STDERR;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700105 return *this;
106}
107
108CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
109 const std::string& message) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700110 values_.loggingMessage_ = message;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700111 return *this;
112}
113
114CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700115 return CommandOptions(values_);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700116}
117
118CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700119 : timeout_(timeout),
120 always_(false),
121 rootMode_(DONT_DROP_ROOT),
122 stdoutMode_(NORMAL_STDOUT),
123 loggingMessage_("") {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700124}
125
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700126CommandOptions::CommandOptions(const CommandOptionsValues& values) : values_(values) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700127}
128
129long CommandOptions::Timeout() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700130 return values_.timeout_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700131}
132
133bool CommandOptions::Always() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700134 return values_.always_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700135}
136
137RootMode CommandOptions::RootMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700138 return values_.rootMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700139}
140
141StdoutMode CommandOptions::StdoutMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700142 return values_.stdoutMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700143}
144
145std::string CommandOptions::LoggingMessage() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700146 return values_.loggingMessage_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700147}
148
149CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
150 return CommandOptions::CommandOptionsBuilder(timeout);
151}
152
Felipe Lemee844a9d2016-09-21 15:01:39 -0700153Dumpstate::Dumpstate() {
154}
155
156Dumpstate& Dumpstate::GetInstance() {
157 static Dumpstate sSingleton;
158 return sSingleton;
159}
160
Felipe Leme608385d2016-02-01 10:35:38 -0800161DurationReporter::DurationReporter(const char *title) : DurationReporter(title, stdout) {}
162
163DurationReporter::DurationReporter(const char *title, FILE *out) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700164 title_ = title;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700165 if (title != nullptr) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700166 started_ = DurationReporter::Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800167 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700168 out_ = out;
Felipe Leme78f2c862015-12-21 09:55:22 -0800169}
170
171DurationReporter::~DurationReporter() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700172 if (title_ != nullptr) {
173 uint64_t elapsed = DurationReporter::Nanotime() - started_;
Felipe Leme78f2c862015-12-21 09:55:22 -0800174 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700175 if (out_ != nullptr) {
176 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
177 (float)elapsed / NANOS_PER_SEC, title_);
Felipe Leme608385d2016-02-01 10:35:38 -0800178 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700179 MYLOGD("Duration of '%s': %.3fs\n", title_, (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800180 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800181 }
182}
183
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700184uint64_t DurationReporter::DurationReporter::Nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800185 struct timespec ts;
186 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800187 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800188}
189
Felipe Lemee844a9d2016-09-21 15:01:39 -0700190// TODO: temporary function used during the C++ refactoring
191static bool is_dry_run() {
192 return Dumpstate::GetInstance().IsDryRun();
193}
194
John Spurlock5ecd4be2014-01-29 14:14:40 -0500195void for_each_userid(void (*func)(int), const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700196 if (is_dry_run()) return;
197
John Spurlock5ecd4be2014-01-29 14:14:40 -0500198 DIR *d;
199 struct dirent *de;
200
201 if (header) printf("\n------ %s ------\n", header);
202 func(0);
203
204 if (!(d = opendir("/data/system/users"))) {
205 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
206 return;
207 }
208
209 while ((de = readdir(d))) {
210 int userid;
211 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
212 continue;
213 }
214 func(userid);
215 }
216
217 closedir(d);
218}
219
Colin Cross0c22e8b2012-11-02 15:46:56 -0700220static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700221 DIR *d;
222 struct dirent *de;
223
224 if (!(d = opendir("/proc"))) {
225 printf("Failed to open /proc (%s)\n", strerror(errno));
226 return;
227 }
228
Felipe Leme635ca312016-01-05 14:23:02 -0800229 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700230 while ((de = readdir(d))) {
231 int pid;
232 int fd;
233 char cmdpath[255];
234 char cmdline[255];
235
236 if (!(pid = atoi(de->d_name))) {
237 continue;
238 }
239
Colin Crossf45fa6b2012-03-26 12:38:26 -0700240 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800241
242 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
243 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
244 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700245 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800246 if (cmdline[0]) {
247 helper(pid, cmdline, arg);
248 continue;
249 }
250 }
251
252 // if no cmdline, a kernel thread has comm
253 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
254 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
255 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
256 close(fd);
257 if (cmdline[1]) {
258 cmdline[0] = '[';
259 size_t len = strcspn(cmdline, "\f\b\r\n");
260 cmdline[len] = ']';
261 cmdline[len+1] = '\0';
262 }
263 }
264 if (!cmdline[0]) {
265 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700266 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700267 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700268 }
269
270 closedir(d);
271}
272
Colin Cross0c22e8b2012-11-02 15:46:56 -0700273static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800274 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700275 func(pid, cmdline);
276}
277
278void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700279 if (is_dry_run()) return;
280
Felipe Leme515eb0d2015-12-14 15:09:56 -0800281 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700282}
283
284static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
285 DIR *d;
286 struct dirent *de;
287 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800288 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700289
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700290 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700291
292 if (!(d = opendir(taskpath))) {
293 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
294 return;
295 }
296
297 func(pid, pid, cmdline);
298
299 while ((de = readdir(d))) {
300 int tid;
301 int fd;
302 char commpath[255];
303 char comm[255];
304
305 if (!(tid = atoi(de->d_name))) {
306 continue;
307 }
308
309 if (tid == pid)
310 continue;
311
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700312 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800313 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700314 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700315 strcpy(comm, "N/A");
316 } else {
317 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800318 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700319 close(fd);
320
321 c = strrchr(comm, '\n');
322 if (c) {
323 *c = '\0';
324 }
325 }
326 func(pid, tid, comm);
327 }
328
329 closedir(d);
330}
331
332void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700333 if (is_dry_run()) return;
334
Felipe Leme8620bb42015-11-10 11:04:45 -0800335 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700336}
337
338void show_wchan(int pid, int tid, const char *name) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700339 if (is_dry_run()) return;
340
Colin Crossf45fa6b2012-03-26 12:38:26 -0700341 char path[255];
342 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800343 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700344 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700345
346 memset(buffer, 0, sizeof(buffer));
347
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700348 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700349 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700350 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
351 return;
352 }
353
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800354 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
355 save_errno = errno;
356 close(fd);
357
358 if (ret < 0) {
359 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
360 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700361 }
362
Colin Cross0c22e8b2012-11-02 15:46:56 -0700363 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
364 pid == tid ? 0 : 3, "", name);
365
366 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700367
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800368 return;
369}
370
371// print time in centiseconds
372static void snprcent(char *buffer, size_t len, size_t spc,
373 unsigned long long time) {
374 static long hz; // cache discovered hz
375
376 if (hz <= 0) {
377 hz = sysconf(_SC_CLK_TCK);
378 if (hz <= 0) {
379 hz = 1000;
380 }
381 }
382
383 // convert to centiseconds
384 time = (time * 100 + (hz / 2)) / hz;
385
386 char str[16];
387
388 snprintf(str, sizeof(str), " %llu.%02u",
389 time / 100, (unsigned)(time % 100));
390 size_t offset = strlen(buffer);
391 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
392 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
393}
394
395// print permille as a percent
396static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
397 char str[16];
398
399 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
400 size_t offset = strlen(buffer);
401 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
402 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
403}
404
405void show_showtime(int pid, const char *name) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700406 if (is_dry_run()) return;
407
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800408 char path[255];
409 char buffer[1023];
410 int fd, ret, save_errno;
411
412 memset(buffer, 0, sizeof(buffer));
413
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700414 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800415 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
416 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
417 return;
418 }
419
420 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
421 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700422 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800423
424 if (ret < 0) {
425 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
426 return;
427 }
428
429 // field 14 is utime
430 // field 15 is stime
431 // field 42 is iotime
432 unsigned long long utime = 0, stime = 0, iotime = 0;
433 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800434 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
435 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
436 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
437 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800438 &utime, &stime, &iotime) != 3) {
439 return;
440 }
441
442 unsigned long long total = utime + stime;
443 if (!total) {
444 return;
445 }
446
447 unsigned permille = (iotime * 1000 + (total / 2)) / total;
448 if (permille > 1000) {
449 permille = 1000;
450 }
451
452 // try to beautify and stabilize columns at <80 characters
453 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
454 if ((name[0] != '[') || utime) {
455 snprcent(buffer, sizeof(buffer), 57, utime);
456 }
457 snprcent(buffer, sizeof(buffer), 65, stime);
458 if ((name[0] != '[') || iotime) {
459 snprcent(buffer, sizeof(buffer), 73, iotime);
460 }
461 if (iotime) {
462 snprdec(buffer, sizeof(buffer), 79, permille);
463 }
464 puts(buffer); // adds a trailing newline
465
Colin Crossf45fa6b2012-03-26 12:38:26 -0700466 return;
467}
468
469void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800470 const char *title = "KERNEL LOG (dmesg)";
471 DurationReporter duration_reporter(title);
472 printf("------ %s ------\n", title);
473
Felipe Lemed402e7d2016-08-03 09:22:27 -0700474 if (is_dry_run()) return;
475
Elliott Hughes5f87b312012-09-17 11:43:40 -0700476 /* Get size of kernel buffer */
477 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700478 if (size <= 0) {
479 printf("Unexpected klogctl return value: %d\n\n", size);
480 return;
481 }
482 char *buf = (char *) malloc(size + 1);
483 if (buf == NULL) {
484 printf("memory allocation failed\n\n");
485 return;
486 }
487 int retval = klogctl(KLOG_READ_ALL, buf, size);
488 if (retval < 0) {
489 printf("klogctl failure\n\n");
490 free(buf);
491 return;
492 }
493 buf[retval] = '\0';
494 printf("%s\n\n", buf);
495 free(buf);
496 return;
497}
498
499void do_showmap(int pid, const char *name) {
500 char title[255];
501 char arg[255];
502
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700503 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
504 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700505 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700506}
507
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800508static int _dump_file_from_fd(const char *title, const char *path, int fd) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700509 if (title) {
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800510 printf("------ %s (%s", title, path);
511
Colin Crossf45fa6b2012-03-26 12:38:26 -0700512 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800513 // Only show the modification time of non-device files.
514 size_t path_len = strlen(path);
515 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
516 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
517 (path_len < 3 || memcmp(path, "/d/", 3)) &&
518 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700519 char stamp[80];
520 time_t mtime = st.st_mtime;
521 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
522 printf(": %s", stamp);
523 }
524 printf(") ------\n");
525 }
Felipe Lemed402e7d2016-08-03 09:22:27 -0700526 if (is_dry_run()) {
527 update_progress(WEIGHT_FILE);
528 close(fd);
529 return 0;
530 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700531
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800532 bool newline = false;
533 fd_set read_set;
534 struct timeval tm;
535 while (1) {
536 FD_ZERO(&read_set);
537 FD_SET(fd, &read_set);
538 /* Timeout if no data is read for 30 seconds. */
539 tm.tv_sec = 30;
540 tm.tv_usec = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700541 uint64_t elapsed = DurationReporter::Nanotime();
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800542 int ret = TEMP_FAILURE_RETRY(select(fd + 1, &read_set, NULL, NULL, &tm));
543 if (ret == -1) {
544 printf("*** %s: select failed: %s\n", path, strerror(errno));
545 newline = true;
546 break;
547 } else if (ret == 0) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700548 elapsed = DurationReporter::Nanotime() - elapsed;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800549 printf("*** %s: Timed out after %.3fs\n", path,
550 (float) elapsed / NANOS_PER_SEC);
551 newline = true;
552 break;
553 } else {
554 char buffer[65536];
555 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
556 if (bytes_read > 0) {
557 fwrite(buffer, bytes_read, 1, stdout);
558 newline = (buffer[bytes_read-1] == '\n');
559 } else {
560 if (bytes_read == -1) {
561 printf("*** %s: Failed to read from fd: %s", path, strerror(errno));
562 newline = true;
563 }
564 break;
565 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700566 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700567 }
Felipe Leme71bbfc52015-11-23 14:14:51 -0800568 update_progress(WEIGHT_FILE);
Elliott Hughes997abb62015-05-15 17:05:40 -0700569 close(fd);
Christopher Ferris7dc7f322014-07-22 16:08:19 -0700570
Colin Crossf45fa6b2012-03-26 12:38:26 -0700571 if (!newline) printf("\n");
572 if (title) printf("\n");
573 return 0;
574}
575
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800576int dump_file(const char *title, const char *path) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700577 return DumpFile(title, path);
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700578}
579
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700580int DumpFile(const char* title, const std::string& path) {
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700581 DurationReporter durationReporter(title);
582 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800583 if (fd < 0) {
584 int err = errno;
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700585 printf("*** %s: %s\n", path.c_str(), strerror(err));
586 if (title != nullptr) printf("\n");
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800587 return -1;
588 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700589 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800590}
591
Felipe Leme71a74ac2016-03-17 15:43:25 -0700592int read_file_as_long(const char *path, long int *output) {
593 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
594 if (fd < 0) {
595 int err = errno;
596 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
597 return -1;
598 }
599 char buffer[50];
600 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
601 if (bytes_read == -1) {
602 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
603 return -2;
604 }
605 if (bytes_read == 0) {
606 MYLOGE("File %s is empty\n", path);
607 return -3;
608 }
609 *output = atoi(buffer);
610 return 0;
611}
612
Mark Salyzyn326842f2015-04-30 09:49:41 -0700613/* calls skip to gate calling dump_from_fd recursively
614 * in the specified directory. dump_from_fd defaults to
615 * dump_file_from_fd above when set to NULL. skip defaults
616 * to false when set to NULL. dump_from_fd will always be
617 * called with title NULL.
618 */
619int dump_files(const char *title, const char *dir,
620 bool (*skip)(const char *path),
621 int (*dump_from_fd)(const char *title, const char *path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800622 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700623 DIR *dirp;
624 struct dirent *d;
625 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800626 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700627 int fd, retval = 0;
628
629 if (title) {
630 printf("------ %s (%s) ------\n", title, dir);
631 }
Felipe Lemed402e7d2016-08-03 09:22:27 -0700632 if (is_dry_run()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700633
634 if (dir[strlen(dir) - 1] == '/') {
635 ++slash;
636 }
637 dirp = opendir(dir);
638 if (dirp == NULL) {
639 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800640 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700641 return retval;
642 }
643
644 if (!dump_from_fd) {
645 dump_from_fd = dump_file_from_fd;
646 }
647 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
648 if ((d->d_name[0] == '.')
649 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
650 || (d->d_name[1] == '\0'))) {
651 continue;
652 }
653 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
654 (d->d_type == DT_DIR) ? "/" : "");
655 if (!newpath) {
656 retval = -errno;
657 continue;
658 }
659 if (skip && (*skip)(newpath)) {
660 continue;
661 }
662 if (d->d_type == DT_DIR) {
663 int ret = dump_files(NULL, newpath, skip, dump_from_fd);
664 if (ret < 0) {
665 retval = ret;
666 }
667 continue;
668 }
669 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
670 if (fd < 0) {
671 retval = fd;
672 printf("*** %s: %s\n", newpath, strerror(errno));
673 continue;
674 }
675 (*dump_from_fd)(NULL, newpath, fd);
676 }
677 closedir(dirp);
678 if (title) {
679 printf("\n");
680 }
681 return retval;
682}
683
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800684/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
685 * it's possible to avoid issues where opening the file itself can get
686 * stuck.
687 */
688int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Lemed402e7d2016-08-03 09:22:27 -0700689 if (is_dry_run()) return 0;
690
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800691 int flags = fcntl(fd, F_GETFL);
692 if (flags == -1) {
693 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800694 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800695 return -1;
696 } else if (!(flags & O_NONBLOCK)) {
697 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800698 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800699 return -1;
700 }
701 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700702}
703
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800704bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
705 sigset_t child_mask, old_mask;
706 sigemptyset(&child_mask);
707 sigaddset(&child_mask, SIGCHLD);
708
709 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
710 printf("*** sigprocmask failed: %s\n", strerror(errno));
711 return false;
712 }
713
714 struct timespec ts;
715 ts.tv_sec = timeout_seconds;
716 ts.tv_nsec = 0;
717 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
718 int saved_errno = errno;
719 // Set the signals back the way they were.
720 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
721 printf("*** sigprocmask failed: %s\n", strerror(errno));
722 if (ret == 0) {
723 return false;
724 }
725 }
726 if (ret == -1) {
727 errno = saved_errno;
728 if (errno == EAGAIN) {
729 errno = ETIMEDOUT;
730 } else {
731 printf("*** sigtimedwait failed: %s\n", strerror(errno));
732 }
733 return false;
734 }
735
736 pid_t child_pid = waitpid(pid, status, WNOHANG);
737 if (child_pid != pid) {
738 if (child_pid != -1) {
739 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
740 } else {
741 printf("*** waitpid failed: %s\n", strerror(errno));
742 }
743 return false;
744 }
745 return true;
746}
747
Felipe Leme30dbfa12016-09-02 12:43:26 -0700748int run_command(const char* title, int timeout_seconds, const char* command, ...) {
749 std::vector<std::string> fullCommand = {command};
Felipe Leme93d705b2015-11-10 20:10:25 -0800750 size_t arg;
751 va_list ap;
752 va_start(ap, command);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700753 for (arg = 0; arg < MAX_ARGS_ARRAY_SIZE; ++arg) {
754 const char* ptr = va_arg(ap, const char*);
755 if (ptr == nullptr) {
Felipe Lemea34efb72016-03-11 09:33:32 -0800756 break;
757 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700758 fullCommand.push_back(ptr);
Felipe Lemed402e7d2016-08-03 09:22:27 -0700759 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800760 va_end(ap);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700761
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700762 return RunCommand(title, fullCommand, CommandOptions::WithTimeout(timeout_seconds).Build());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800763}
764
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700765int RunCommand(const char* title, const std::vector<std::string>& fullCommand,
Felipe Leme30dbfa12016-09-02 12:43:26 -0700766 const CommandOptions& options) {
767 if (fullCommand.empty()) {
768 MYLOGE("No arguments on command '%s'\n", title);
769 return -1;
770 }
771 DurationReporter durationReporter(title);
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800772
Felipe Leme30dbfa12016-09-02 12:43:26 -0700773 int size = fullCommand.size() + 1; // null terminated
774 if (options.RootMode() == SU_ROOT) {
775 size += 2; // "su" "root"
776 }
777
778 const char* args[size];
779
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700780 if (title) {
781 printf("------ %s (", title);
782 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700783
784 std::string commandString;
785 int i = 0;
786 if (options.RootMode() == SU_ROOT) {
787 args[0] = SU_PATH;
788 commandString += SU_PATH;
789 args[1] = "root";
790 commandString += " root ";
791 }
792 for (auto arg = fullCommand.begin(); arg < fullCommand.end(); arg++) {
793 args[i++] = arg->c_str();
794 commandString += arg->c_str();
795 if (arg != fullCommand.end() - 1) {
796 commandString += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800797 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800798 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700799 args[i] = nullptr;
800 const char* path = args[0];
801 const char* command = commandString.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700802
803 if (title) {
804 printf("%s) ------\n", command);
805 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700806
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800807 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700808
809 const std::string& loggingMessage = options.LoggingMessage();
810 if (!loggingMessage.empty()) {
811 MYLOGI(loggingMessage.c_str(), commandString.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800812 }
813
Felipe Leme30dbfa12016-09-02 12:43:26 -0700814 if (is_dry_run() && !options.Always()) {
815 update_progress(options.Timeout());
816 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700817 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800818
Felipe Leme30dbfa12016-09-02 12:43:26 -0700819 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700820
Felipe Leme30dbfa12016-09-02 12:43:26 -0700821 /* TODO: for now we're simplifying the progress calculation by using the
822 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
823 * where its weight should be much higher proportionally to its timeout.
824 * Ideally, it should use a options.EstimatedDuration() instead...*/
825 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800826
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700827 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700828 pid_t pid = fork();
829
830 /* handle error case */
831 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700832 if (!silent) printf("*** fork: %s\n", strerror(errno));
833 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700834 return pid;
835 }
836
837 /* handle child case */
838 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700839 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
840 if (!silent)
841 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700842 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700843 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800844 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700845
Felipe Leme29c39712016-04-01 10:02:00 -0700846 if (silent) {
847 // Redirect stderr to stdout
848 dup2(STDERR_FILENO, STDOUT_FILENO);
849 }
850
John Michelaue7b6cf12013-03-07 15:35:35 -0600851 /* make sure the child dies when dumpstate dies */
852 prctl(PR_SET_PDEATHSIG, SIGKILL);
853
Andres Morales2e671bb2014-08-21 12:38:22 -0700854 /* just ignore SIGPIPE, will go down with parent's */
855 struct sigaction sigact;
856 memset(&sigact, 0, sizeof(sigact));
857 sigact.sa_handler = SIG_IGN;
858 sigaction(SIGPIPE, &sigact, NULL);
859
Felipe Leme30dbfa12016-09-02 12:43:26 -0700860 execvp(path, (char**)args);
861 // execvp's result will be handled after waitpid_with_timeout() below, but
862 // if it failed, it's safer to exit dumpstate.
863 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700864 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700865 // Must call _exit (instead of exit), otherwise it will corrupt the zip
866 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700867 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700868 }
869
870 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800871 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700872 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700873 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800874 if (!ret) {
875 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700876 if (!silent)
877 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
878 (float)elapsed / NANOS_PER_SEC, pid);
879 MYLOGE("command '%s' timed out after %.3fs (killing pid %d)\n", command,
880 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800881 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700882 if (!silent)
883 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
884 (float)elapsed / NANOS_PER_SEC, pid);
885 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
886 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800887 }
888 kill(pid, SIGTERM);
889 if (!waitpid_with_timeout(pid, 5, NULL)) {
890 kill(pid, SIGKILL);
891 if (!waitpid_with_timeout(pid, 5, NULL)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700892 if (!silent)
893 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
894 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700895 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700896 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700897 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800898 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700899 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800900
901 if (WIFSIGNALED(status)) {
Felipe Leme29c39712016-04-01 10:02:00 -0700902 if (!silent) printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
903 MYLOGE("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800904 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700905 if (!silent) printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
906 MYLOGE("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800907 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800908
Felipe Leme71bbfc52015-11-23 14:14:51 -0800909 if (weight > 0) {
910 update_progress(weight);
911 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800912 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700913}
914
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700915void RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
Felipe Leme5bcce572016-09-27 09:21:08 -0700916 const CommandOptions& options, long dumpsysTimeout) {
917 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
918 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme30dbfa12016-09-02 12:43:26 -0700919 dumpsys.insert(dumpsys.end(), dumpsysArgs.begin(), dumpsysArgs.end());
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700920 RunCommand(title.c_str(), dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700921}
922
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800923bool drop_root_user() {
924 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
925 MYLOGD("drop_root_user(): already running as Shell");
926 return true;
927 }
928 /* ensure we will keep capabilities when we drop root */
929 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
930 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
931 return false;
932 }
933
934 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700935 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
936 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800937 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
938 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
939 return false;
940 }
941 if (setgid(AID_SHELL) != 0) {
942 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
943 return false;
944 }
945 if (setuid(AID_SHELL) != 0) {
946 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
947 return false;
948 }
949
950 struct __user_cap_header_struct capheader;
951 struct __user_cap_data_struct capdata[2];
952 memset(&capheader, 0, sizeof(capheader));
953 memset(&capdata, 0, sizeof(capdata));
954 capheader.version = _LINUX_CAPABILITY_VERSION_3;
955 capheader.pid = 0;
956
Wei Liuf87959e2016-08-26 14:51:42 -0700957 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
958 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
959 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
960 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800961 capdata[0].inheritable = 0;
962 capdata[1].inheritable = 0;
963
964 if (capset(&capheader, &capdata[0]) < 0) {
965 MYLOGE("capset failed: %s\n", strerror(errno));
966 return false;
967 }
968
969 return true;
970}
971
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800972void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700973 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
974
975 am.insert(am.end(), args.begin(), args.end());
976
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700977 RunCommand(nullptr, am, CommandOptions::WithTimeout(20)
Felipe Leme30dbfa12016-09-02 12:43:26 -0700978 .Log("Sending broadcast: '%s'\n")
979 .Always()
980 .DropRoot()
981 .RedirectStderr()
982 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800983}
984
Colin Crossf45fa6b2012-03-26 12:38:26 -0700985size_t num_props = 0;
986static char* props[2000];
987
988static void print_prop(const char *key, const char *name, void *user) {
989 (void) user;
990 if (num_props < sizeof(props) / sizeof(props[0])) {
991 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
992 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
993 props[num_props++] = strdup(buf);
994 }
995}
996
997static int compare_prop(const void *a, const void *b) {
998 return strcmp(*(char * const *) a, *(char * const *) b);
999}
1000
1001/* prints all the system properties */
1002void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001003 const char* title = "SYSTEM PROPERTIES";
1004 DurationReporter duration_reporter(title);
1005 printf("------ %s ------\n", title);
Felipe Lemed402e7d2016-08-03 09:22:27 -07001006 if (is_dry_run()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001007 size_t i;
1008 num_props = 0;
1009 property_list(print_prop, NULL);
1010 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1011
Colin Crossf45fa6b2012-03-26 12:38:26 -07001012 for (i = 0; i < num_props; ++i) {
1013 fputs(props[i], stdout);
1014 free(props[i]);
1015 }
1016 printf("\n");
1017}
1018
Felipe Leme2628e9e2016-04-12 16:36:51 -07001019int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001020 int s = android_get_control_socket(service);
1021 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001022 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001023 exit(1);
1024 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001025 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001026 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001027 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001028 exit(1);
1029 }
1030
1031 struct sockaddr addr;
1032 socklen_t alen = sizeof(addr);
1033 int fd = accept(s, &addr, &alen);
1034 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001035 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001036 exit(1);
1037 }
1038
Felipe Leme2628e9e2016-04-12 16:36:51 -07001039 return fd;
1040}
1041
1042/* redirect output to a service control socket */
1043void redirect_to_socket(FILE *redirect, const char *service) {
1044 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001045 fflush(redirect);
1046 dup2(fd, fileno(redirect));
1047 close(fd);
1048}
1049
Felipe Leme2628e9e2016-04-12 16:36:51 -07001050// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001051void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001052 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001053
1054 /* skip initial slash */
1055 if (chp[0] == '/')
1056 chp++;
1057
1058 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001059 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001060 while (chp && chp[0]) {
1061 chp = strchr(chp, '/');
1062 if (chp) {
1063 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001064 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001065 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001066 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001067 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001068 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001069 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001070 }
1071 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001072 *chp++ = '/';
1073 }
1074 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001075}
1076
Felipe Leme0f3fb202016-06-10 17:10:53 -07001077void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001078 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001079
Felipe Leme0f3fb202016-06-10 17:10:53 -07001080 int fd = TEMP_FAILURE_RETRY(open(path,
1081 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001082 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001083 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001084 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001085 exit(1);
1086 }
1087
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001088 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001089 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001090}
1091
Felipe Leme0f3fb202016-06-10 17:10:53 -07001092void redirect_to_file(FILE *redirect, char *path) {
1093 _redirect_to_file(redirect, path, O_TRUNC);
1094}
1095
1096void redirect_to_existing_file(FILE *redirect, char *path) {
1097 _redirect_to_file(redirect, path, O_APPEND);
1098}
1099
Jeff Brownbf7f4922012-06-07 16:40:01 -07001100static bool should_dump_native_traces(const char* path) {
1101 for (const char** p = native_processes_to_dump; *p; p++) {
1102 if (!strcmp(*p, path)) {
1103 return true;
1104 }
1105 }
1106 return false;
1107}
1108
1109/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1110const char *dump_traces() {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001111 DurationReporter duration_reporter("DUMP TRACES", nullptr);
1112 if (is_dry_run()) return nullptr;
Felipe Lemed402e7d2016-08-03 09:22:27 -07001113
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001114 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001115
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001116 std::string tracesPath = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1117 if (tracesPath.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001118
1119 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001120 std::string anrTracesPath = tracesPath + ".anr";
1121 if (rename(tracesPath.c_str(), anrTracesPath.c_str()) && errno != ENOENT) {
1122 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), anrTracesPath.c_str(), strerror(errno));
1123 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001124 }
1125
Colin Crossf45fa6b2012-03-26 12:38:26 -07001126 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001127 int fd = TEMP_FAILURE_RETRY(open(tracesPath.c_str(),
1128 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1129 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001130 if (fd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001131 MYLOGE("%s: %s\n", tracesPath.c_str(), strerror(errno));
1132 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001133 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001134 int chmod_ret = fchmod(fd, 0666);
1135 if (chmod_ret < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001136 MYLOGE("fchmod on %s failed: %s\n", tracesPath.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001137 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001138 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001139 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001140
Felipe Leme8620bb42015-11-10 11:04:45 -08001141 /* Variables below must be initialized before 'goto' statements */
1142 int dalvik_found = 0;
1143 int ifd, wfd = -1;
1144
Colin Crossf45fa6b2012-03-26 12:38:26 -07001145 /* walk /proc and kill -QUIT all Dalvik processes */
1146 DIR *proc = opendir("/proc");
1147 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001148 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001149 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001150 }
1151
1152 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001153 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001154 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001155 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001156 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001157 }
1158
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001159 wfd = inotify_add_watch(ifd, tracesPath.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001160 if (wfd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001161 MYLOGE("inotify_add_watch(%s): %s\n", tracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001162 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001163 }
1164
1165 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001166 while ((d = readdir(proc))) {
1167 int pid = atoi(d->d_name);
1168 if (pid <= 0) continue;
1169
Jeff Brownbf7f4922012-06-07 16:40:01 -07001170 char path[PATH_MAX];
1171 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001172 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001173 ssize_t len = readlink(path, data, sizeof(data) - 1);
1174 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001175 continue;
1176 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001177 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001178
Colin Cross0d6180f2014-07-16 19:00:46 -07001179 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001180 /* skip zygote -- it won't dump its stack anyway */
1181 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001182 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001183 len = read(cfd, data, sizeof(data) - 1);
1184 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001185 if (len <= 0) {
1186 continue;
1187 }
1188 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001189 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001190 continue;
1191 }
1192
1193 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001194 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001195 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001196 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001197 continue;
1198 }
1199
1200 /* wait for the writable-close notification from inotify */
1201 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001202 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001203 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001204 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001205 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001206 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001207 } else {
1208 struct inotify_event ie;
1209 read(ifd, &ie, sizeof(ie));
1210 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001211
1212 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001213 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001214 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001215 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1216 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001217 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001218 } else if (should_dump_native_traces(data)) {
1219 /* dump native process if appropriate */
1220 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001221 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001222 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001223 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001224 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001225
1226 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1227 if (timeout_failures == 3) {
1228 dprintf(fd, "too many stack dump failures, skipping...\n");
1229 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1230 dprintf(fd, "dumping failed, likely due to a timeout\n");
1231 timeout_failures++;
1232 } else {
1233 timeout_failures = 0;
1234 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001235 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1236 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001237 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001238 }
1239 }
1240
Colin Crossf45fa6b2012-03-26 12:38:26 -07001241 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001242 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001243 }
1244
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001245 static std::string dumpTracesPath = tracesPath + ".bugreport";
1246 if (rename(tracesPath.c_str(), dumpTracesPath.c_str())) {
1247 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), dumpTracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001248 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001249 }
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001250 result = dumpTracesPath.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001251
1252 /* replace the saved [ANR] traces.txt file */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001253 rename(anrTracesPath.c_str(), tracesPath.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001254
1255error_close_ifd:
1256 close(ifd);
1257error_close_fd:
1258 close(fd);
1259 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001260}
1261
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001262void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001263 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Lemed402e7d2016-08-03 09:22:27 -07001264 if (is_dry_run()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001265 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
1266 dump_file("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001267 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001268 if (!fp) {
1269 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1270 return;
1271 }
1272 char table[16];
1273 // Each line has an integer (the table number), a space, and a string (the table name). We only
1274 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1275 // Add a fixed max limit so this doesn't go awry.
1276 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001277 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1278 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001279 }
1280 fclose(fp);
1281}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001282
Felipe Leme71bbfc52015-11-23 14:14:51 -08001283// TODO: make this function thread safe if sections are generated in parallel.
1284void update_progress(int delta) {
Felipe Lemee844a9d2016-09-21 15:01:39 -07001285 if (!ds.updateProgress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001286
Felipe Lemee844a9d2016-09-21 15:01:39 -07001287 ds.progress_ += delta;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001288
1289 char key[PROPERTY_KEY_MAX];
1290 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001291
1292 // adjusts max on the fly
Felipe Lemee844a9d2016-09-21 15:01:39 -07001293 if (ds.progress_ > ds.weightTotal_) {
1294 int newTotal = ds.weightTotal_ * 1.2;
1295 MYLOGD("Adjusting total weight from %d to %d\n", ds.weightTotal_, newTotal);
1296 ds.weightTotal_ = newTotal;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001297 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
Felipe Lemee844a9d2016-09-21 15:01:39 -07001298 snprintf(value, sizeof(value), "%d", ds.weightTotal_);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001299 int status = property_set(key, value);
Felipe Lemee844a9d2016-09-21 15:01:39 -07001300 if (status != 0) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001301 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001302 key, value, status);
1303 }
1304 }
1305
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001306 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
Felipe Lemee844a9d2016-09-21 15:01:39 -07001307 snprintf(value, sizeof(value), "%d", ds.progress_);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001308
Felipe Lemee844a9d2016-09-21 15:01:39 -07001309 if (ds.progress_ % 100 == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001310 // We don't want to spam logcat, so only log multiples of 100.
Felipe Lemee844a9d2016-09-21 15:01:39 -07001311 MYLOGD("Setting progress (%s): %s/%d\n", key, value, ds.weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001312 } else {
1313 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1314 // directly for debuggging.
Felipe Lemee844a9d2016-09-21 15:01:39 -07001315 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, ds.weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001316 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001317
Felipe Lemee844a9d2016-09-21 15:01:39 -07001318 if (ds.controlSocketFd_ >= 0) {
1319 dprintf(ds.controlSocketFd_, "PROGRESS:%d/%d\n", ds.progress_, ds.weightTotal_);
1320 fsync(ds.controlSocketFd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001321 }
1322
Felipe Leme71bbfc52015-11-23 14:14:51 -08001323 int status = property_set(key, value);
1324 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001325 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001326 key, value, status);
1327 }
1328}
Felipe Lemee338bf62015-12-07 14:03:50 -08001329
Felipe Leme3634a1e2015-12-09 10:11:47 -08001330void take_screenshot(const std::string& path) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001331 RunCommand(nullptr, {"/system/bin/screencap", "-p", path},
Felipe Leme30dbfa12016-09-02 12:43:26 -07001332 CommandOptions::WithTimeout(10).Always().RedirectStderr().Build());
Felipe Lemee338bf62015-12-07 14:03:50 -08001333}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001334
Felipe Leme0c80cf02016-01-05 13:25:34 -08001335void vibrate(FILE* vibrator, int ms) {
1336 fprintf(vibrator, "%d\n", ms);
1337 fflush(vibrator);
1338}
1339
1340bool is_dir(const char* pathname) {
1341 struct stat info;
1342 if (stat(pathname, &info) == -1) {
1343 return false;
1344 }
1345 return S_ISDIR(info.st_mode);
1346}
1347
1348time_t get_mtime(int fd, time_t default_mtime) {
1349 struct stat info;
1350 if (fstat(fd, &info) == -1) {
1351 return default_mtime;
1352 }
1353 return info.st_mtime;
1354}
1355
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001356void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001357 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001358 struct hex {
1359 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001360 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001361 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1362 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1363 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1364 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1365
1366 std::string buffer;
1367 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1368 return;
1369 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001370
1371 printf("------ %s Extended CSD ------\n", ext_csd_path);
1372
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001373 if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1374 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001375 return;
1376 }
1377
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001378 int ext_csd_rev = 0;
1379 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1380 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1381 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1382 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001383 return;
1384 }
1385
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001386 static const char *ver_str[] = {
1387 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1388 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001389 printf("rev 1.%d (MMC %s)\n",
1390 ext_csd_rev,
1391 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1392 ver_str[ext_csd_rev] :
1393 "Unknown");
1394 if (ext_csd_rev < 7) {
1395 printf("\n");
1396 return;
1397 }
1398
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001399 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1400 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001401 return;
1402 }
1403
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001404 int ext_pre_eol_info = 0;
1405 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1406 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1407 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1408 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001409 return;
1410 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001411
1412 static const char *eol_str[] = {
1413 "Undefined",
1414 "Normal",
1415 "Warning (consumed 80% of reserve)",
1416 "Urgent (consumed 90% of reserve)"
1417 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001418 printf("PRE_EOL_INFO %d (MMC %s)\n",
1419 ext_pre_eol_info,
1420 eol_str[(ext_pre_eol_info < (int)
1421 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1422 ext_pre_eol_info : 0]);
1423
1424 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1425 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001426 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001427 int ext_device_life_time_est;
1428 static const char *est_str[] = {
1429 "Undefined",
1430 "0-10% of device lifetime used",
1431 "10-20% of device lifetime used",
1432 "20-30% of device lifetime used",
1433 "30-40% of device lifetime used",
1434 "40-50% of device lifetime used",
1435 "50-60% of device lifetime used",
1436 "60-70% of device lifetime used",
1437 "70-80% of device lifetime used",
1438 "80-90% of device lifetime used",
1439 "90-100% of device lifetime used",
1440 "Exceeded the maximum estimated device lifetime",
1441 };
1442
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001443 if (buffer.length() < (lifetime + sizeof(hex))) {
1444 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001445 break;
1446 }
1447
1448 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001449 sub = buffer.substr(lifetime, sizeof(hex));
1450 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1451 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001452 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001453 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1454 sizeof(hex)) + 'A',
1455 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001456 continue;
1457 }
1458 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001459 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1460 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001461 ext_device_life_time_est,
1462 est_str[(ext_device_life_time_est < (int)
1463 (sizeof(est_str) / sizeof(est_str[0]))) ?
1464 ext_device_life_time_est : 0]);
1465 }
1466
1467 printf("\n");
1468}