OSDN Git Service

4655d33763c498c3b704ef0db52255998d4ceb9d
[android-x86/frameworks-native.git] / cmds / dumpstate / utils.cpp
1 /*
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 #define LOG_TAG "dumpstate"
18
19 #include "dumpstate.h"
20
21 #include <dirent.h>
22 #include <fcntl.h>
23 #include <libgen.h>
24 #include <math.h>
25 #include <poll.h>
26 #include <signal.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/capability.h>
32 #include <sys/inotify.h>
33 #include <sys/klog.h>
34 #include <sys/prctl.h>
35 #include <sys/stat.h>
36 #include <sys/time.h>
37 #include <sys/wait.h>
38 #include <time.h>
39 #include <unistd.h>
40
41 #include <string>
42 #include <vector>
43
44 #include <android-base/file.h>
45 #include <android-base/properties.h>
46 #include <android-base/stringprintf.h>
47 #include <android-base/strings.h>
48 #include <cutils/properties.h>
49 #include <cutils/sockets.h>
50 #include <debuggerd/client.h>
51 #include <log/log.h>
52 #include <private/android_filesystem_config.h>
53
54 #include "DumpstateInternal.h"
55
56 // TODO: remove once moved to namespace
57 using android::os::dumpstate::CommandOptions;
58 using android::os::dumpstate::DumpFileToFd;
59 using android::os::dumpstate::PropertiesHelper;
60
61 static const int TRACE_DUMP_TIMEOUT_MS = 10000; // 10 seconds
62
63 /* Most simple commands have 10 as timeout, so 5 is a good estimate */
64 static const int32_t WEIGHT_FILE = 5;
65
66 // TODO: temporary variables and functions used during C++ refactoring
67 static Dumpstate& ds = Dumpstate::GetInstance();
68 static int RunCommand(const std::string& title, const std::vector<std::string>& full_command,
69                       const CommandOptions& options = CommandOptions::DEFAULT) {
70     return ds.RunCommand(title, full_command, options);
71 }
72
73 /* list of native processes to include in the native dumps */
74 // This matches the /proc/pid/exe link instead of /proc/pid/cmdline.
75 static const char* native_processes_to_dump[] = {
76         "/system/bin/audioserver",
77         "/system/bin/cameraserver",
78         "/system/bin/drmserver",
79         "/system/bin/mediacodec",     // media.codec
80         "/system/bin/mediadrmserver",
81         "/system/bin/mediaextractor", // media.extractor
82         "/system/bin/mediaserver",
83         "/system/bin/sdcard",
84         "/system/bin/surfaceflinger",
85         "/system/bin/vehicle_network_service",
86         NULL,
87 };
88
89 // Reasonable value for max stats.
90 static const int STATS_MAX_N_RUNS = 1000;
91 static const long STATS_MAX_AVERAGE = 100000;
92
93 CommandOptions Dumpstate::DEFAULT_DUMPSYS = CommandOptions::WithTimeout(30).Build();
94
95 Dumpstate::Dumpstate(const std::string& version)
96     : pid_(getpid()), version_(version), now_(time(nullptr)) {
97 }
98
99 Dumpstate& Dumpstate::GetInstance() {
100     static Dumpstate singleton_(android::base::GetProperty("dumpstate.version", VERSION_CURRENT));
101     return singleton_;
102 }
103
104 DurationReporter::DurationReporter(const std::string& title, bool log_only)
105     : title_(title), log_only_(log_only) {
106     if (!title_.empty()) {
107         started_ = Nanotime();
108     }
109 }
110
111 DurationReporter::~DurationReporter() {
112     if (!title_.empty()) {
113         uint64_t elapsed = Nanotime() - started_;
114         if (log_only_) {
115             MYLOGD("Duration of '%s': %.3fs\n", title_.c_str(), (float)elapsed / NANOS_PER_SEC);
116         } else {
117             // Use "Yoda grammar" to make it easier to grep|sort sections.
118             printf("------ %.3fs was the duration of '%s' ------\n", (float)elapsed / NANOS_PER_SEC,
119                    title_.c_str());
120         }
121     }
122 }
123
124 const int32_t Progress::kDefaultMax = 5000;
125
126 Progress::Progress(const std::string& path) : Progress(Progress::kDefaultMax, 1.1, path) {
127 }
128
129 Progress::Progress(int32_t initial_max, int32_t progress, float growth_factor)
130     : Progress(initial_max, growth_factor, "") {
131     progress_ = progress;
132 }
133
134 Progress::Progress(int32_t initial_max, float growth_factor, const std::string& path)
135     : initial_max_(initial_max),
136       progress_(0),
137       max_(initial_max),
138       growth_factor_(growth_factor),
139       n_runs_(0),
140       average_max_(0),
141       path_(path) {
142     if (!path_.empty()) {
143         Load();
144     }
145 }
146
147 void Progress::Load() {
148     MYLOGD("Loading stats from %s\n", path_.c_str());
149     std::string content;
150     if (!android::base::ReadFileToString(path_, &content)) {
151         MYLOGI("Could not read stats from %s; using max of %d\n", path_.c_str(), max_);
152         return;
153     }
154     if (content.empty()) {
155         MYLOGE("No stats (empty file) on %s; using max of %d\n", path_.c_str(), max_);
156         return;
157     }
158     std::vector<std::string> lines = android::base::Split(content, "\n");
159
160     if (lines.size() < 1) {
161         MYLOGE("Invalid stats on file %s: not enough lines (%d). Using max of %d\n", path_.c_str(),
162                (int)lines.size(), max_);
163         return;
164     }
165     char* ptr;
166     n_runs_ = strtol(lines[0].c_str(), &ptr, 10);
167     average_max_ = strtol(ptr, nullptr, 10);
168     if (n_runs_ <= 0 || average_max_ <= 0 || n_runs_ > STATS_MAX_N_RUNS ||
169         average_max_ > STATS_MAX_AVERAGE) {
170         MYLOGE("Invalid stats line on file %s: %s\n", path_.c_str(), lines[0].c_str());
171         initial_max_ = Progress::kDefaultMax;
172     } else {
173         initial_max_ = average_max_;
174     }
175     max_ = initial_max_;
176
177     MYLOGI("Average max progress: %d in %d runs; estimated max: %d\n", average_max_, n_runs_, max_);
178 }
179
180 void Progress::Save() {
181     int32_t total = n_runs_ * average_max_ + progress_;
182     int32_t runs = n_runs_ + 1;
183     int32_t average = floor(((float)total) / runs);
184     MYLOGI("Saving stats (total=%d, runs=%d, average=%d) on %s\n", total, runs, average,
185            path_.c_str());
186     if (path_.empty()) {
187         return;
188     }
189
190     std::string content = android::base::StringPrintf("%d %d\n", runs, average);
191     if (!android::base::WriteStringToFile(content, path_)) {
192         MYLOGE("Could not save stats on %s\n", path_.c_str());
193     }
194 }
195
196 int32_t Progress::Get() const {
197     return progress_;
198 }
199
200 bool Progress::Inc(int32_t delta) {
201     bool changed = false;
202     if (delta >= 0) {
203         progress_ += delta;
204         if (progress_ > max_) {
205             int32_t old_max = max_;
206             max_ = floor((float)progress_ * growth_factor_);
207             MYLOGD("Adjusting max progress from %d to %d\n", old_max, max_);
208             changed = true;
209         }
210     }
211     return changed;
212 }
213
214 int32_t Progress::GetMax() const {
215     return max_;
216 }
217
218 int32_t Progress::GetInitialMax() const {
219     return initial_max_;
220 }
221
222 void Progress::Dump(int fd, const std::string& prefix) const {
223     const char* pr = prefix.c_str();
224     dprintf(fd, "%sprogress: %d\n", pr, progress_);
225     dprintf(fd, "%smax: %d\n", pr, max_);
226     dprintf(fd, "%sinitial_max: %d\n", pr, initial_max_);
227     dprintf(fd, "%sgrowth_factor: %0.2f\n", pr, growth_factor_);
228     dprintf(fd, "%spath: %s\n", pr, path_.c_str());
229     dprintf(fd, "%sn_runs: %d\n", pr, n_runs_);
230     dprintf(fd, "%saverage_max: %d\n", pr, average_max_);
231 }
232
233 bool Dumpstate::IsZipping() const {
234     return zip_writer_ != nullptr;
235 }
236
237 std::string Dumpstate::GetPath(const std::string& suffix) const {
238     return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
239                                        name_.c_str(), suffix.c_str());
240 }
241
242 void Dumpstate::SetProgress(std::unique_ptr<Progress> progress) {
243     progress_ = std::move(progress);
244 }
245
246 void for_each_userid(void (*func)(int), const char *header) {
247     std::string title = header == nullptr ? "for_each_userid" : android::base::StringPrintf(
248                                                                     "for_each_userid(%s)", header);
249     DurationReporter duration_reporter(title);
250     if (PropertiesHelper::IsDryRun()) return;
251
252     DIR *d;
253     struct dirent *de;
254
255     if (header) printf("\n------ %s ------\n", header);
256     func(0);
257
258     if (!(d = opendir("/data/system/users"))) {
259         printf("Failed to open /data/system/users (%s)\n", strerror(errno));
260         return;
261     }
262
263     while ((de = readdir(d))) {
264         int userid;
265         if (de->d_type != DT_DIR || !(userid = atoi(de->d_name))) {
266             continue;
267         }
268         func(userid);
269     }
270
271     closedir(d);
272 }
273
274 static void __for_each_pid(void (*helper)(int, const char *, void *), const char *header, void *arg) {
275     DIR *d;
276     struct dirent *de;
277
278     if (!(d = opendir("/proc"))) {
279         printf("Failed to open /proc (%s)\n", strerror(errno));
280         return;
281     }
282
283     if (header) printf("\n------ %s ------\n", header);
284     while ((de = readdir(d))) {
285         int pid;
286         int fd;
287         char cmdpath[255];
288         char cmdline[255];
289
290         if (!(pid = atoi(de->d_name))) {
291             continue;
292         }
293
294         memset(cmdline, 0, sizeof(cmdline));
295
296         snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/cmdline", pid);
297         if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
298             TEMP_FAILURE_RETRY(read(fd, cmdline, sizeof(cmdline) - 2));
299             close(fd);
300             if (cmdline[0]) {
301                 helper(pid, cmdline, arg);
302                 continue;
303             }
304         }
305
306         // if no cmdline, a kernel thread has comm
307         snprintf(cmdpath, sizeof(cmdpath), "/proc/%d/comm", pid);
308         if ((fd = TEMP_FAILURE_RETRY(open(cmdpath, O_RDONLY | O_CLOEXEC))) >= 0) {
309             TEMP_FAILURE_RETRY(read(fd, cmdline + 1, sizeof(cmdline) - 4));
310             close(fd);
311             if (cmdline[1]) {
312                 cmdline[0] = '[';
313                 size_t len = strcspn(cmdline, "\f\b\r\n");
314                 cmdline[len] = ']';
315                 cmdline[len+1] = '\0';
316             }
317         }
318         if (!cmdline[0]) {
319             strcpy(cmdline, "N/A");
320         }
321         helper(pid, cmdline, arg);
322     }
323
324     closedir(d);
325 }
326
327 static void for_each_pid_helper(int pid, const char *cmdline, void *arg) {
328     for_each_pid_func *func = (for_each_pid_func*) arg;
329     func(pid, cmdline);
330 }
331
332 void for_each_pid(for_each_pid_func func, const char *header) {
333     std::string title = header == nullptr ? "for_each_pid"
334                                           : android::base::StringPrintf("for_each_pid(%s)", header);
335     DurationReporter duration_reporter(title);
336     if (PropertiesHelper::IsDryRun()) return;
337
338     __for_each_pid(for_each_pid_helper, header, (void *) func);
339 }
340
341 static void for_each_tid_helper(int pid, const char *cmdline, void *arg) {
342     DIR *d;
343     struct dirent *de;
344     char taskpath[255];
345     for_each_tid_func *func = (for_each_tid_func *) arg;
346
347     snprintf(taskpath, sizeof(taskpath), "/proc/%d/task", pid);
348
349     if (!(d = opendir(taskpath))) {
350         printf("Failed to open %s (%s)\n", taskpath, strerror(errno));
351         return;
352     }
353
354     func(pid, pid, cmdline);
355
356     while ((de = readdir(d))) {
357         int tid;
358         int fd;
359         char commpath[255];
360         char comm[255];
361
362         if (!(tid = atoi(de->d_name))) {
363             continue;
364         }
365
366         if (tid == pid)
367             continue;
368
369         snprintf(commpath, sizeof(commpath), "/proc/%d/comm", tid);
370         memset(comm, 0, sizeof(comm));
371         if ((fd = TEMP_FAILURE_RETRY(open(commpath, O_RDONLY | O_CLOEXEC))) < 0) {
372             strcpy(comm, "N/A");
373         } else {
374             char *c;
375             TEMP_FAILURE_RETRY(read(fd, comm, sizeof(comm) - 2));
376             close(fd);
377
378             c = strrchr(comm, '\n');
379             if (c) {
380                 *c = '\0';
381             }
382         }
383         func(pid, tid, comm);
384     }
385
386     closedir(d);
387 }
388
389 void for_each_tid(for_each_tid_func func, const char *header) {
390     std::string title = header == nullptr ? "for_each_tid"
391                                           : android::base::StringPrintf("for_each_tid(%s)", header);
392     DurationReporter duration_reporter(title);
393
394     if (PropertiesHelper::IsDryRun()) return;
395
396     __for_each_pid(for_each_tid_helper, header, (void *) func);
397 }
398
399 void show_wchan(int pid, int tid, const char *name) {
400     if (PropertiesHelper::IsDryRun()) return;
401
402     char path[255];
403     char buffer[255];
404     int fd, ret, save_errno;
405     char name_buffer[255];
406
407     memset(buffer, 0, sizeof(buffer));
408
409     snprintf(path, sizeof(path), "/proc/%d/wchan", tid);
410     if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
411         printf("Failed to open '%s' (%s)\n", path, strerror(errno));
412         return;
413     }
414
415     ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
416     save_errno = errno;
417     close(fd);
418
419     if (ret < 0) {
420         printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
421         return;
422     }
423
424     snprintf(name_buffer, sizeof(name_buffer), "%*s%s",
425              pid == tid ? 0 : 3, "", name);
426
427     printf("%-7d %-32s %s\n", tid, name_buffer, buffer);
428
429     return;
430 }
431
432 // print time in centiseconds
433 static void snprcent(char *buffer, size_t len, size_t spc,
434                      unsigned long long time) {
435     static long hz; // cache discovered hz
436
437     if (hz <= 0) {
438         hz = sysconf(_SC_CLK_TCK);
439         if (hz <= 0) {
440             hz = 1000;
441         }
442     }
443
444     // convert to centiseconds
445     time = (time * 100 + (hz / 2)) / hz;
446
447     char str[16];
448
449     snprintf(str, sizeof(str), " %llu.%02u",
450              time / 100, (unsigned)(time % 100));
451     size_t offset = strlen(buffer);
452     snprintf(buffer + offset, (len > offset) ? len - offset : 0,
453              "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
454 }
455
456 // print permille as a percent
457 static void snprdec(char *buffer, size_t len, size_t spc, unsigned permille) {
458     char str[16];
459
460     snprintf(str, sizeof(str), " %u.%u%%", permille / 10, permille % 10);
461     size_t offset = strlen(buffer);
462     snprintf(buffer + offset, (len > offset) ? len - offset : 0,
463              "%*s", (spc > offset) ? (int)(spc - offset) : 0, str);
464 }
465
466 void show_showtime(int pid, const char *name) {
467     if (PropertiesHelper::IsDryRun()) return;
468
469     char path[255];
470     char buffer[1023];
471     int fd, ret, save_errno;
472
473     memset(buffer, 0, sizeof(buffer));
474
475     snprintf(path, sizeof(path), "/proc/%d/stat", pid);
476     if ((fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC))) < 0) {
477         printf("Failed to open '%s' (%s)\n", path, strerror(errno));
478         return;
479     }
480
481     ret = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
482     save_errno = errno;
483     close(fd);
484
485     if (ret < 0) {
486         printf("Failed to read '%s' (%s)\n", path, strerror(save_errno));
487         return;
488     }
489
490     // field 14 is utime
491     // field 15 is stime
492     // field 42 is iotime
493     unsigned long long utime = 0, stime = 0, iotime = 0;
494     if (sscanf(buffer,
495                "%*u %*s %*s %*d %*d %*d %*d %*d %*d %*d %*d "
496                "%*d %*d %llu %llu %*d %*d %*d %*d %*d %*d "
497                "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
498                "%*d %*d %*d %*d %*d %*d %*d %*d %*d %llu ",
499                &utime, &stime, &iotime) != 3) {
500         return;
501     }
502
503     unsigned long long total = utime + stime;
504     if (!total) {
505         return;
506     }
507
508     unsigned permille = (iotime * 1000 + (total / 2)) / total;
509     if (permille > 1000) {
510         permille = 1000;
511     }
512
513     // try to beautify and stabilize columns at <80 characters
514     snprintf(buffer, sizeof(buffer), "%-6d%s", pid, name);
515     if ((name[0] != '[') || utime) {
516         snprcent(buffer, sizeof(buffer), 57, utime);
517     }
518     snprcent(buffer, sizeof(buffer), 65, stime);
519     if ((name[0] != '[') || iotime) {
520         snprcent(buffer, sizeof(buffer), 73, iotime);
521     }
522     if (iotime) {
523         snprdec(buffer, sizeof(buffer), 79, permille);
524     }
525     puts(buffer);  // adds a trailing newline
526
527     return;
528 }
529
530 void do_dmesg() {
531     const char *title = "KERNEL LOG (dmesg)";
532     DurationReporter duration_reporter(title);
533     printf("------ %s ------\n", title);
534
535     if (PropertiesHelper::IsDryRun()) return;
536
537     /* Get size of kernel buffer */
538     int size = klogctl(KLOG_SIZE_BUFFER, NULL, 0);
539     if (size <= 0) {
540         printf("Unexpected klogctl return value: %d\n\n", size);
541         return;
542     }
543     char *buf = (char *) malloc(size + 1);
544     if (buf == NULL) {
545         printf("memory allocation failed\n\n");
546         return;
547     }
548     int retval = klogctl(KLOG_READ_ALL, buf, size);
549     if (retval < 0) {
550         printf("klogctl failure\n\n");
551         free(buf);
552         return;
553     }
554     buf[retval] = '\0';
555     printf("%s\n\n", buf);
556     free(buf);
557     return;
558 }
559
560 void do_showmap(int pid, const char *name) {
561     char title[255];
562     char arg[255];
563
564     snprintf(title, sizeof(title), "SHOW MAP %d (%s)", pid, name);
565     snprintf(arg, sizeof(arg), "%d", pid);
566     RunCommand(title, {"showmap", "-q", arg}, CommandOptions::AS_ROOT);
567 }
568
569 int Dumpstate::DumpFile(const std::string& title, const std::string& path) {
570     DurationReporter duration_reporter(title);
571
572     int status = DumpFileToFd(STDOUT_FILENO, title, path);
573
574     UpdateProgress(WEIGHT_FILE);
575
576     return status;
577 }
578
579 int read_file_as_long(const char *path, long int *output) {
580     int fd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
581     if (fd < 0) {
582         int err = errno;
583         MYLOGE("Error opening file descriptor for %s: %s\n", path, strerror(err));
584         return -1;
585     }
586     char buffer[50];
587     ssize_t bytes_read = TEMP_FAILURE_RETRY(read(fd, buffer, sizeof(buffer)));
588     if (bytes_read == -1) {
589         MYLOGE("Error reading file %s: %s\n", path, strerror(errno));
590         return -2;
591     }
592     if (bytes_read == 0) {
593         MYLOGE("File %s is empty\n", path);
594         return -3;
595     }
596     *output = atoi(buffer);
597     return 0;
598 }
599
600 /* calls skip to gate calling dump_from_fd recursively
601  * in the specified directory. dump_from_fd defaults to
602  * dump_file_from_fd above when set to NULL. skip defaults
603  * to false when set to NULL. dump_from_fd will always be
604  * called with title NULL.
605  */
606 int dump_files(const std::string& title, const char* dir, bool (*skip)(const char* path),
607                int (*dump_from_fd)(const char* title, const char* path, int fd)) {
608     DurationReporter duration_reporter(title);
609     DIR *dirp;
610     struct dirent *d;
611     char *newpath = NULL;
612     const char *slash = "/";
613     int fd, retval = 0;
614
615     if (!title.empty()) {
616         printf("------ %s (%s) ------\n", title.c_str(), dir);
617     }
618     if (PropertiesHelper::IsDryRun()) return 0;
619
620     if (dir[strlen(dir) - 1] == '/') {
621         ++slash;
622     }
623     dirp = opendir(dir);
624     if (dirp == NULL) {
625         retval = -errno;
626         MYLOGE("%s: %s\n", dir, strerror(errno));
627         return retval;
628     }
629
630     if (!dump_from_fd) {
631         dump_from_fd = dump_file_from_fd;
632     }
633     for (; ((d = readdir(dirp))); free(newpath), newpath = NULL) {
634         if ((d->d_name[0] == '.')
635          && (((d->d_name[1] == '.') && (d->d_name[2] == '\0'))
636           || (d->d_name[1] == '\0'))) {
637             continue;
638         }
639         asprintf(&newpath, "%s%s%s%s", dir, slash, d->d_name,
640                  (d->d_type == DT_DIR) ? "/" : "");
641         if (!newpath) {
642             retval = -errno;
643             continue;
644         }
645         if (skip && (*skip)(newpath)) {
646             continue;
647         }
648         if (d->d_type == DT_DIR) {
649             int ret = dump_files("", newpath, skip, dump_from_fd);
650             if (ret < 0) {
651                 retval = ret;
652             }
653             continue;
654         }
655         fd = TEMP_FAILURE_RETRY(open(newpath, O_RDONLY | O_NONBLOCK | O_CLOEXEC));
656         if (fd < 0) {
657             retval = fd;
658             printf("*** %s: %s\n", newpath, strerror(errno));
659             continue;
660         }
661         (*dump_from_fd)(NULL, newpath, fd);
662     }
663     closedir(dirp);
664     if (!title.empty()) {
665         printf("\n");
666     }
667     return retval;
668 }
669
670 /* fd must have been opened with the flag O_NONBLOCK. With this flag set,
671  * it's possible to avoid issues where opening the file itself can get
672  * stuck.
673  */
674 int dump_file_from_fd(const char *title, const char *path, int fd) {
675     if (PropertiesHelper::IsDryRun()) return 0;
676
677     int flags = fcntl(fd, F_GETFL);
678     if (flags == -1) {
679         printf("*** %s: failed to get flags on fd %d: %s\n", path, fd, strerror(errno));
680         close(fd);
681         return -1;
682     } else if (!(flags & O_NONBLOCK)) {
683         printf("*** %s: fd must have O_NONBLOCK set.\n", path);
684         close(fd);
685         return -1;
686     }
687     return DumpFileFromFdToFd(title, path, fd, STDOUT_FILENO, PropertiesHelper::IsDryRun());
688 }
689
690 int Dumpstate::RunCommand(const std::string& title, const std::vector<std::string>& full_command,
691                           const CommandOptions& options) {
692     DurationReporter duration_reporter(title);
693
694     int status = RunCommandToFd(STDOUT_FILENO, title, full_command, options);
695
696     /* TODO: for now we're simplifying the progress calculation by using the
697      * timeout as the weight. It's a good approximation for most cases, except when calling dumpsys,
698      * where its weight should be much higher proportionally to its timeout.
699      * Ideally, it should use a options.EstimatedDuration() instead...*/
700     UpdateProgress(options.Timeout());
701
702     return status;
703 }
704
705 void Dumpstate::RunDumpsys(const std::string& title, const std::vector<std::string>& dumpsys_args,
706                            const CommandOptions& options, long dumpsysTimeout) {
707     long timeout = dumpsysTimeout > 0 ? dumpsysTimeout : options.Timeout();
708     std::vector<std::string> dumpsys = {"/system/bin/dumpsys", "-t", std::to_string(timeout)};
709     dumpsys.insert(dumpsys.end(), dumpsys_args.begin(), dumpsys_args.end());
710     RunCommand(title, dumpsys, options);
711 }
712
713 int open_socket(const char *service) {
714     int s = android_get_control_socket(service);
715     if (s < 0) {
716         MYLOGE("android_get_control_socket(%s): %s\n", service, strerror(errno));
717         exit(1);
718     }
719     fcntl(s, F_SETFD, FD_CLOEXEC);
720     if (listen(s, 4) < 0) {
721         MYLOGE("listen(control socket): %s\n", strerror(errno));
722         exit(1);
723     }
724
725     struct sockaddr addr;
726     socklen_t alen = sizeof(addr);
727     int fd = accept(s, &addr, &alen);
728     if (fd < 0) {
729         MYLOGE("accept(control socket): %s\n", strerror(errno));
730         exit(1);
731     }
732
733     return fd;
734 }
735
736 /* redirect output to a service control socket */
737 void redirect_to_socket(FILE *redirect, const char *service) {
738     int fd = open_socket(service);
739     fflush(redirect);
740     dup2(fd, fileno(redirect));
741     close(fd);
742 }
743
744 // TODO: should call is_valid_output_file and/or be merged into it.
745 void create_parent_dirs(const char *path) {
746     char *chp = const_cast<char *> (path);
747
748     /* skip initial slash */
749     if (chp[0] == '/')
750         chp++;
751
752     /* create leading directories, if necessary */
753     struct stat dir_stat;
754     while (chp && chp[0]) {
755         chp = strchr(chp, '/');
756         if (chp) {
757             *chp = 0;
758             if (stat(path, &dir_stat) == -1 || !S_ISDIR(dir_stat.st_mode)) {
759                 MYLOGI("Creating directory %s\n", path);
760                 if (mkdir(path, 0770)) { /* drwxrwx--- */
761                     MYLOGE("Unable to create directory %s: %s\n", path, strerror(errno));
762                 } else if (chown(path, AID_SHELL, AID_SHELL)) {
763                     MYLOGE("Unable to change ownership of dir %s: %s\n", path, strerror(errno));
764                 }
765             }
766             *chp++ = '/';
767         }
768     }
769 }
770
771 void _redirect_to_file(FILE *redirect, char *path, int truncate_flag) {
772     create_parent_dirs(path);
773
774     int fd = TEMP_FAILURE_RETRY(open(path,
775                                      O_WRONLY | O_CREAT | truncate_flag | O_CLOEXEC | O_NOFOLLOW,
776                                      S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
777     if (fd < 0) {
778         MYLOGE("%s: %s\n", path, strerror(errno));
779         exit(1);
780     }
781
782     TEMP_FAILURE_RETRY(dup2(fd, fileno(redirect)));
783     close(fd);
784 }
785
786 void redirect_to_file(FILE *redirect, char *path) {
787     _redirect_to_file(redirect, path, O_TRUNC);
788 }
789
790 void redirect_to_existing_file(FILE *redirect, char *path) {
791     _redirect_to_file(redirect, path, O_APPEND);
792 }
793
794 static bool should_dump_native_traces(const char* path) {
795     for (const char** p = native_processes_to_dump; *p; p++) {
796         if (!strcmp(*p, path)) {
797             return true;
798         }
799     }
800     return false;
801 }
802
803 /* dump Dalvik and native stack traces, return the trace file location (NULL if none) */
804 const char *dump_traces() {
805     DurationReporter duration_reporter("DUMP TRACES");
806
807     const char* result = nullptr;
808
809     std::string traces_path = android::base::GetProperty("dalvik.vm.stack-trace-file", "");
810     if (traces_path.empty()) return nullptr;
811
812     /* move the old traces.txt (if any) out of the way temporarily */
813     std::string anrtraces_path = traces_path + ".anr";
814     if (rename(traces_path.c_str(), anrtraces_path.c_str()) && errno != ENOENT) {
815         MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), anrtraces_path.c_str(), strerror(errno));
816         return nullptr;  // Can't rename old traces.txt -- no permission? -- leave it alone instead
817     }
818
819     /* create a new, empty traces.txt file to receive stack dumps */
820     int fd = TEMP_FAILURE_RETRY(
821         open(traces_path.c_str(), O_CREAT | O_WRONLY | O_APPEND | O_TRUNC | O_NOFOLLOW | O_CLOEXEC,
822              0666)); /* -rw-rw-rw- */
823     if (fd < 0) {
824         MYLOGE("%s: %s\n", traces_path.c_str(), strerror(errno));
825         return nullptr;
826     }
827     int chmod_ret = fchmod(fd, 0666);
828     if (chmod_ret < 0) {
829         MYLOGE("fchmod on %s failed: %s\n", traces_path.c_str(), strerror(errno));
830         close(fd);
831         return nullptr;
832     }
833
834     /* Variables below must be initialized before 'goto' statements */
835     int dalvik_found = 0;
836     int ifd, wfd = -1;
837
838     /* walk /proc and kill -QUIT all Dalvik processes */
839     DIR *proc = opendir("/proc");
840     if (proc == NULL) {
841         MYLOGE("/proc: %s\n", strerror(errno));
842         goto error_close_fd;
843     }
844
845     /* use inotify to find when processes are done dumping */
846     ifd = inotify_init();
847     if (ifd < 0) {
848         MYLOGE("inotify_init: %s\n", strerror(errno));
849         goto error_close_fd;
850     }
851
852     wfd = inotify_add_watch(ifd, traces_path.c_str(), IN_CLOSE_WRITE);
853     if (wfd < 0) {
854         MYLOGE("inotify_add_watch(%s): %s\n", traces_path.c_str(), strerror(errno));
855         goto error_close_ifd;
856     }
857
858     struct dirent *d;
859     while ((d = readdir(proc))) {
860         int pid = atoi(d->d_name);
861         if (pid <= 0) continue;
862
863         char path[PATH_MAX];
864         char data[PATH_MAX];
865         snprintf(path, sizeof(path), "/proc/%d/exe", pid);
866         ssize_t len = readlink(path, data, sizeof(data) - 1);
867         if (len <= 0) {
868             continue;
869         }
870         data[len] = '\0';
871
872         if (!strncmp(data, "/system/bin/app_process", strlen("/system/bin/app_process"))) {
873             /* skip zygote -- it won't dump its stack anyway */
874             snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
875             int cfd = TEMP_FAILURE_RETRY(open(path, O_RDONLY | O_CLOEXEC));
876             len = read(cfd, data, sizeof(data) - 1);
877             close(cfd);
878             if (len <= 0) {
879                 continue;
880             }
881             data[len] = '\0';
882             if (!strncmp(data, "zygote", strlen("zygote"))) {
883                 continue;
884             }
885
886             ++dalvik_found;
887             uint64_t start = Nanotime();
888             if (kill(pid, SIGQUIT)) {
889                 MYLOGE("kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
890                 continue;
891             }
892
893             /* wait for the writable-close notification from inotify */
894             struct pollfd pfd = { ifd, POLLIN, 0 };
895             int ret = poll(&pfd, 1, TRACE_DUMP_TIMEOUT_MS);
896             if (ret < 0) {
897                 MYLOGE("poll: %s\n", strerror(errno));
898             } else if (ret == 0) {
899                 MYLOGE("warning: timed out dumping pid %d\n", pid);
900             } else {
901                 struct inotify_event ie;
902                 read(ifd, &ie, sizeof(ie));
903             }
904
905             if (lseek(fd, 0, SEEK_END) < 0) {
906                 MYLOGE("lseek: %s\n", strerror(errno));
907             } else {
908                 dprintf(fd, "[dump dalvik stack %d: %.3fs elapsed]\n", pid,
909                         (float)(Nanotime() - start) / NANOS_PER_SEC);
910             }
911         } else if (should_dump_native_traces(data)) {
912             /* dump native process if appropriate */
913             if (lseek(fd, 0, SEEK_END) < 0) {
914                 MYLOGE("lseek: %s\n", strerror(errno));
915             } else {
916                 static uint16_t timeout_failures = 0;
917                 uint64_t start = Nanotime();
918
919                 /* If 3 backtrace dumps fail in a row, consider debuggerd dead. */
920                 if (timeout_failures == 3) {
921                     dprintf(fd, "too many stack dump failures, skipping...\n");
922                 } else if (dump_backtrace_to_file_timeout(pid, fd, 20) == -1) {
923                     dprintf(fd, "dumping failed, likely due to a timeout\n");
924                     timeout_failures++;
925                 } else {
926                     timeout_failures = 0;
927                 }
928                 dprintf(fd, "[dump native stack %d: %.3fs elapsed]\n", pid,
929                         (float)(Nanotime() - start) / NANOS_PER_SEC);
930             }
931         }
932     }
933
934     if (dalvik_found == 0) {
935         MYLOGE("Warning: no Dalvik processes found to dump stacks\n");
936     }
937
938     static std::string dumptraces_path = android::base::StringPrintf(
939         "%s/bugreport-%s", dirname(traces_path.c_str()), basename(traces_path.c_str()));
940     if (rename(traces_path.c_str(), dumptraces_path.c_str())) {
941         MYLOGE("rename(%s, %s): %s\n", traces_path.c_str(), dumptraces_path.c_str(),
942                strerror(errno));
943         goto error_close_ifd;
944     }
945     result = dumptraces_path.c_str();
946
947     /* replace the saved [ANR] traces.txt file */
948     rename(anrtraces_path.c_str(), traces_path.c_str());
949
950 error_close_ifd:
951     close(ifd);
952 error_close_fd:
953     close(fd);
954     return result;
955 }
956
957 void dump_route_tables() {
958     DurationReporter duration_reporter("DUMP ROUTE TABLES");
959     if (PropertiesHelper::IsDryRun()) return;
960     const char* const RT_TABLES_PATH = "/data/misc/net/rt_tables";
961     ds.DumpFile("RT_TABLES", RT_TABLES_PATH);
962     FILE* fp = fopen(RT_TABLES_PATH, "re");
963     if (!fp) {
964         printf("*** %s: %s\n", RT_TABLES_PATH, strerror(errno));
965         return;
966     }
967     char table[16];
968     // Each line has an integer (the table number), a space, and a string (the table name). We only
969     // need the table number. It's a 32-bit unsigned number, so max 10 chars. Skip the table name.
970     // Add a fixed max limit so this doesn't go awry.
971     for (int i = 0; i < 64 && fscanf(fp, " %10s %*s", table) == 1; ++i) {
972         RunCommand("ROUTE TABLE IPv4", {"ip", "-4", "route", "show", "table", table});
973         RunCommand("ROUTE TABLE IPv6", {"ip", "-6", "route", "show", "table", table});
974     }
975     fclose(fp);
976 }
977
978 // TODO: make this function thread safe if sections are generated in parallel.
979 void Dumpstate::UpdateProgress(int32_t delta) {
980     if (progress_ == nullptr) {
981         MYLOGE("UpdateProgress: progress_ not set\n");
982         return;
983     }
984
985     // Always update progess so stats can be tuned...
986     bool max_changed = progress_->Inc(delta);
987
988     // ...but only notifiy listeners when necessary.
989     if (!update_progress_) return;
990
991     int progress = progress_->Get();
992     int max = progress_->GetMax();
993
994     // adjusts max on the fly
995     if (max_changed && listener_ != nullptr) {
996         listener_->onMaxProgressUpdated(max);
997     }
998
999     int32_t last_update_delta = progress - last_updated_progress_;
1000     if (last_updated_progress_ > 0 && last_update_delta < update_progress_threshold_) {
1001         return;
1002     }
1003     last_updated_progress_ = progress;
1004
1005     if (control_socket_fd_ >= 0) {
1006         dprintf(control_socket_fd_, "PROGRESS:%d/%d\n", progress, max);
1007         fsync(control_socket_fd_);
1008     }
1009
1010     if (listener_ != nullptr) {
1011         if (progress % 100 == 0) {
1012             // We don't want to spam logcat, so only log multiples of 100.
1013             MYLOGD("Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
1014         } else {
1015             // stderr is ignored on normal invocations, but useful when calling
1016             // /system/bin/dumpstate directly for debuggging.
1017             fprintf(stderr, "Setting progress (%s): %d/%d\n", listener_name_.c_str(), progress, max);
1018         }
1019         listener_->onProgressUpdated(progress);
1020     }
1021 }
1022
1023 void Dumpstate::TakeScreenshot(const std::string& path) {
1024     const std::string& real_path = path.empty() ? screenshot_path_ : path;
1025     int status =
1026         RunCommand("", {"/system/bin/screencap", "-p", real_path},
1027                    CommandOptions::WithTimeout(10).Always().DropRoot().RedirectStderr().Build());
1028     if (status == 0) {
1029         MYLOGD("Screenshot saved on %s\n", real_path.c_str());
1030     } else {
1031         MYLOGE("Failed to take screenshot on %s\n", real_path.c_str());
1032     }
1033 }
1034
1035 bool is_dir(const char* pathname) {
1036     struct stat info;
1037     if (stat(pathname, &info) == -1) {
1038         return false;
1039     }
1040     return S_ISDIR(info.st_mode);
1041 }
1042
1043 time_t get_mtime(int fd, time_t default_mtime) {
1044     struct stat info;
1045     if (fstat(fd, &info) == -1) {
1046         return default_mtime;
1047     }
1048     return info.st_mtime;
1049 }
1050
1051 void dump_emmc_ecsd(const char *ext_csd_path) {
1052     // List of interesting offsets
1053     struct hex {
1054         char str[2];
1055     };
1056     static const size_t EXT_CSD_REV = 192 * sizeof(hex);
1057     static const size_t EXT_PRE_EOL_INFO = 267 * sizeof(hex);
1058     static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_A = 268 * sizeof(hex);
1059     static const size_t EXT_DEVICE_LIFE_TIME_EST_TYP_B = 269 * sizeof(hex);
1060
1061     std::string buffer;
1062     if (!android::base::ReadFileToString(ext_csd_path, &buffer)) {
1063         return;
1064     }
1065
1066     printf("------ %s Extended CSD ------\n", ext_csd_path);
1067
1068     if (buffer.length() < (EXT_CSD_REV + sizeof(hex))) {
1069         printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
1070         return;
1071     }
1072
1073     int ext_csd_rev = 0;
1074     std::string sub = buffer.substr(EXT_CSD_REV, sizeof(hex));
1075     if (sscanf(sub.c_str(), "%2x", &ext_csd_rev) != 1) {
1076         printf("*** %s: EXT_CSD_REV parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
1077         return;
1078     }
1079
1080     static const char *ver_str[] = {
1081         "4.0", "4.1", "4.2", "4.3", "Obsolete", "4.41", "4.5", "5.0"
1082     };
1083     printf("rev 1.%d (MMC %s)\n", ext_csd_rev,
1084            (ext_csd_rev < (int)(sizeof(ver_str) / sizeof(ver_str[0]))) ? ver_str[ext_csd_rev]
1085                                                                        : "Unknown");
1086     if (ext_csd_rev < 7) {
1087         printf("\n");
1088         return;
1089     }
1090
1091     if (buffer.length() < (EXT_PRE_EOL_INFO + sizeof(hex))) {
1092         printf("*** %s: truncated content %zu\n\n", ext_csd_path, buffer.length());
1093         return;
1094     }
1095
1096     int ext_pre_eol_info = 0;
1097     sub = buffer.substr(EXT_PRE_EOL_INFO, sizeof(hex));
1098     if (sscanf(sub.c_str(), "%2x", &ext_pre_eol_info) != 1) {
1099         printf("*** %s: PRE_EOL_INFO parse error \"%s\"\n\n", ext_csd_path, sub.c_str());
1100         return;
1101     }
1102
1103     static const char *eol_str[] = {
1104         "Undefined",
1105         "Normal",
1106         "Warning (consumed 80% of reserve)",
1107         "Urgent (consumed 90% of reserve)"
1108     };
1109     printf(
1110         "PRE_EOL_INFO %d (MMC %s)\n", ext_pre_eol_info,
1111         eol_str[(ext_pre_eol_info < (int)(sizeof(eol_str) / sizeof(eol_str[0]))) ? ext_pre_eol_info
1112                                                                                  : 0]);
1113
1114     for (size_t lifetime = EXT_DEVICE_LIFE_TIME_EST_TYP_A;
1115             lifetime <= EXT_DEVICE_LIFE_TIME_EST_TYP_B;
1116             lifetime += sizeof(hex)) {
1117         int ext_device_life_time_est;
1118         static const char *est_str[] = {
1119             "Undefined",
1120             "0-10% of device lifetime used",
1121             "10-20% of device lifetime used",
1122             "20-30% of device lifetime used",
1123             "30-40% of device lifetime used",
1124             "40-50% of device lifetime used",
1125             "50-60% of device lifetime used",
1126             "60-70% of device lifetime used",
1127             "70-80% of device lifetime used",
1128             "80-90% of device lifetime used",
1129             "90-100% of device lifetime used",
1130             "Exceeded the maximum estimated device lifetime",
1131         };
1132
1133         if (buffer.length() < (lifetime + sizeof(hex))) {
1134             printf("*** %s: truncated content %zu\n", ext_csd_path, buffer.length());
1135             break;
1136         }
1137
1138         ext_device_life_time_est = 0;
1139         sub = buffer.substr(lifetime, sizeof(hex));
1140         if (sscanf(sub.c_str(), "%2x", &ext_device_life_time_est) != 1) {
1141             printf("*** %s: DEVICE_LIFE_TIME_EST_TYP_%c parse error \"%s\"\n", ext_csd_path,
1142                    (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1143                    sub.c_str());
1144             continue;
1145         }
1146         printf("DEVICE_LIFE_TIME_EST_TYP_%c %d (MMC %s)\n",
1147                (unsigned)((lifetime - EXT_DEVICE_LIFE_TIME_EST_TYP_A) / sizeof(hex)) + 'A',
1148                ext_device_life_time_est,
1149                est_str[(ext_device_life_time_est < (int)(sizeof(est_str) / sizeof(est_str[0])))
1150                            ? ext_device_life_time_est
1151                            : 0]);
1152     }
1153
1154     printf("\n");
1155 }