blob: 83fcf21a72730b6cba16d96e2d064f7233a95824 [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
Felipe Lemefd8affa2016-09-30 17:38:57 -070053#define SU_PATH "/system/xbin/su"
54
Jeff Brown1dc94e32014-09-11 14:15:27 -070055static const int64_t NANOS_PER_SEC = 1000000000;
56
Felipe Leme61884122016-06-13 09:23:30 -070057static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
58
Felipe Lemee844a9d2016-09-21 15:01:39 -070059// TODO: temporary variables and functions used during C++ refactoring
60static Dumpstate& ds = Dumpstate::GetInstance();
Felipe Leme678727a2016-09-21 17:22:11 -070061static int RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
62 const CommandOptions& options = CommandOptions::DEFAULT) {
63 return ds.RunCommand(title, fullCommand, options);
64}
Felipe Leme4c2d6632016-09-28 14:32:00 -070065static bool IsDryRun() {
66 return Dumpstate::GetInstance().IsDryRun();
67}
Felipe Lemed80e6b62016-10-03 13:08:14 -070068static void UpdateProgress(int delta) {
69 ds.UpdateProgress(delta);
70}
Felipe Lemee844a9d2016-09-21 15:01:39 -070071
Jeff Brownbf7f4922012-06-07 16:40:01 -070072/* list of native processes to include in the native dumps */
Andy Hung5c04e742016-04-13 19:35:34 -070073// This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
Jeff Brownbf7f4922012-06-07 16:40:01 -070074static const char* native_processes_to_dump[] = {
Andy Hung9609bbd2015-12-15 12:42:50 -080075 "/system/bin/audioserver",
Chien-Yu Chenf5248da2016-01-28 14:23:03 -080076 "/system/bin/cameraserver",
James Dong1fc4f802012-09-10 16:08:48 -070077 "/system/bin/drmserver",
Andy Hung5c04e742016-04-13 19:35:34 -070078 "/system/bin/mediacodec", // media.codec
79 "/system/bin/mediadrmserver",
80 "/system/bin/mediaextractor", // media.extractor
Jeff Brownbf7f4922012-06-07 16:40:01 -070081 "/system/bin/mediaserver",
82 "/system/bin/sdcard",
83 "/system/bin/surfaceflinger",
keunyoungd907b322015-10-16 15:21:43 -070084 "/system/bin/vehicle_network_service",
Jeff Brownbf7f4922012-06-07 16:40:01 -070085 NULL,
86};
87
Felipe Lemee844a9d2016-09-21 15:01:39 -070088/* Most simple commands have 10 as timeout, so 5 is a good estimate */
89static const int WEIGHT_FILE = 5;
90
Felipe Leme30dbfa12016-09-02 12:43:26 -070091CommandOptions CommandOptions::DEFAULT = CommandOptions::WithTimeout(10).Build();
92CommandOptions CommandOptions::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
93CommandOptions CommandOptions::AS_ROOT_5 = CommandOptions::WithTimeout(5).AsRoot().Build();
94CommandOptions CommandOptions::AS_ROOT_10 = CommandOptions::WithTimeout(10).AsRoot().Build();
95CommandOptions CommandOptions::AS_ROOT_20 = CommandOptions::WithTimeout(20).AsRoot().Build();
96
Felipe Lemeb0f669d2016-09-26 18:26:11 -070097CommandOptions::CommandOptionsBuilder::CommandOptionsBuilder(long timeout) : values_(timeout) {
Felipe Leme30dbfa12016-09-02 12:43:26 -070098}
99
100CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Always() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700101 values_.always_ = true;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700102 return *this;
103}
104
105CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::AsRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700106 values_.rootMode_ = SU_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700107 return *this;
108}
109
110CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::DropRoot() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700111 values_.rootMode_ = DROP_ROOT;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700112 return *this;
113}
114
115CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::RedirectStderr() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700116 values_.stdoutMode_ = REDIRECT_TO_STDERR;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700117 return *this;
118}
119
120CommandOptions::CommandOptionsBuilder& CommandOptions::CommandOptionsBuilder::Log(
121 const std::string& message) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700122 values_.loggingMessage_ = message;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700123 return *this;
124}
125
126CommandOptions CommandOptions::CommandOptionsBuilder::Build() {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700127 return CommandOptions(values_);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700128}
129
130CommandOptions::CommandOptionsValues::CommandOptionsValues(long timeout)
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700131 : timeout_(timeout),
132 always_(false),
133 rootMode_(DONT_DROP_ROOT),
134 stdoutMode_(NORMAL_STDOUT),
135 loggingMessage_("") {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700136}
137
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700138CommandOptions::CommandOptions(const CommandOptionsValues& values) : values_(values) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700139}
140
141long CommandOptions::Timeout() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700142 return values_.timeout_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700143}
144
145bool CommandOptions::Always() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700146 return values_.always_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700147}
148
149RootMode CommandOptions::RootMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700150 return values_.rootMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700151}
152
153StdoutMode CommandOptions::StdoutMode() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700154 return values_.stdoutMode_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700155}
156
157std::string CommandOptions::LoggingMessage() const {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700158 return values_.loggingMessage_;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700159}
160
161CommandOptions::CommandOptionsBuilder CommandOptions::WithTimeout(long timeout) {
162 return CommandOptions::CommandOptionsBuilder(timeout);
163}
164
Felipe Lemed80e6b62016-10-03 13:08:14 -0700165Dumpstate::Dumpstate(bool dryRun, const std::string& buildType)
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700166 : now_(time(nullptr)), dryRun_(dryRun), buildType_(buildType) {
Felipe Lemee844a9d2016-09-21 15:01:39 -0700167}
168
169Dumpstate& Dumpstate::GetInstance() {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700170 static Dumpstate sSingleton(android::base::GetBoolProperty("dumpstate.dry_run", false),
171 android::base::GetProperty("ro.build.type", "(unknown)"));
Felipe Lemee844a9d2016-09-21 15:01:39 -0700172 return sSingleton;
173}
174
Felipe Leme678727a2016-09-21 17:22:11 -0700175DurationReporter::DurationReporter(const std::string& title) : DurationReporter(title, stdout) {
176}
Felipe Leme608385d2016-02-01 10:35:38 -0800177
Felipe Leme678727a2016-09-21 17:22:11 -0700178DurationReporter::DurationReporter(const std::string& title, FILE* out) : title_(title), out_(out) {
179 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700180 started_ = DurationReporter::Nanotime();
Felipe Leme78f2c862015-12-21 09:55:22 -0800181 }
182}
183
184DurationReporter::~DurationReporter() {
Felipe Leme678727a2016-09-21 17:22:11 -0700185 if (!title_.empty()) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700186 uint64_t elapsed = DurationReporter::Nanotime() - started_;
Felipe Leme78f2c862015-12-21 09:55:22 -0800187 // Use "Yoda grammar" to make it easier to grep|sort sections.
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700188 if (out_ != nullptr) {
189 fprintf(out_, "------ %.3fs was the duration of '%s' ------\n",
Felipe Leme678727a2016-09-21 17:22:11 -0700190 (float)elapsed / NANOS_PER_SEC, title_.c_str());
Felipe Leme608385d2016-02-01 10:35:38 -0800191 } else {
Felipe Leme678727a2016-09-21 17:22:11 -0700192 MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
Felipe Leme608385d2016-02-01 10:35:38 -0800193 }
Felipe Leme78f2c862015-12-21 09:55:22 -0800194 }
195}
196
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700197uint64_t DurationReporter::DurationReporter::Nanotime() {
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800198 struct timespec ts;
199 clock_gettime(CLOCK_MONOTONIC, &ts);
Felipe Leme78f2c862015-12-21 09:55:22 -0800200 return (uint64_t) ts.tv_sec * NANOS_PER_SEC + ts.tv_nsec;
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800201}
202
Felipe Leme4c2d6632016-09-28 14:32:00 -0700203bool Dumpstate::IsDryRun() {
204 return dryRun_;
205}
206
207bool Dumpstate::IsUserBuild() {
208 return "user" == buildType_;
Felipe Lemee844a9d2016-09-21 15:01:39 -0700209}
210
Felipe Lemebbaf3c12016-10-11 14:32:25 -0700211std::string Dumpstate::GetPath(const std::string& suffix) {
212 return bugreportDir_ + "/" + baseName_ + "-" + suffix_ + suffix;
213}
214
John Spurlock5ecd4be2014-01-29 14:14:40 -0500215void for_each_userid(void (*func)(int), const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700216 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700217
John Spurlock5ecd4be2014-01-29 14:14:40 -0500218 DIR *d;
219 struct dirent *de;
220
221 if (header) printf("\n------ %s ------\n", header);
222 func(0);
223
224 if (!(d = opendir("/data/system/users"))) {
225 printf("Failed to open /data/system/users (%s)\n", strerror(errno));
226 return;
227 }
228
229 while ((de = readdir(d))) {
230 int userid;
231 if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
232 continue;
233 }
234 func(userid);
235 }
236
237 closedir(d);
238}
239
Colin Cross0c22e8b2012-11-02 15:46:56 -0700240static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700241 DIR *d;
242 struct dirent *de;
243
244 if (!(d = opendir("/proc"))) {
245 printf("Failed to open /proc (%s)\n", strerror(errno));
246 return;
247 }
248
Felipe Leme635ca312016-01-05 14:23:02 -0800249 if (header) printf("\n------ %s ------\n", header);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700250 while ((de = readdir(d))) {
251 int pid;
252 int fd;
253 char cmdpath[255];
254 char cmdline[255];
255
256 if (!(pid = atoi(de->d_name))) {
257 continue;
258 }
259
Colin Crossf45fa6b2012-03-26 12:38:26 -0700260 memset(cmdline, 0, sizeof(cmdline));
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800261
262 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
263 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
264 TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700265 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800266 if (cmdline[0]) {
267 helper(pid, cmdline, arg);
268 continue;
269 }
270 }
271
272 // if no cmdline, a kernel thread has comm
273 snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
274 if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
275 TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
276 close(fd);
277 if (cmdline[1]) {
278 cmdline[0] = '[';
279 size_t len = strcspn(cmdline, "\f\b\r\n");
280 cmdline[len] = ']';
281 cmdline[len+1] = '\0';
282 }
283 }
284 if (!cmdline[0]) {
285 strcpy(cmdline, "N/A");
Colin Crossf45fa6b2012-03-26 12:38:26 -0700286 }
Colin Cross0c22e8b2012-11-02 15:46:56 -0700287 helper(pid, cmdline, arg);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700288 }
289
290 closedir(d);
291}
292
Colin Cross0c22e8b2012-11-02 15:46:56 -0700293static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
Felipe Leme8620bb42015-11-10 11:04:45 -0800294 for_each_pid_func *func = (for_each_pid_func*) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700295 func(pid, cmdline);
296}
297
298void for_each_pid(for_each_pid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700299 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700300
Felipe Leme515eb0d2015-12-14 15:09:56 -0800301 __for_each_pid(for_each_pid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700302}
303
304static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
305 DIR *d;
306 struct dirent *de;
307 char taskpath[255];
Felipe Leme8620bb42015-11-10 11:04:45 -0800308 for_each_tid_func *func = (for_each_tid_func *) arg;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700309
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700310 snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700311
312 if (!(d = opendir(taskpath))) {
313 printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
314 return;
315 }
316
317 func(pid, pid, cmdline);
318
319 while ((de = readdir(d))) {
320 int tid;
321 int fd;
322 char commpath[255];
323 char comm[255];
324
325 if (!(tid = atoi(de->d_name))) {
326 continue;
327 }
328
329 if (tid == pid)
330 continue;
331
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700332 snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
Colin Cross1493a392012-11-07 11:25:31 -0800333 memset(comm, 0, sizeof(comm));
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700334 if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Cross0c22e8b2012-11-02 15:46:56 -0700335 strcpy(comm, "N/A");
336 } else {
337 char *c;
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800338 TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
Colin Cross0c22e8b2012-11-02 15:46:56 -0700339 close(fd);
340
341 c = strrchr(comm, '\n');
342 if (c) {
343 *c = '\0';
344 }
345 }
346 func(pid, tid, comm);
347 }
348
349 closedir(d);
350}
351
352void for_each_tid(for_each_tid_func func, const char *header) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700353 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700354
Felipe Leme8620bb42015-11-10 11:04:45 -0800355 __for_each_pid(for_each_tid_helper, header, (void *) func);
Colin Cross0c22e8b2012-11-02 15:46:56 -0700356}
357
358void show_wchan(int pid, int tid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700359 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700360
Colin Crossf45fa6b2012-03-26 12:38:26 -0700361 char path[255];
362 char buffer[255];
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800363 int fd, ret, save_errno;
Colin Cross0c22e8b2012-11-02 15:46:56 -0700364 char name_buffer[255];
Colin Crossf45fa6b2012-03-26 12:38:26 -0700365
366 memset(buffer, 0, sizeof(buffer));
367
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700368 snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -0700369 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700370 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
371 return;
372 }
373
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800374 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
375 save_errno = errno;
376 close(fd);
377
378 if (ret < 0) {
379 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
380 return;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700381 }
382
Colin Cross0c22e8b2012-11-02 15:46:56 -0700383 snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
384 pid == tid ? 0 : 3, "", name);
385
386 printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700387
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800388 return;
389}
390
391// print time in centiseconds
392static void snprcent(char *buffer, size_t len, size_t spc,
393 unsigned long long time) {
394 static long hz; // cache discovered hz
395
396 if (hz <= 0) {
397 hz = sysconf(_SC_CLK_TCK);
398 if (hz <= 0) {
399 hz = 1000;
400 }
401 }
402
403 // convert to centiseconds
404 time = (time * 100 + (hz / 2)) / hz;
405
406 char str[16];
407
408 snprintf(str, sizeof(str), " %llu.%02u",
409 time / 100, (unsigned)(time % 100));
410 size_t offset = strlen(buffer);
411 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
412 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
413}
414
415// print permille as a percent
416static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
417 char str[16];
418
419 snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
420 size_t offset = strlen(buffer);
421 snprintf(buffer + offset, (len > offset) ? len - offset : 0,
422 "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
423}
424
425void show_showtime(int pid, const char *name) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700426 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700427
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800428 char path[255];
429 char buffer[1023];
430 int fd, ret, save_errno;
431
432 memset(buffer, 0, sizeof(buffer));
433
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700434 snprintf(path, sizeof(path), "/proc/%d/stat", pid);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800435 if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
436 printf("Failed to open '%s' (%s)\n", path, strerror(errno));
437 return;
438 }
439
440 ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
441 save_errno = errno;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700442 close(fd);
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800443
444 if (ret < 0) {
445 printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
446 return;
447 }
448
449 // field 14 is utime
450 // field 15 is stime
451 // field 42 is iotime
452 unsigned long long utime = 0, stime = 0, iotime = 0;
453 if (sscanf(buffer,
Mark Salyzyn791ddd32016-02-10 07:41:12 -0800454 "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
455 "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
456 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
457 "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
Mark Salyzyn0751efa2016-02-05 15:33:17 -0800458 &utime, &stime, &iotime) != 3) {
459 return;
460 }
461
462 unsigned long long total = utime + stime;
463 if (!total) {
464 return;
465 }
466
467 unsigned permille = (iotime * 1000 + (total / 2)) / total;
468 if (permille > 1000) {
469 permille = 1000;
470 }
471
472 // try to beautify and stabilize columns at <80 characters
473 snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
474 if ((name[0] != '[') || utime) {
475 snprcent(buffer, sizeof(buffer), 57, utime);
476 }
477 snprcent(buffer, sizeof(buffer), 65, stime);
478 if ((name[0] != '[') || iotime) {
479 snprcent(buffer, sizeof(buffer), 73, iotime);
480 }
481 if (iotime) {
482 snprdec(buffer, sizeof(buffer), 79, permille);
483 }
484 puts(buffer); // adds a trailing newline
485
Colin Crossf45fa6b2012-03-26 12:38:26 -0700486 return;
487}
488
489void do_dmesg() {
Felipe Leme78f2c862015-12-21 09:55:22 -0800490 const char *title = "KERNEL LOG (dmesg)";
491 DurationReporter duration_reporter(title);
492 printf("------ %s ------\n", title);
493
Felipe Leme4c2d6632016-09-28 14:32:00 -0700494 if (IsDryRun()) return;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700495
Elliott Hughes5f87b312012-09-17 11:43:40 -0700496 /* Get size of kernel buffer */
497 int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700498 if (size <= 0) {
499 printf("Unexpected klogctl return value: %d\n\n", size);
500 return;
501 }
502 char *buf = (char *) malloc(size + 1);
503 if (buf == NULL) {
504 printf("memory allocation failed\n\n");
505 return;
506 }
507 int retval = klogctl(KLOG_READ_ALL, buf, size);
508 if (retval < 0) {
509 printf("klogctl failure\n\n");
510 free(buf);
511 return;
512 }
513 buf[retval] = '\0';
514 printf("%s\n\n", buf);
515 free(buf);
516 return;
517}
518
519void do_showmap(int pid, const char *name) {
520 char title[255];
521 char arg[255];
522
Nick Kralevichf0922cc2016-05-14 16:47:44 -0700523 snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
524 snprintf(arg, sizeof(arg), "%d", pid);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700525 RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT_10);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700526}
527
Felipe Leme678727a2016-09-21 17:22:11 -0700528static int _dump_file_from_fd(const std::string& title, const char* path, int fd) {
529 if (!title.empty()) {
530 printf("------ %s (%s", title.c_str(), path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800531
Colin Crossf45fa6b2012-03-26 12:38:26 -0700532 struct stat st;
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800533 // Only show the modification time of non-device files.
534 size_t path_len = strlen(path);
535 if ((path_len < 6 || memcmp(path, "/proc/", 6)) &&
536 (path_len < 5 || memcmp(path, "/sys/", 5)) &&
537 (path_len < 3 || memcmp(path, "/d/", 3)) &&
538 !fstat(fd, &st)) {
Colin Crossf45fa6b2012-03-26 12:38:26 -0700539 char stamp[80];
540 time_t mtime = st.st_mtime;
541 strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
542 printf(": %s", stamp);
543 }
544 printf(") ------\n");
545 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700546 if (IsDryRun()) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700547 UpdateProgress(WEIGHT_FILE);
Felipe Lemed402e7d2016-08-03 09:22:27 -0700548 close(fd);
549 return 0;
550 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700551
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 Leme0bcc7ca2016-09-13 16:45:56 -0700597 DurationReporter durationReporter(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 }
606
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700607 int fd = TEMP_FAILURE_RETRY(open(path.c_str(), O_RDONLY | O_NONBLOCK | O_CLOEXEC));
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800608 if (fd < 0) {
609 int err = errno;
Felipe Lemecef02982016-10-03 17:22:22 -0700610 if (title.empty()) {
611 printf("*** Error dumping %s: %s\n", path.c_str(), strerror(err));
612 } else {
613 printf("*** Error dumping %s (%s): %s\n", path.c_str(), title.c_str(), strerror(err));
614 }
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800615 return -1;
616 }
Felipe Leme0bcc7ca2016-09-13 16:45:56 -0700617 return _dump_file_from_fd(title, path.c_str(), fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800618}
619
Felipe Leme71a74ac2016-03-17 15:43:25 -0700620int read_file_as_long(const char *path, long int *output) {
621 int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
622 if (fd < 0) {
623 int err = errno;
624 MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
625 return -1;
626 }
627 char buffer[50];
628 ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
629 if (bytes_read == -1) {
630 MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
631 return -2;
632 }
633 if (bytes_read == 0) {
634 MYLOGE("File %s is empty\n", path);
635 return -3;
636 }
637 *output = atoi(buffer);
638 return 0;
639}
640
Mark Salyzyn326842f2015-04-30 09:49:41 -0700641/* calls skip to gate calling dump_from_fd recursively
642 * in the specified directory. dump_from_fd defaults to
643 * dump_file_from_fd above when set to NULL. skip defaults
644 * to false when set to NULL. dump_from_fd will always be
645 * called with title NULL.
646 */
Felipe Leme678727a2016-09-21 17:22:11 -0700647int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
648 int (*dump_from_fd)(const char* title, const char* path, int fd)) {
Felipe Leme78f2c862015-12-21 09:55:22 -0800649 DurationReporter duration_reporter(title);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700650 DIR *dirp;
651 struct dirent *d;
652 char *newpath = NULL;
Felipe Leme8620bb42015-11-10 11:04:45 -0800653 const char *slash = "/";
Mark Salyzyn326842f2015-04-30 09:49:41 -0700654 int fd, retval = 0;
655
Felipe Leme678727a2016-09-21 17:22:11 -0700656 if (!title.empty()) {
657 printf("------ %s (%s) ------\n", title.c_str(), dir);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700658 }
Felipe Leme4c2d6632016-09-28 14:32:00 -0700659 if (IsDryRun()) return 0;
Mark Salyzyn326842f2015-04-30 09:49:41 -0700660
661 if (dir[strlen(dir) - 1] == '/') {
662 ++slash;
663 }
664 dirp = opendir(dir);
665 if (dirp == NULL) {
666 retval = -errno;
Felipe Leme107a05f2016-03-08 15:11:15 -0800667 MYLOGE("%s: %s\n", dir, strerror(errno));
Mark Salyzyn326842f2015-04-30 09:49:41 -0700668 return retval;
669 }
670
671 if (!dump_from_fd) {
672 dump_from_fd = dump_file_from_fd;
673 }
674 for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
675 if ((d->d_name[0] == '.')
676 && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
677 || (d->d_name[1] == '\0'))) {
678 continue;
679 }
680 asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
681 (d->d_type == DT_DIR) ? "/" : "");
682 if (!newpath) {
683 retval = -errno;
684 continue;
685 }
686 if (skip && (*skip)(newpath)) {
687 continue;
688 }
689 if (d->d_type == DT_DIR) {
Felipe Leme678727a2016-09-21 17:22:11 -0700690 int ret = dump_files("", newpath, skip, dump_from_fd);
Mark Salyzyn326842f2015-04-30 09:49:41 -0700691 if (ret < 0) {
692 retval = ret;
693 }
694 continue;
695 }
696 fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
697 if (fd < 0) {
698 retval = fd;
699 printf("*** %s: %s\n", newpath, strerror(errno));
700 continue;
701 }
702 (*dump_from_fd)(NULL, newpath, fd);
703 }
704 closedir(dirp);
Felipe Leme678727a2016-09-21 17:22:11 -0700705 if (!title.empty()) {
Mark Salyzyn326842f2015-04-30 09:49:41 -0700706 printf("\n");
707 }
708 return retval;
709}
710
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800711/* fd must have been opened with the flag O_NONBLOCK. With this flag set,
712 * it's possible to avoid issues where opening the file itself can get
713 * stuck.
714 */
715int dump_file_from_fd(const char *title, const char *path, int fd) {
Felipe Leme4c2d6632016-09-28 14:32:00 -0700716 if (IsDryRun()) return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700717
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800718 int flags = fcntl(fd, F_GETFL);
719 if (flags == -1) {
720 printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800721 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800722 return -1;
723 } else if (!(flags & O_NONBLOCK)) {
724 printf("*** %s: fd must have O_NONBLOCK set.\n", path);
Christopher Ferrised24d2a2015-11-12 14:01:56 -0800725 close(fd);
Christopher Ferris54bcc5f2015-02-10 12:15:01 -0800726 return -1;
727 }
728 return _dump_file_from_fd(title, path, fd);
Jeff Brown1dc94e32014-09-11 14:15:27 -0700729}
730
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800731bool waitpid_with_timeout(pid_t pid, int timeout_seconds, int* status) {
732 sigset_t child_mask, old_mask;
733 sigemptyset(&child_mask);
734 sigaddset(&child_mask, SIGCHLD);
735
736 if (sigprocmask(SIG_BLOCK, &child_mask, &old_mask) == -1) {
737 printf("*** sigprocmask failed: %s\n", strerror(errno));
738 return false;
739 }
740
741 struct timespec ts;
742 ts.tv_sec = timeout_seconds;
743 ts.tv_nsec = 0;
744 int ret = TEMP_FAILURE_RETRY(sigtimedwait(&child_mask, NULL, &ts));
745 int saved_errno = errno;
746 // Set the signals back the way they were.
747 if (sigprocmask(SIG_SETMASK, &old_mask, NULL) == -1) {
748 printf("*** sigprocmask failed: %s\n", strerror(errno));
749 if (ret == 0) {
750 return false;
751 }
752 }
753 if (ret == -1) {
754 errno = saved_errno;
755 if (errno == EAGAIN) {
756 errno = ETIMEDOUT;
757 } else {
758 printf("*** sigtimedwait failed: %s\n", strerror(errno));
759 }
760 return false;
761 }
762
763 pid_t child_pid = waitpid(pid, status, WNOHANG);
764 if (child_pid != pid) {
765 if (child_pid != -1) {
766 printf("*** Waiting for pid %d, got pid %d instead\n", pid, child_pid);
767 } else {
768 printf("*** waitpid failed: %s\n", strerror(errno));
769 }
770 return false;
771 }
772 return true;
773}
774
Felipe Leme678727a2016-09-21 17:22:11 -0700775int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
776 const CommandOptions& options) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700777 if (fullCommand.empty()) {
Felipe Leme678727a2016-09-21 17:22:11 -0700778 MYLOGE("No arguments on command '%s'\n", title.c_str());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700779 return -1;
780 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800781
Felipe Leme30dbfa12016-09-02 12:43:26 -0700782 int size = fullCommand.size() + 1; // null terminated
Felipe Leme6ad9c062016-09-28 11:58:36 -0700783 int startingIndex = 0;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700784 if (options.RootMode() == SU_ROOT) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700785 startingIndex = 2; // "su" "root"
786 size += startingIndex;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700787 }
788
Felipe Leme6ad9c062016-09-28 11:58:36 -0700789 std::vector<const char*> args;
790 args.resize(size);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700791
792 std::string commandString;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700793 if (options.RootMode() == SU_ROOT) {
794 args[0] = SU_PATH;
795 commandString += SU_PATH;
796 args[1] = "root";
797 commandString += " root ";
798 }
Felipe Leme6ad9c062016-09-28 11:58:36 -0700799 int i = startingIndex;
800 for (auto arg = fullCommand.begin(); arg != fullCommand.end(); ++arg) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700801 args[i++] = arg->c_str();
802 commandString += arg->c_str();
803 if (arg != fullCommand.end() - 1) {
804 commandString += " ";
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800805 }
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800806 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700807 args[i] = nullptr;
808 const char* path = args[0];
809 const char* command = commandString.c_str();
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700810
Felipe Leme6ad9c062016-09-28 11:58:36 -0700811 if (options.RootMode() == SU_ROOT && ds.IsUserBuild()) {
812 printf("Skipping '%s' on user build.\n", command);
813 return 0;
814 }
815
Felipe Leme678727a2016-09-21 17:22:11 -0700816 if (!title.empty()) {
Felipe Leme6ad9c062016-09-28 11:58:36 -0700817 printf("------ %s (%s) ------\n", title.c_str(), command);
Felipe Lemec5d6cfc2016-09-26 15:57:04 -0700818 }
Felipe Leme30dbfa12016-09-02 12:43:26 -0700819
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800820 fflush(stdout);
Felipe Leme6ad9c062016-09-28 11:58:36 -0700821 DurationReporter durationReporter(title);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700822
823 const std::string& loggingMessage = options.LoggingMessage();
824 if (!loggingMessage.empty()) {
825 MYLOGI(loggingMessage.c_str(), commandString.c_str());
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800826 }
827
Felipe Leme4c2d6632016-09-28 14:32:00 -0700828 if (IsDryRun() && !options.Always()) {
829 if (!title.empty()) {
830 printf("\t(skipped on dry run)\n");
831 }
Felipe Lemed80e6b62016-10-03 13:08:14 -0700832 UpdateProgress(options.Timeout());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700833 return 0;
Felipe Lemed402e7d2016-08-03 09:22:27 -0700834 }
Felipe Leme93d705b2015-11-10 20:10:25 -0800835
Felipe Leme30dbfa12016-09-02 12:43:26 -0700836 bool silent = (options.StdoutMode() == REDIRECT_TO_STDERR);
Felipe Lemeea160d12016-03-24 11:29:44 -0700837
Felipe Leme30dbfa12016-09-02 12:43:26 -0700838 /* TODO: for now we're simplifying the progress calculation by using the
839 * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
840 * where its weight should be much higher proportionally to its timeout.
841 * Ideally, it should use a options.EstimatedDuration() instead...*/
842 int weight = options.Timeout();
Felipe Leme93d705b2015-11-10 20:10:25 -0800843
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700844 uint64_t start = DurationReporter::Nanotime();
Colin Crossf45fa6b2012-03-26 12:38:26 -0700845 pid_t pid = fork();
846
847 /* handle error case */
848 if (pid < 0) {
Felipe Leme29c39712016-04-01 10:02:00 -0700849 if (!silent) printf("*** fork: %s\n", strerror(errno));
850 MYLOGE("*** fork: %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -0700851 return pid;
852 }
853
854 /* handle child case */
855 if (pid == 0) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700856 if (options.RootMode() == DROP_ROOT && !drop_root_user()) {
857 if (!silent)
858 printf("*** failed to drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme29c39712016-04-01 10:02:00 -0700859 MYLOGE("*** could not drop root before running %s: %s\n", command, strerror(errno));
Felipe Leme73f731c2016-03-23 16:47:00 -0700860 return -1;
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800861 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700862
Felipe Leme29c39712016-04-01 10:02:00 -0700863 if (silent) {
864 // Redirect stderr to stdout
865 dup2(STDERR_FILENO, STDOUT_FILENO);
866 }
867
John Michelaue7b6cf12013-03-07 15:35:35 -0600868 /* make sure the child dies when dumpstate dies */
869 prctl(PR_SET_PDEATHSIG, SIGKILL);
870
Andres Morales2e671bb2014-08-21 12:38:22 -0700871 /* just ignore SIGPIPE, will go down with parent's */
872 struct sigaction sigact;
873 memset(&sigact, 0, sizeof(sigact));
874 sigact.sa_handler = SIG_IGN;
875 sigaction(SIGPIPE, &sigact, NULL);
876
Felipe Leme6ad9c062016-09-28 11:58:36 -0700877 execvp(path, (char**)args.data());
Felipe Leme30dbfa12016-09-02 12:43:26 -0700878 // execvp's result will be handled after waitpid_with_timeout() below, but
879 // if it failed, it's safer to exit dumpstate.
880 MYLOGD("execvp on command '%s' failed (error: %s)\n", command, strerror(errno));
Felipe Lemeec725782016-03-23 11:47:00 -0700881 fflush(stdout);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700882 // Must call _exit (instead of exit), otherwise it will corrupt the zip
883 // file.
Felipe Lemebaa85bd2016-03-29 13:29:11 -0700884 _exit(EXIT_FAILURE);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700885 }
886
887 /* handle parent case */
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800888 int status;
Felipe Leme30dbfa12016-09-02 12:43:26 -0700889 bool ret = waitpid_with_timeout(pid, options.Timeout(), &status);
Felipe Lemeb0f669d2016-09-26 18:26:11 -0700890 uint64_t elapsed = DurationReporter::Nanotime() - start;
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800891 if (!ret) {
892 if (errno == ETIMEDOUT) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700893 if (!silent)
894 printf("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
895 (float)elapsed / NANOS_PER_SEC, pid);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700896 MYLOGE("*** command '%s' timed out after %.3fs (killing pid %d)\n", command,
Felipe Leme30dbfa12016-09-02 12:43:26 -0700897 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800898 } else {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700899 if (!silent)
900 printf("*** command '%s': Error after %.4fs (killing pid %d)\n", command,
901 (float)elapsed / NANOS_PER_SEC, pid);
902 MYLOGE("command '%s': Error after %.4fs (killing pid %d)\n", command,
903 (float)elapsed / NANOS_PER_SEC, pid);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800904 }
905 kill(pid, SIGTERM);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700906 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800907 kill(pid, SIGKILL);
Felipe Lemefd8affa2016-09-30 17:38:57 -0700908 if (!waitpid_with_timeout(pid, 5, nullptr)) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700909 if (!silent)
910 printf("could not kill command '%s' (pid %d) even with SIGKILL.\n", command,
911 pid);
Felipe Leme14e034a2016-03-30 18:51:03 -0700912 MYLOGE("could not kill command '%s' (pid %d) even with SIGKILL.\n", command, pid);
Colin Crossf45fa6b2012-03-26 12:38:26 -0700913 }
Colin Crossf45fa6b2012-03-26 12:38:26 -0700914 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800915 return -1;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700916 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800917
918 if (WIFSIGNALED(status)) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700919 if (!silent)
920 printf("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
921 MYLOGE("*** command '%s' failed: killed by signal %d\n", command, WTERMSIG(status));
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800922 } else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
Felipe Lemefd8affa2016-09-30 17:38:57 -0700923 status = WEXITSTATUS(status);
924 if (!silent) printf("*** command '%s' failed: exit code %d\n", command, status);
925 MYLOGE("*** command '%s' failed: exit code %d\n", command, status);
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800926 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800927
Felipe Leme71bbfc52015-11-23 14:14:51 -0800928 if (weight > 0) {
Felipe Lemed80e6b62016-10-03 13:08:14 -0700929 UpdateProgress(weight);
Felipe Leme71bbfc52015-11-23 14:14:51 -0800930 }
Christopher Ferris1a9a3382015-01-30 11:00:52 -0800931 return status;
Colin Crossf45fa6b2012-03-26 12:38:26 -0700932}
933
Felipe Leme678727a2016-09-21 17:22:11 -0700934void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsysArgs,
935 const CommandOptions& options, long dumpsysTimeout) {
Felipe Leme5bcce572016-09-27 09:21:08 -0700936 long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
937 std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
Felipe Leme30dbfa12016-09-02 12:43:26 -0700938 dumpsys.insert(dumpsys.end(), dumpsysArgs.begin(), dumpsysArgs.end());
Felipe Leme678727a2016-09-21 17:22:11 -0700939 RunCommand(title, dumpsys, options);
Felipe Leme30dbfa12016-09-02 12:43:26 -0700940}
941
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800942bool drop_root_user() {
943 if (getgid() == AID_SHELL && getuid() == AID_SHELL) {
Felipe Leme26c41572016-10-06 14:34:43 -0700944 MYLOGD("drop_root_user(): already running as Shell\n");
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800945 return true;
946 }
947 /* ensure we will keep capabilities when we drop root */
948 if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
949 MYLOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
950 return false;
951 }
952
953 gid_t groups[] = { AID_LOG, AID_SDCARD_R, AID_SDCARD_RW,
Ajay Panickerd886ec42016-09-14 12:26:46 -0700954 AID_MOUNT, AID_INET, AID_NET_BW_STATS, AID_READPROC, AID_WAKELOCK,
955 AID_BLUETOOTH };
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800956 if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
957 MYLOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
958 return false;
959 }
960 if (setgid(AID_SHELL) != 0) {
961 MYLOGE("Unable to setgid, aborting: %s\n", strerror(errno));
962 return false;
963 }
964 if (setuid(AID_SHELL) != 0) {
965 MYLOGE("Unable to setuid, aborting: %s\n", strerror(errno));
966 return false;
967 }
968
969 struct __user_cap_header_struct capheader;
970 struct __user_cap_data_struct capdata[2];
971 memset(&capheader, 0, sizeof(capheader));
972 memset(&capdata, 0, sizeof(capdata));
973 capheader.version = _LINUX_CAPABILITY_VERSION_3;
974 capheader.pid = 0;
975
Wei Liuf87959e2016-08-26 14:51:42 -0700976 capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted =
977 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
978 capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective =
979 (CAP_TO_MASK(CAP_SYSLOG) | CAP_TO_MASK(CAP_BLOCK_SUSPEND));
Felipe Lemecf6a8b42016-03-11 10:38:19 -0800980 capdata[0].inheritable = 0;
981 capdata[1].inheritable = 0;
982
983 if (capset(&capheader, &capdata[0]) < 0) {
984 MYLOGE("capset failed: %s\n", strerror(errno));
985 return false;
986 }
987
988 return true;
989}
990
Felipe Leme36b3f6f2015-11-19 15:41:04 -0800991void send_broadcast(const std::string& action, const std::vector<std::string>& args) {
Felipe Leme30dbfa12016-09-02 12:43:26 -0700992 std::vector<std::string> am = {"/system/bin/am", "broadcast", "--user", "0", "-a", action};
993
994 am.insert(am.end(), args.begin(), args.end());
995
Felipe Leme678727a2016-09-21 17:22:11 -0700996 RunCommand("", am, CommandOptions::WithTimeout(20)
997 .Log("Sending broadcast: '%s'\n")
998 .Always()
999 .DropRoot()
1000 .RedirectStderr()
1001 .Build());
Felipe Leme36b3f6f2015-11-19 15:41:04 -08001002}
1003
Colin Crossf45fa6b2012-03-26 12:38:26 -07001004size_t num_props = 0;
1005static char* props[2000];
1006
1007static void print_prop(const char *key, const char *name, void *user) {
1008 (void) user;
1009 if (num_props < sizeof(props) / sizeof(props[0])) {
1010 char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
1011 snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
1012 props[num_props++] = strdup(buf);
1013 }
1014}
1015
1016static int compare_prop(const void *a, const void *b) {
1017 return strcmp(*(char * const *) a, *(char * const *) b);
1018}
1019
1020/* prints all the system properties */
1021void print_properties() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001022 const char* title = "SYSTEM PROPERTIES";
1023 DurationReporter duration_reporter(title);
1024 printf("------ %s ------\n", title);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001025 if (IsDryRun()) return;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001026 size_t i;
1027 num_props = 0;
1028 property_list(print_prop, NULL);
1029 qsort(&props, num_props, sizeof(props[0]), compare_prop);
1030
Colin Crossf45fa6b2012-03-26 12:38:26 -07001031 for (i = 0; i < num_props; ++i) {
1032 fputs(props[i], stdout);
1033 free(props[i]);
1034 }
1035 printf("\n");
1036}
1037
Felipe Leme2628e9e2016-04-12 16:36:51 -07001038int open_socket(const char *service) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001039 int s = android_get_control_socket(service);
1040 if (s < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001041 MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001042 exit(1);
1043 }
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001044 fcntl(s, F_SETFD, FD_CLOEXEC);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001045 if (listen(s, 4) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001046 MYLOGE("listen(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001047 exit(1);
1048 }
1049
1050 struct sockaddr addr;
1051 socklen_t alen = sizeof(addr);
1052 int fd = accept(s, &addr, &alen);
1053 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001054 MYLOGE("accept(control socket): %s\n", strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001055 exit(1);
1056 }
1057
Felipe Leme2628e9e2016-04-12 16:36:51 -07001058 return fd;
1059}
1060
1061/* redirect output to a service control socket */
1062void redirect_to_socket(FILE *redirect, const char *service) {
1063 int fd = open_socket(service);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001064 fflush(redirect);
1065 dup2(fd, fileno(redirect));
1066 close(fd);
1067}
1068
Felipe Leme2628e9e2016-04-12 16:36:51 -07001069// TODO: should call is_valid_output_file and/or be merged into it.
Felipe Leme111b9d02016-02-03 09:28:24 -08001070void create_parent_dirs(const char *path) {
Srinath Sridharanfdf52d32016-02-01 15:50:22 -08001071 char *chp = const_cast<char *> (path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001072
1073 /* skip initial slash */
1074 if (chp[0] == '/')
1075 chp++;
1076
1077 /* create leading directories, if necessary */
Felipe Leme111b9d02016-02-03 09:28:24 -08001078 struct stat dir_stat;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001079 while (chp && chp[0]) {
1080 chp = strchr(chp, '/');
1081 if (chp) {
1082 *chp = 0;
Felipe Leme111b9d02016-02-03 09:28:24 -08001083 if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001084 MYLOGI("Creating directory %s\n", path);
Felipe Leme111b9d02016-02-03 09:28:24 -08001085 if (mkdir(path, 0770)) { /* drwxrwx--- */
Felipe Lemecbce55d2016-02-08 09:53:18 -08001086 MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001087 } else if (chown(path, AID_SHELL, AID_SHELL)) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001088 MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
Felipe Leme111b9d02016-02-03 09:28:24 -08001089 }
1090 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001091 *chp++ = '/';
1092 }
1093 }
Felipe Leme111b9d02016-02-03 09:28:24 -08001094}
1095
Felipe Leme0f3fb202016-06-10 17:10:53 -07001096void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
Felipe Leme111b9d02016-02-03 09:28:24 -08001097 create_parent_dirs(path);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001098
Felipe Leme0f3fb202016-06-10 17:10:53 -07001099 int fd = TEMP_FAILURE_RETRY(open(path,
1100 O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001101 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001102 if (fd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001103 MYLOGE("%s: %s\n", path, strerror(errno));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001104 exit(1);
1105 }
1106
Christopher Ferrisff4a4dc2015-02-09 16:24:47 -08001107 TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
Colin Crossf45fa6b2012-03-26 12:38:26 -07001108 close(fd);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001109}
1110
Felipe Leme0f3fb202016-06-10 17:10:53 -07001111void redirect_to_file(FILE *redirect, char *path) {
1112 _redirect_to_file(redirect, path, O_TRUNC);
1113}
1114
1115void redirect_to_existing_file(FILE *redirect, char *path) {
1116 _redirect_to_file(redirect, path, O_APPEND);
1117}
1118
Jeff Brownbf7f4922012-06-07 16:40:01 -07001119static bool should_dump_native_traces(const char* path) {
1120 for (const char** p = native_processes_to_dump; *p; p++) {
1121 if (!strcmp(*p, path)) {
1122 return true;
1123 }
1124 }
1125 return false;
1126}
1127
1128/* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
1129const char *dump_traces() {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001130 DurationReporter duration_reporter("DUMP TRACES", nullptr);
Felipe Leme4c2d6632016-09-28 14:32:00 -07001131 if (IsDryRun()) return nullptr;
Felipe Lemed402e7d2016-08-03 09:22:27 -07001132
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001133 const char* result = nullptr;
Jeff Brownbf7f4922012-06-07 16:40:01 -07001134
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001135 std::string tracesPath = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
1136 if (tracesPath.empty()) return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001137
1138 /* move the old traces.txt (if any) out of the way temporarily */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001139 std::string anrTracesPath = tracesPath + ".anr";
1140 if (rename(tracesPath.c_str(), anrTracesPath.c_str()) && errno != ENOENT) {
1141 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), anrTracesPath.c_str(), strerror(errno));
1142 return nullptr; // Can't rename old traces.txt -- no permission? -- leave it alone instead
Colin Crossf45fa6b2012-03-26 12:38:26 -07001143 }
1144
Colin Crossf45fa6b2012-03-26 12:38:26 -07001145 /* create a new, empty traces.txt file to receive stack dumps */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001146 int fd = TEMP_FAILURE_RETRY(open(tracesPath.c_str(),
1147 O_CREAT | O_WRONLY | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
1148 0666)); /* -rw-rw-rw- */
Colin Crossf45fa6b2012-03-26 12:38:26 -07001149 if (fd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001150 MYLOGE("%s: %s\n", tracesPath.c_str(), strerror(errno));
1151 return nullptr;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001152 }
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001153 int chmod_ret = fchmod(fd, 0666);
1154 if (chmod_ret < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001155 MYLOGE("fchmod on %s failed: %s\n", tracesPath.c_str(), strerror(errno));
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001156 close(fd);
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001157 return nullptr;
Nick Kralevichc7f1fe22012-04-06 09:31:28 -07001158 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001159
Felipe Leme8620bb42015-11-10 11:04:45 -08001160 /* Variables below must be initialized before 'goto' statements */
1161 int dalvik_found = 0;
1162 int ifd, wfd = -1;
1163
Colin Crossf45fa6b2012-03-26 12:38:26 -07001164 /* walk /proc and kill -QUIT all Dalvik processes */
1165 DIR *proc = opendir("/proc");
1166 if (proc == NULL) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001167 MYLOGE("/proc: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001168 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001169 }
1170
1171 /* use inotify to find when processes are done dumping */
Felipe Leme8620bb42015-11-10 11:04:45 -08001172 ifd = inotify_init();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001173 if (ifd < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001174 MYLOGE("inotify_init: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001175 goto error_close_fd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001176 }
1177
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001178 wfd = inotify_add_watch(ifd, tracesPath.c_str(), IN_CLOSE_WRITE);
Colin Crossf45fa6b2012-03-26 12:38:26 -07001179 if (wfd < 0) {
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001180 MYLOGE("inotify_add_watch(%s): %s\n", tracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001181 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001182 }
1183
1184 struct dirent *d;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001185 while ((d = readdir(proc))) {
1186 int pid = atoi(d->d_name);
1187 if (pid <= 0) continue;
1188
Jeff Brownbf7f4922012-06-07 16:40:01 -07001189 char path[PATH_MAX];
1190 char data[PATH_MAX];
Colin Crossf45fa6b2012-03-26 12:38:26 -07001191 snprintf(path, sizeof(path), "/proc/%d/exe", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001192 ssize_t len = readlink(path, data, sizeof(data) - 1);
1193 if (len <= 0) {
Colin Crossf45fa6b2012-03-26 12:38:26 -07001194 continue;
1195 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001196 data[len] = '\0';
Colin Crossf45fa6b2012-03-26 12:38:26 -07001197
Colin Cross0d6180f2014-07-16 19:00:46 -07001198 if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001199 /* skip zygote -- it won't dump its stack anyway */
1200 snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001201 int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001202 len = read(cfd, data, sizeof(data) - 1);
1203 close(cfd);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001204 if (len <= 0) {
1205 continue;
1206 }
1207 data[len] = '\0';
Colin Cross0d6180f2014-07-16 19:00:46 -07001208 if (!strncmp(data, "zygote", strlen("zygote"))) {
Jeff Brownbf7f4922012-06-07 16:40:01 -07001209 continue;
1210 }
1211
1212 ++dalvik_found;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001213 uint64_t start = DurationReporter::Nanotime();
Jeff Brownbf7f4922012-06-07 16:40:01 -07001214 if (kill(pid, SIGQUIT)) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001215 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001216 continue;
1217 }
1218
1219 /* wait for the writable-close notification from inotify */
1220 struct pollfd pfd = { ifd, POLLIN, 0 };
Felipe Leme61884122016-06-13 09:23:30 -07001221 int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001222 if (ret < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001223 MYLOGE("poll: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001224 } else if (ret == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001225 MYLOGE("warning: timed out dumping pid %d\n", pid);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001226 } else {
1227 struct inotify_event ie;
1228 read(ifd, &ie, sizeof(ie));
1229 }
Jeff Brown1dc94e32014-09-11 14:15:27 -07001230
1231 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001232 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brown1dc94e32014-09-11 14:15:27 -07001233 } else {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001234 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
1235 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brown1dc94e32014-09-11 14:15:27 -07001236 }
Jeff Brownbf7f4922012-06-07 16:40:01 -07001237 } else if (should_dump_native_traces(data)) {
1238 /* dump native process if appropriate */
1239 if (lseek(fd, 0, SEEK_END) < 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001240 MYLOGE("lseek: %s\n", strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001241 } else {
Christopher Ferris31ef8552015-01-14 13:23:30 -08001242 static uint16_t timeout_failures = 0;
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001243 uint64_t start = DurationReporter::Nanotime();
Christopher Ferris31ef8552015-01-14 13:23:30 -08001244
1245 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
1246 if (timeout_failures == 3) {
1247 dprintf(fd, "too many stack dump failures, skipping...\n");
1248 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
1249 dprintf(fd, "dumping failed, likely due to a timeout\n");
1250 timeout_failures++;
1251 } else {
1252 timeout_failures = 0;
1253 }
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001254 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
1255 (float)(DurationReporter::Nanotime() - start) / NANOS_PER_SEC);
Jeff Brownbf7f4922012-06-07 16:40:01 -07001256 }
Colin Crossf45fa6b2012-03-26 12:38:26 -07001257 }
1258 }
1259
Colin Crossf45fa6b2012-03-26 12:38:26 -07001260 if (dalvik_found == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001261 MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
Colin Crossf45fa6b2012-03-26 12:38:26 -07001262 }
1263
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001264 static std::string dumpTracesPath = tracesPath + ".bugreport";
1265 if (rename(tracesPath.c_str(), dumpTracesPath.c_str())) {
1266 MYLOGE("rename(%s, %s): %s\n", tracesPath.c_str(), dumpTracesPath.c_str(), strerror(errno));
Jeff Brownbf7f4922012-06-07 16:40:01 -07001267 goto error_close_ifd;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001268 }
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001269 result = dumpTracesPath.c_str();
Colin Crossf45fa6b2012-03-26 12:38:26 -07001270
1271 /* replace the saved [ANR] traces.txt file */
Felipe Leme96c2bbb2016-09-26 09:21:21 -07001272 rename(anrTracesPath.c_str(), tracesPath.c_str());
Jeff Brownbf7f4922012-06-07 16:40:01 -07001273
1274error_close_ifd:
1275 close(ifd);
1276error_close_fd:
1277 close(fd);
1278 return result;
Colin Crossf45fa6b2012-03-26 12:38:26 -07001279}
1280
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001281void dump_route_tables() {
Felipe Leme78f2c862015-12-21 09:55:22 -08001282 DurationReporter duration_reporter("DUMP ROUTE TABLES");
Felipe Leme4c2d6632016-09-28 14:32:00 -07001283 if (IsDryRun()) return;
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001284 const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
Felipe Lemec7fe8fe2016-09-21 18:13:20 -07001285 ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
Nick Kralevichcd67e9f2015-03-19 11:30:59 -07001286 FILE* fp = fopen(RT_TABLES_PATH, "re");
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001287 if (!fp) {
1288 printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
1289 return;
1290 }
1291 char table[16];
1292 // Each line has an integer (the table number), a space, and a string (the table name). We only
1293 // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
1294 // Add a fixed max limit so this doesn't go awry.
1295 for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
Felipe Lemeb0f669d2016-09-26 18:26:11 -07001296 RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
1297 RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
Sreeram Ramachandran2b3bba32014-07-08 15:40:55 -07001298 }
1299 fclose(fp);
1300}
Felipe Leme71bbfc52015-11-23 14:14:51 -08001301
Felipe Leme71bbfc52015-11-23 14:14:51 -08001302// TODO: make this function thread safe if sections are generated in parallel.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001303void Dumpstate::UpdateProgress(int delta) {
1304 if (!updateProgress_) return;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001305
Felipe Lemed80e6b62016-10-03 13:08:14 -07001306 progress_ += delta;
Felipe Leme71bbfc52015-11-23 14:14:51 -08001307
1308 char key[PROPERTY_KEY_MAX];
1309 char value[PROPERTY_VALUE_MAX];
Felipe Lemead5f6c42015-11-30 14:26:46 -08001310
1311 // adjusts max on the fly
Felipe Lemed80e6b62016-10-03 13:08:14 -07001312 if (progress_ > weightTotal_) {
1313 int newTotal = weightTotal_ * 1.2;
1314 MYLOGD("Adjusting total weight from %d to %d\n", weightTotal_, newTotal);
1315 weightTotal_ = newTotal;
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001316 snprintf(key, sizeof(key), "dumpstate.%d.max", getpid());
Felipe Lemed80e6b62016-10-03 13:08:14 -07001317 snprintf(value, sizeof(value), "%d", weightTotal_);
Felipe Lemead5f6c42015-11-30 14:26:46 -08001318 int status = property_set(key, value);
Felipe Lemee844a9d2016-09-21 15:01:39 -07001319 if (status != 0) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001320 MYLOGE("Could not update max weight by setting system property %s to %s: %d\n",
Felipe Lemead5f6c42015-11-30 14:26:46 -08001321 key, value, status);
1322 }
1323 }
1324
Nick Kralevichf0922cc2016-05-14 16:47:44 -07001325 snprintf(key, sizeof(key), "dumpstate.%d.progress", getpid());
Felipe Lemed80e6b62016-10-03 13:08:14 -07001326 snprintf(value, sizeof(value), "%d", progress_);
Felipe Leme71bbfc52015-11-23 14:14:51 -08001327
Felipe Lemed80e6b62016-10-03 13:08:14 -07001328 if (progress_ % 100 == 0) {
Felipe Leme107a05f2016-03-08 15:11:15 -08001329 // We don't want to spam logcat, so only log multiples of 100.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001330 MYLOGD("Setting progress (%s): %s/%d\n", key, value, weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001331 } else {
1332 // stderr is ignored on normal invocations, but useful when calling /system/bin/dumpstate
1333 // directly for debuggging.
Felipe Lemed80e6b62016-10-03 13:08:14 -07001334 fprintf(stderr, "Setting progress (%s): %s/%d\n", key, value, weightTotal_);
Felipe Leme107a05f2016-03-08 15:11:15 -08001335 }
Felipe Leme71bbfc52015-11-23 14:14:51 -08001336
Felipe Lemed80e6b62016-10-03 13:08:14 -07001337 if (controlSocketFd_ >= 0) {
1338 dprintf(controlSocketFd_, "PROGRESS:%d/%d\n", progress_, weightTotal_);
1339 fsync(controlSocketFd_);
Felipe Leme02b7e002016-07-22 12:03:20 -07001340 }
1341
Felipe Leme71bbfc52015-11-23 14:14:51 -08001342 int status = property_set(key, value);
1343 if (status) {
Felipe Lemecbce55d2016-02-08 09:53:18 -08001344 MYLOGE("Could not update progress by setting system property %s to %s: %d\n",
Felipe Leme71bbfc52015-11-23 14:14:51 -08001345 key, value, status);
1346 }
1347}
Felipe Lemee338bf62015-12-07 14:03:50 -08001348
Felipe Lemebbaf3c12016-10-11 14:32:25 -07001349void Dumpstate::TakeScreenshot(const std::string& path) {
1350 const std::string& realPath = path.empty() ? screenshotPath_ : path;
1351 int status =
1352 RunCommand("", {"/system/bin/screencap", "-p", realPath},
1353 CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1354 if (status == 0) {
1355 MYLOGD("Screenshot saved on %s\n", realPath.c_str());
1356 } else {
1357 MYLOGE("Failed to take screenshot on %s\n", realPath.c_str());
1358 }
Felipe Lemee338bf62015-12-07 14:03:50 -08001359}
Mark Salyzynf55d4022015-12-11 07:32:31 -08001360
Felipe Leme0c80cf02016-01-05 13:25:34 -08001361void vibrate(FILE* vibrator, int ms) {
1362 fprintf(vibrator, "%d\n", ms);
1363 fflush(vibrator);
1364}
1365
1366bool is_dir(const char* pathname) {
1367 struct stat info;
1368 if (stat(pathname, &info) == -1) {
1369 return false;
1370 }
1371 return S_ISDIR(info.st_mode);
1372}
1373
1374time_t get_mtime(int fd, time_t default_mtime) {
1375 struct stat info;
1376 if (fstat(fd, &info) == -1) {
1377 return default_mtime;
1378 }
1379 return info.st_mtime;
1380}
1381
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001382void dump_emmc_ecsd(const char *ext_csd_path) {
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001383 // List of interesting offsets
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001384 struct hex {
1385 char str[2];
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001386 };
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001387 static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1388 static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1389 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1390 static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1391
1392 std::string buffer;
1393 if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1394 return;
1395 }
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001396
1397 printf("------ %s Extended CSD ------\n", ext_csd_path);
1398
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001399 if (buffer.length() < (EXT_CSD_REV + 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_csd_rev = 0;
1405 std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1406 if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1407 printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n",
1408 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001409 return;
1410 }
1411
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001412 static const char *ver_str[] = {
1413 "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1414 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001415 printf("rev 1.%d (MMC %s)\n",
1416 ext_csd_rev,
1417 (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ?
1418 ver_str[ext_csd_rev] :
1419 "Unknown");
1420 if (ext_csd_rev < 7) {
1421 printf("\n");
1422 return;
1423 }
1424
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001425 if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1426 printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001427 return;
1428 }
1429
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001430 int ext_pre_eol_info = 0;
1431 sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1432 if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1433 printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n",
1434 ext_csd_path, sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001435 return;
1436 }
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001437
1438 static const char *eol_str[] = {
1439 "Undefined",
1440 "Normal",
1441 "Warning (consumed 80% of reserve)",
1442 "Urgent (consumed 90% of reserve)"
1443 };
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001444 printf("PRE_EOL_INFO %d (MMC %s)\n",
1445 ext_pre_eol_info,
1446 eol_str[(ext_pre_eol_info < (int)
1447 (sizeof(eol_str) / sizeof(eol_str[0]))) ?
1448 ext_pre_eol_info : 0]);
1449
1450 for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1451 lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001452 lifetime += sizeof(hex)) {
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001453 int ext_device_life_time_est;
1454 static const char *est_str[] = {
1455 "Undefined",
1456 "0-10% of device lifetime used",
1457 "10-20% of device lifetime used",
1458 "20-30% of device lifetime used",
1459 "30-40% of device lifetime used",
1460 "40-50% of device lifetime used",
1461 "50-60% of device lifetime used",
1462 "60-70% of device lifetime used",
1463 "70-80% of device lifetime used",
1464 "80-90% of device lifetime used",
1465 "90-100% of device lifetime used",
1466 "Exceeded the maximum estimated device lifetime",
1467 };
1468
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001469 if (buffer.length() < (lifetime + sizeof(hex))) {
1470 printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001471 break;
1472 }
1473
1474 ext_device_life_time_est = 0;
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001475 sub = buffer.substr(lifetime, sizeof(hex));
1476 if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1477 printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n",
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001478 ext_csd_path,
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001479 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1480 sizeof(hex)) + 'A',
1481 sub.c_str());
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001482 continue;
1483 }
1484 printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
Mark Salyzyn290f4b92016-05-16 08:33:59 -07001485 (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) /
1486 sizeof(hex)) + 'A',
Mark Salyzyn8c8130e2015-12-09 11:21:28 -08001487 ext_device_life_time_est,
1488 est_str[(ext_device_life_time_est < (int)
1489 (sizeof(est_str) / sizeof(est_str[0]))) ?
1490 ext_device_life_time_est : 0]);
1491 }
1492
1493 printf("\n");
1494}