move dumpstate and dumpsys from frameworks/base to frameworks/native

Change-Id: I8a5318022ce5cd3e7c8055f21fe5da74639aa6c0
This commit is contained in:
Colin Cross 2012-03-26 12:38:26 -07:00
parent 0b94dcd03d
commit f45fa6b285
8 changed files with 1297 additions and 0 deletions

19
cmds/dumpstate/Android.mk Normal file
View File

@ -0,0 +1,19 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
ifdef BOARD_WLAN_DEVICE
LOCAL_CFLAGS := -DFWDUMP_$(BOARD_WLAN_DEVICE)
endif
LOCAL_SRC_FILES := dumpstate.c utils.c
LOCAL_MODULE := dumpstate
LOCAL_SHARED_LIBRARIES := libcutils
ifdef BOARD_LIB_DUMPSTATE
LOCAL_STATIC_LIBRARIES := $(BOARD_LIB_DUMPSTATE)
LOCAL_CFLAGS += -DBOARD_HAS_DUMPSTATE
endif
include $(BUILD_EXECUTABLE)

452
cmds/dumpstate/dumpstate.c Normal file
View File

@ -0,0 +1,452 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
#include <linux/capability.h>
#include <linux/prctl.h>
#include <cutils/properties.h>
#include "private/android_filesystem_config.h"
#define LOG_TAG "dumpstate"
#include <utils/Log.h>
#include "dumpstate.h"
/* read before root is shed */
static char cmdline_buf[16384] = "(unknown)";
static const char *dump_traces_path = NULL;
static char screenshot_path[PATH_MAX] = "";
/* dumps the current system state to stdout */
static void dumpstate() {
time_t now = time(NULL);
char build[PROPERTY_VALUE_MAX], fingerprint[PROPERTY_VALUE_MAX];
char radio[PROPERTY_VALUE_MAX], bootloader[PROPERTY_VALUE_MAX];
char network[PROPERTY_VALUE_MAX], date[80];
char build_type[PROPERTY_VALUE_MAX];
property_get("ro.build.display.id", build, "(unknown)");
property_get("ro.build.fingerprint", fingerprint, "(unknown)");
property_get("ro.build.type", build_type, "(unknown)");
property_get("ro.baseband", radio, "(unknown)");
property_get("ro.bootloader", bootloader, "(unknown)");
property_get("gsm.operator.alpha", network, "(unknown)");
strftime(date, sizeof(date), "%Y-%m-%d %H:%M:%S", localtime(&now));
printf("========================================================\n");
printf("== dumpstate: %s\n", date);
printf("========================================================\n");
printf("\n");
printf("Build: %s\n", build);
printf("Build fingerprint: '%s'\n", fingerprint); /* format is important for other tools */
printf("Bootloader: %s\n", bootloader);
printf("Radio: %s\n", radio);
printf("Network: %s\n", network);
printf("Kernel: ");
dump_file(NULL, "/proc/version");
printf("Command line: %s\n", strtok(cmdline_buf, "\n"));
printf("\n");
run_command("UPTIME", 10, "uptime", NULL);
dump_file("MEMORY INFO", "/proc/meminfo");
run_command("CPU INFO", 10, "top", "-n", "1", "-d", "1", "-m", "30", "-t", NULL);
run_command("PROCRANK", 20, "procrank", NULL);
dump_file("VIRTUAL MEMORY STATS", "/proc/vmstat");
dump_file("VMALLOC INFO", "/proc/vmallocinfo");
dump_file("SLAB INFO", "/proc/slabinfo");
dump_file("ZONEINFO", "/proc/zoneinfo");
dump_file("PAGETYPEINFO", "/proc/pagetypeinfo");
dump_file("BUDDYINFO", "/proc/buddyinfo");
dump_file("KERNEL WAKELOCKS", "/proc/wakelocks");
dump_file("KERNEL CPUFREQ", "/sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state");
run_command("PROCESSES", 10, "ps", "-P", NULL);
run_command("PROCESSES AND THREADS", 10, "ps", "-t", "-p", "-P", NULL);
run_command("LIBRANK", 10, "librank", NULL);
do_dmesg();
run_command("LIST OF OPEN FILES", 10, SU_PATH, "root", "lsof", NULL);
for_each_pid(do_showmap, "SMAPS OF ALL PROCESSES");
for_each_pid(show_wchan, "BLOCKED PROCESS WAIT-CHANNELS");
// dump_file("EVENT LOG TAGS", "/etc/event-log-tags");
run_command("SYSTEM LOG", 20, "logcat", "-v", "threadtime", "-d", "*:v", NULL);
run_command("EVENT LOG", 20, "logcat", "-b", "events", "-v", "threadtime", "-d", "*:v", NULL);
run_command("RADIO LOG", 20, "logcat", "-b", "radio", "-v", "threadtime", "-d", "*:v", NULL);
/* show the traces we collected in main(), if that was done */
if (dump_traces_path != NULL) {
dump_file("VM TRACES JUST NOW", dump_traces_path);
}
/* only show ANR traces if they're less than 15 minutes old */
struct stat st;
char anr_traces_path[PATH_MAX];
property_get("dalvik.vm.stack-trace-file", anr_traces_path, "");
if (!anr_traces_path[0]) {
printf("*** NO VM TRACES FILE DEFINED (dalvik.vm.stack-trace-file)\n\n");
} else if (stat(anr_traces_path, &st)) {
printf("*** NO ANR VM TRACES FILE (%s): %s\n\n", anr_traces_path, strerror(errno));
} else {
dump_file("VM TRACES AT LAST ANR", anr_traces_path);
}
/* slow traces for slow operations */
if (anr_traces_path[0] != 0) {
int tail = strlen(anr_traces_path)-1;
while (tail > 0 && anr_traces_path[tail] != '/') {
tail--;
}
int i = 0;
while (1) {
sprintf(anr_traces_path+tail+1, "slow%02d.txt", i);
if (stat(anr_traces_path, &st)) {
// No traces file at this index, done with the files.
break;
}
dump_file("VM TRACES WHEN SLOW", anr_traces_path);
i++;
}
}
dump_file("NETWORK DEV INFO", "/proc/net/dev");
dump_file("QTAGUID NETWORK INTERFACES INFO", "/proc/net/xt_qtaguid/iface_stat_all");
dump_file("QTAGUID CTRL INFO", "/proc/net/xt_qtaguid/ctrl");
dump_file("QTAGUID STATS INFO", "/proc/net/xt_qtaguid/stats");
dump_file("NETWORK ROUTES", "/proc/net/route");
dump_file("NETWORK ROUTES IPV6", "/proc/net/ipv6_route");
/* TODO: Make last_kmsg CAP_SYSLOG protected. b/5555691 */
dump_file("LAST KMSG", "/proc/last_kmsg");
dump_file("LAST PANIC CONSOLE", "/data/dontpanic/apanic_console");
dump_file("LAST PANIC THREADS", "/data/dontpanic/apanic_threads");
if (screenshot_path[0]) {
ALOGI("taking screenshot\n");
run_command(NULL, 5, SU_PATH, "root", "screenshot", screenshot_path, NULL);
ALOGI("wrote screenshot: %s\n", screenshot_path);
}
run_command("SYSTEM SETTINGS", 20, SU_PATH, "root", "sqlite3",
"/data/data/com.android.providers.settings/databases/settings.db",
"pragma user_version; select * from system; select * from secure;", NULL);
/* The following have a tendency to get wedged when wifi drivers/fw goes belly-up. */
run_command("NETWORK INTERFACES", 10, SU_PATH, "root", "netcfg", NULL);
run_command("IP RULES", 10, "ip", "rule", "show", NULL);
run_command("IP RULES v6", 10, "ip", "-6", "rule", "show", NULL);
run_command("ROUTE TABLE 60", 10, "ip", "route", "show", "table", "60", NULL);
run_command("ROUTE TABLE 61 v6", 10, "ip", "-6", "route", "show", "table", "60", NULL);
run_command("ROUTE TABLE 61", 10, "ip", "route", "show", "table", "61", NULL);
run_command("ROUTE TABLE 61 v6", 10, "ip", "-6", "route", "show", "table", "61", NULL);
dump_file("ARP CACHE", "/proc/net/arp");
run_command("IPTABLES", 10, SU_PATH, "root", "iptables", "-L", "-nvx", NULL);
run_command("IP6TABLES", 10, SU_PATH, "root", "ip6tables", "-L", "-nvx", NULL);
run_command("IPTABLE NAT", 10, SU_PATH, "root", "iptables", "-t", "nat", "-L", "-n", NULL);
run_command("IPT6ABLE NAT", 10, SU_PATH, "root", "ip6tables", "-t", "nat", "-L", "-n", NULL);
run_command("WIFI NETWORKS", 20,
SU_PATH, "root", "wpa_cli", "list_networks", NULL);
property_get("dhcp.wlan0.gateway", network, "");
if (network[0])
run_command("PING GATEWAY", 10, SU_PATH, "root", "ping", "-c", "3", "-i", ".5", network, NULL);
property_get("dhcp.wlan0.dns1", network, "");
if (network[0])
run_command("PING DNS1", 10, SU_PATH, "root", "ping", "-c", "3", "-i", ".5", network, NULL);
property_get("dhcp.wlan0.dns2", network, "");
if (network[0])
run_command("PING DNS2", 10, SU_PATH, "root", "ping", "-c", "3", "-i", ".5", network, NULL);
#ifdef FWDUMP_bcm4329
run_command("DUMP WIFI STATUS", 20,
SU_PATH, "root", "dhdutil", "-i", "wlan0", "dump", NULL);
run_command("DUMP WIFI INTERNAL COUNTERS", 20,
SU_PATH, "root", "wlutil", "counters", NULL);
#endif
print_properties();
run_command("VOLD DUMP", 10, "vdc", "dump", NULL);
run_command("SECURE CONTAINERS", 10, "vdc", "asec", "list", NULL);
run_command("FILESYSTEMS & FREE SPACE", 10, SU_PATH, "root", "df", NULL);
dump_file("PACKAGE SETTINGS", "/data/system/packages.xml");
dump_file("PACKAGE UID ERRORS", "/data/system/uiderrors.txt");
run_command("LAST RADIO LOG", 10, "parse_radio_log", "/proc/last_radio_log", NULL);
printf("------ BACKLIGHTS ------\n");
printf("LCD brightness=");
dump_file(NULL, "/sys/class/leds/lcd-backlight/brightness");
printf("Button brightness=");
dump_file(NULL, "/sys/class/leds/button-backlight/brightness");
printf("Keyboard brightness=");
dump_file(NULL, "/sys/class/leds/keyboard-backlight/brightness");
printf("ALS mode=");
dump_file(NULL, "/sys/class/leds/lcd-backlight/als");
printf("LCD driver registers:\n");
dump_file(NULL, "/sys/class/leds/lcd-backlight/registers");
printf("\n");
/* Binder state is expensive to look at as it uses a lot of memory. */
dump_file("BINDER FAILED TRANSACTION LOG", "/sys/kernel/debug/binder/failed_transaction_log");
dump_file("BINDER TRANSACTION LOG", "/sys/kernel/debug/binder/transaction_log");
dump_file("BINDER TRANSACTIONS", "/sys/kernel/debug/binder/transactions");
dump_file("BINDER STATS", "/sys/kernel/debug/binder/stats");
dump_file("BINDER STATE", "/sys/kernel/debug/binder/state");
#ifdef BOARD_HAS_DUMPSTATE
printf("========================================================\n");
printf("== Board\n");
printf("========================================================\n");
dumpstate_board();
printf("\n");
#endif
/* Migrate the ril_dumpstate to a dumpstate_board()? */
char ril_dumpstate_timeout[PROPERTY_VALUE_MAX] = {0};
property_get("ril.dumpstate.timeout", ril_dumpstate_timeout, "30");
if (strnlen(ril_dumpstate_timeout, PROPERTY_VALUE_MAX - 1) > 0) {
if (0 == strncmp(build_type, "user", PROPERTY_VALUE_MAX - 1)) {
// su does not exist on user builds, so try running without it.
// This way any implementations of vril-dump that do not require
// root can run on user builds.
run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout),
"vril-dump", NULL);
} else {
run_command("DUMP VENDOR RIL LOGS", atoi(ril_dumpstate_timeout),
SU_PATH, "root", "vril-dump", NULL);
}
}
printf("========================================================\n");
printf("== Android Framework Services\n");
printf("========================================================\n");
/* the full dumpsys is starting to take a long time, so we need
to increase its timeout. we really need to do the timeouts in
dumpsys itself... */
run_command("DUMPSYS", 60, "dumpsys", NULL);
printf("========================================================\n");
printf("== Running Application Activities\n");
printf("========================================================\n");
run_command("APP ACTIVITIES", 30, "dumpsys", "activity", "all", NULL);
printf("========================================================\n");
printf("== Running Application Services\n");
printf("========================================================\n");
run_command("APP SERVICES", 30, "dumpsys", "activity", "service", "all", NULL);
printf("========================================================\n");
printf("== Running Application Providers\n");
printf("========================================================\n");
run_command("APP SERVICES", 30, "dumpsys", "activity", "provider", "all", NULL);
printf("========================================================\n");
printf("== dumpstate: done\n");
printf("========================================================\n");
}
static void usage() {
fprintf(stderr, "usage: dumpstate [-b soundfile] [-e soundfile] [-o file [-d] [-p] [-z]] [-s]\n"
" -o: write to file (instead of stdout)\n"
" -d: append date to filename (requires -o)\n"
" -z: gzip output (requires -o)\n"
" -p: capture screenshot to filename.png (requires -o)\n"
" -s: write output to control socket (for init)\n"
" -b: play sound file instead of vibrate, at beginning of job\n"
" -e: play sound file instead of vibrate, at end of job\n"
);
}
int main(int argc, char *argv[]) {
int do_add_date = 0;
int do_compress = 0;
char* use_outfile = 0;
char* begin_sound = 0;
char* end_sound = 0;
int use_socket = 0;
int do_fb = 0;
ALOGI("begin\n");
/* set as high priority, and protect from OOM killer */
setpriority(PRIO_PROCESS, 0, -20);
FILE *oom_adj = fopen("/proc/self/oom_adj", "w");
if (oom_adj) {
fputs("-17", oom_adj);
fclose(oom_adj);
}
/* very first thing, collect VM traces from Dalvik (needs root) */
dump_traces_path = dump_vm_traces();
int c;
while ((c = getopt(argc, argv, "b:de:ho:svzp")) != -1) {
switch (c) {
case 'b': begin_sound = optarg; break;
case 'd': do_add_date = 1; break;
case 'e': end_sound = optarg; break;
case 'o': use_outfile = optarg; break;
case 's': use_socket = 1; break;
case 'v': break; // compatibility no-op
case 'z': do_compress = 6; break;
case 'p': do_fb = 1; break;
case '?': printf("\n");
case 'h':
usage();
exit(1);
}
}
/* open the vibrator before dropping root */
FILE *vibrator = fopen("/sys/class/timed_output/vibrator/enable", "w");
if (vibrator) fcntl(fileno(vibrator), F_SETFD, FD_CLOEXEC);
/* read /proc/cmdline before dropping root */
FILE *cmdline = fopen("/proc/cmdline", "r");
if (cmdline != NULL) {
fgets(cmdline_buf, sizeof(cmdline_buf), cmdline);
fclose(cmdline);
}
if (getuid() == 0) {
if (prctl(PR_SET_KEEPCAPS, 1) < 0) {
ALOGE("prctl(PR_SET_KEEPCAPS) failed: %s\n", strerror(errno));
return -1;
}
/* switch to non-root user and group */
gid_t groups[] = { AID_LOG, AID_SDCARD_RW, AID_MOUNT, AID_INET, AID_NET_BW_STATS };
if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) {
ALOGE("Unable to setgroups, aborting: %s\n", strerror(errno));
return -1;
}
if (setgid(AID_SHELL) != 0) {
ALOGE("Unable to setgid, aborting: %s\n", strerror(errno));
return -1;
}
if (setuid(AID_SHELL) != 0) {
ALOGE("Unable to setuid, aborting: %s\n", strerror(errno));
return -1;
}
struct __user_cap_header_struct capheader;
struct __user_cap_data_struct capdata[2];
memset(&capheader, 0, sizeof(capheader));
memset(&capdata, 0, sizeof(capdata));
capheader.version = _LINUX_CAPABILITY_VERSION_3;
capheader.pid = 0;
capdata[CAP_TO_INDEX(CAP_SYSLOG)].permitted = CAP_TO_MASK(CAP_SYSLOG);
capdata[CAP_TO_INDEX(CAP_SYSLOG)].effective = CAP_TO_MASK(CAP_SYSLOG);
capdata[0].inheritable = 0;
capdata[1].inheritable = 0;
if (capset(&capheader, &capdata[0]) < 0) {
ALOGE("capset failed: %s\n", strerror(errno));
return -1;
}
}
char path[PATH_MAX], tmp_path[PATH_MAX];
pid_t gzip_pid = -1;
if (use_socket) {
redirect_to_socket(stdout, "dumpstate");
} else if (use_outfile) {
strlcpy(path, use_outfile, sizeof(path));
if (do_add_date) {
char date[80];
time_t now = time(NULL);
strftime(date, sizeof(date), "-%Y-%m-%d-%H-%M-%S", localtime(&now));
strlcat(path, date, sizeof(path));
}
if (do_fb) {
strlcpy(screenshot_path, path, sizeof(screenshot_path));
strlcat(screenshot_path, ".png", sizeof(screenshot_path));
}
strlcat(path, ".txt", sizeof(path));
if (do_compress) strlcat(path, ".gz", sizeof(path));
strlcpy(tmp_path, path, sizeof(tmp_path));
strlcat(tmp_path, ".tmp", sizeof(tmp_path));
gzip_pid = redirect_to_file(stdout, tmp_path, do_compress);
}
if (begin_sound) {
play_sound(begin_sound);
} else if (vibrator) {
fputs("150", vibrator);
fflush(vibrator);
}
dumpstate();
if (end_sound) {
play_sound(end_sound);
} else if (vibrator) {
int i;
for (i = 0; i < 3; i++) {
fputs("75\n", vibrator);
fflush(vibrator);
usleep((75 + 50) * 1000);
}
fclose(vibrator);
}
/* wait for gzip to finish, otherwise it might get killed when we exit */
if (gzip_pid > 0) {
fclose(stdout);
waitpid(gzip_pid, NULL, 0);
}
/* rename the (now complete) .tmp file to its final location */
if (use_outfile && rename(tmp_path, path)) {
fprintf(stderr, "rename(%s, %s): %s\n", tmp_path, path, strerror(errno));
}
ALOGI("done\n");
return 0;
}

View File

@ -0,0 +1,62 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _DUMPSTATE_H_
#define _DUMPSTATE_H_
#include <time.h>
#include <unistd.h>
#include <stdio.h>
#define SU_PATH "/system/xbin/su"
/* prints the contents of a file */
int dump_file(const char *title, const char* path);
/* forks a command and waits for it to finish -- terminate args with NULL */
int run_command(const char *title, int timeout_seconds, const char *command, ...);
/* prints all the system properties */
void print_properties();
/* redirect output to a service control socket */
void redirect_to_socket(FILE *redirect, const char *service);
/* redirect output to a file, optionally gzipping; returns gzip pid */
pid_t redirect_to_file(FILE *redirect, char *path, int gzip_level);
/* dump Dalvik stack traces, return the trace file location (NULL if none) */
const char *dump_vm_traces();
/* for each process in the system, run the specified function */
void for_each_pid(void (*func)(int, const char *), const char *header);
/* Displays a blocked processes in-kernel wait channel */
void show_wchan(int pid, const char *name);
/* Runs "showmap" for a process */
void do_showmap(int pid, const char *name);
/* Gets the dmesg output for the kernel */
void do_dmesg();
/* Play a sound via Stagefright */
void play_sound(const char* path);
/* Implemented by libdumpstate_board to dump board-specific info */
void dumpstate_board();
#endif /* _DUMPSTATE_H_ */

470
cmds/dumpstate/utils.c Normal file
View File

@ -0,0 +1,470 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <sys/klog.h>
#include <time.h>
#include <unistd.h>
#include <cutils/properties.h>
#include <cutils/sockets.h>
#include <private/android_filesystem_config.h>
#include "dumpstate.h"
void for_each_pid(void (*func)(int, const char *), const char *header) {
DIR *d;
struct dirent *de;
if (!(d = opendir("/proc"))) {
printf("Failed to open /proc (%s)\n", strerror(errno));
return;
}
printf("\n------ %s ------\n", header);
while ((de = readdir(d))) {
int pid;
int fd;
char cmdpath[255];
char cmdline[255];
if (!(pid = atoi(de->d_name))) {
continue;
}
sprintf(cmdpath,"/proc/%d/cmdline", pid);
memset(cmdline, 0, sizeof(cmdline));
if ((fd = open(cmdpath, O_RDONLY)) < 0) {
strcpy(cmdline, "N/A");
} else {
read(fd, cmdline, sizeof(cmdline));
close(fd);
}
func(pid, cmdline);
}
closedir(d);
}
void show_wchan(int pid, const char *name) {
char path[255];
char buffer[255];
int fd;
memset(buffer, 0, sizeof(buffer));
sprintf(path, "/proc/%d/wchan", pid);
if ((fd = open(path, O_RDONLY)) < 0) {
printf("Failed to open '%s' (%s)\n", path, strerror(errno));
return;
}
if (read(fd, buffer, sizeof(buffer)) < 0) {
printf("Failed to read '%s' (%s)\n", path, strerror(errno));
goto out_close;
}
printf("%-7d %-32s %s\n", pid, name, buffer);
out_close:
close(fd);
return;
}
void do_dmesg() {
printf("------ KERNEL LOG (dmesg) ------\n");
int size = klogctl(10, NULL, 0); /* Get size of kernel buffer */
if (size <= 0) {
printf("Unexpected klogctl return value: %d\n\n", size);
return;
}
char *buf = (char *) malloc(size + 1);
if (buf == NULL) {
printf("memory allocation failed\n\n");
return;
}
int retval = klogctl(KLOG_READ_ALL, buf, size);
if (retval < 0) {
printf("klogctl failure\n\n");
free(buf);
return;
}
buf[retval] = '\0';
printf("%s\n\n", buf);
free(buf);
return;
}
void do_showmap(int pid, const char *name) {
char title[255];
char arg[255];
sprintf(title, "SHOW MAP %d (%s)", pid, name);
sprintf(arg, "%d", pid);
run_command(title, 10, SU_PATH, "root", "showmap", arg, NULL);
}
/* prints the contents of a file */
int dump_file(const char *title, const char* path) {
char buffer[32768];
int fd = open(path, O_RDONLY);
if (fd < 0) {
int err = errno;
if (title) printf("------ %s (%s) ------\n", title, path);
printf("*** %s: %s\n", path, strerror(err));
if (title) printf("\n");
return -1;
}
if (title) printf("------ %s (%s", title, path);
if (title) {
struct stat st;
if (memcmp(path, "/proc/", 6) && memcmp(path, "/sys/", 5) && !fstat(fd, &st)) {
char stamp[80];
time_t mtime = st.st_mtime;
strftime(stamp, sizeof(stamp), "%Y-%m-%d %H:%M:%S", localtime(&mtime));
printf(": %s", stamp);
}
printf(") ------\n");
}
int newline = 0;
for (;;) {
int ret = read(fd, buffer, sizeof(buffer));
if (ret > 0) {
newline = (buffer[ret - 1] == '\n');
ret = fwrite(buffer, ret, 1, stdout);
}
if (ret <= 0) break;
}
close(fd);
if (!newline) printf("\n");
if (title) printf("\n");
return 0;
}
/* forks a command and waits for it to finish */
int run_command(const char *title, int timeout_seconds, const char *command, ...) {
fflush(stdout);
clock_t start = clock();
pid_t pid = fork();
/* handle error case */
if (pid < 0) {
printf("*** fork: %s\n", strerror(errno));
return pid;
}
/* handle child case */
if (pid == 0) {
const char *args[1024] = {command};
size_t arg;
va_list ap;
va_start(ap, command);
if (title) printf("------ %s (%s", title, command);
for (arg = 1; arg < sizeof(args) / sizeof(args[0]); ++arg) {
args[arg] = va_arg(ap, const char *);
if (args[arg] == NULL) break;
if (title) printf(" %s", args[arg]);
}
if (title) printf(") ------\n");
fflush(stdout);
execvp(command, (char**) args);
printf("*** exec(%s): %s\n", command, strerror(errno));
fflush(stdout);
_exit(-1);
}
/* handle parent case */
for (;;) {
int status;
pid_t p = waitpid(pid, &status, WNOHANG);
float elapsed = (float) (clock() - start) / CLOCKS_PER_SEC;
if (p == pid) {
if (WIFSIGNALED(status)) {
printf("*** %s: Killed by signal %d\n", command, WTERMSIG(status));
} else if (WIFEXITED(status) && WEXITSTATUS(status) > 0) {
printf("*** %s: Exit code %d\n", command, WEXITSTATUS(status));
}
if (title) printf("[%s: %.1fs elapsed]\n\n", command, elapsed);
return status;
}
if (timeout_seconds && elapsed > timeout_seconds) {
printf("*** %s: Timed out after %.1fs (killing pid %d)\n", command, elapsed, pid);
kill(pid, SIGTERM);
return -1;
}
usleep(100000); // poll every 0.1 sec
}
}
size_t num_props = 0;
static char* props[2000];
static void print_prop(const char *key, const char *name, void *user) {
(void) user;
if (num_props < sizeof(props) / sizeof(props[0])) {
char buf[PROPERTY_KEY_MAX + PROPERTY_VALUE_MAX + 10];
snprintf(buf, sizeof(buf), "[%s]: [%s]\n", key, name);
props[num_props++] = strdup(buf);
}
}
static int compare_prop(const void *a, const void *b) {
return strcmp(*(char * const *) a, *(char * const *) b);
}
/* prints all the system properties */
void print_properties() {
size_t i;
num_props = 0;
property_list(print_prop, NULL);
qsort(&props, num_props, sizeof(props[0]), compare_prop);
printf("------ SYSTEM PROPERTIES ------\n");
for (i = 0; i < num_props; ++i) {
fputs(props[i], stdout);
free(props[i]);
}
printf("\n");
}
/* redirect output to a service control socket */
void redirect_to_socket(FILE *redirect, const char *service) {
int s = android_get_control_socket(service);
if (s < 0) {
fprintf(stderr, "android_get_control_socket(%s): %s\n", service, strerror(errno));
exit(1);
}
if (listen(s, 4) < 0) {
fprintf(stderr, "listen(control socket): %s\n", strerror(errno));
exit(1);
}
struct sockaddr addr;
socklen_t alen = sizeof(addr);
int fd = accept(s, &addr, &alen);
if (fd < 0) {
fprintf(stderr, "accept(control socket): %s\n", strerror(errno));
exit(1);
}
fflush(redirect);
dup2(fd, fileno(redirect));
close(fd);
}
/* redirect output to a file, optionally gzipping; returns gzip pid (or -1) */
pid_t redirect_to_file(FILE *redirect, char *path, int gzip_level) {
char *chp = path;
/* skip initial slash */
if (chp[0] == '/')
chp++;
/* create leading directories, if necessary */
while (chp && chp[0]) {
chp = strchr(chp, '/');
if (chp) {
*chp = 0;
mkdir(path, 0775); /* drwxrwxr-x */
*chp++ = '/';
}
}
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd < 0) {
fprintf(stderr, "%s: %s\n", path, strerror(errno));
exit(1);
}
pid_t gzip_pid = -1;
if (gzip_level > 0) {
int fds[2];
if (pipe(fds)) {
fprintf(stderr, "pipe: %s\n", strerror(errno));
exit(1);
}
fflush(redirect);
fflush(stdout);
gzip_pid = fork();
if (gzip_pid < 0) {
fprintf(stderr, "fork: %s\n", strerror(errno));
exit(1);
}
if (gzip_pid == 0) {
dup2(fds[0], STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
close(fd);
close(fds[0]);
close(fds[1]);
char level[10];
snprintf(level, sizeof(level), "-%d", gzip_level);
execlp("gzip", "gzip", level, NULL);
fprintf(stderr, "exec(gzip): %s\n", strerror(errno));
_exit(-1);
}
close(fd);
close(fds[0]);
fd = fds[1];
}
dup2(fd, fileno(redirect));
close(fd);
return gzip_pid;
}
/* dump Dalvik stack traces, return the trace file location (NULL if none) */
const char *dump_vm_traces() {
char traces_path[PROPERTY_VALUE_MAX] = "";
property_get("dalvik.vm.stack-trace-file", traces_path, "");
if (!traces_path[0]) return NULL;
/* move the old traces.txt (if any) out of the way temporarily */
char anr_traces_path[PATH_MAX];
strlcpy(anr_traces_path, traces_path, sizeof(anr_traces_path));
strlcat(anr_traces_path, ".anr", sizeof(anr_traces_path));
if (rename(traces_path, anr_traces_path) && errno != ENOENT) {
fprintf(stderr, "rename(%s, %s): %s\n", traces_path, anr_traces_path, strerror(errno));
return NULL; // Can't rename old traces.txt -- no permission? -- leave it alone instead
}
/* make the directory if necessary */
char anr_traces_dir[PATH_MAX];
strlcpy(anr_traces_dir, traces_path, sizeof(anr_traces_dir));
char *slash = strrchr(anr_traces_dir, '/');
if (slash != NULL) {
*slash = '\0';
if (!mkdir(anr_traces_dir, 0775)) {
chown(anr_traces_dir, AID_SYSTEM, AID_SYSTEM);
} else if (errno != EEXIST) {
fprintf(stderr, "mkdir(%s): %s\n", anr_traces_dir, strerror(errno));
return NULL;
}
}
/* create a new, empty traces.txt file to receive stack dumps */
int fd = open(traces_path, O_CREAT | O_WRONLY | O_TRUNC, 0666); /* -rw-rw-rw- */
if (fd < 0) {
fprintf(stderr, "%s: %s\n", traces_path, strerror(errno));
return NULL;
}
close(fd);
/* walk /proc and kill -QUIT all Dalvik processes */
DIR *proc = opendir("/proc");
if (proc == NULL) {
fprintf(stderr, "/proc: %s\n", strerror(errno));
return NULL;
}
/* use inotify to find when processes are done dumping */
int ifd = inotify_init();
if (ifd < 0) {
fprintf(stderr, "inotify_init: %s\n", strerror(errno));
return NULL;
}
int wfd = inotify_add_watch(ifd, traces_path, IN_CLOSE_WRITE);
if (wfd < 0) {
fprintf(stderr, "inotify_add_watch(%s): %s\n", traces_path, strerror(errno));
return NULL;
}
struct dirent *d;
int dalvik_found = 0;
while ((d = readdir(proc))) {
int pid = atoi(d->d_name);
if (pid <= 0) continue;
/* identify Dalvik: /proc/(pid)/exe = /system/bin/app_process */
char path[PATH_MAX], data[PATH_MAX];
snprintf(path, sizeof(path), "/proc/%d/exe", pid);
size_t len = readlink(path, data, sizeof(data) - 1);
if (len <= 0 || memcmp(data, "/system/bin/app_process", 23)) continue;
/* skip zygote -- it won't dump its stack anyway */
snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
int fd = open(path, O_RDONLY);
len = read(fd, data, sizeof(data) - 1);
close(fd);
if (len <= 0 || !memcmp(data, "zygote", 6)) continue;
++dalvik_found;
if (kill(pid, SIGQUIT)) {
fprintf(stderr, "kill(%d, SIGQUIT): %s\n", pid, strerror(errno));
continue;
}
/* wait for the writable-close notification from inotify */
struct pollfd pfd = { ifd, POLLIN, 0 };
int ret = poll(&pfd, 1, 200); /* 200 msec timeout */
if (ret < 0) {
fprintf(stderr, "poll: %s\n", strerror(errno));
} else if (ret == 0) {
fprintf(stderr, "warning: timed out dumping pid %d\n", pid);
} else {
struct inotify_event ie;
read(ifd, &ie, sizeof(ie));
}
}
close(ifd);
if (dalvik_found == 0) {
fprintf(stderr, "Warning: no Dalvik processes found to dump stacks\n");
}
static char dump_traces_path[PATH_MAX];
strlcpy(dump_traces_path, traces_path, sizeof(dump_traces_path));
strlcat(dump_traces_path, ".bugreport", sizeof(dump_traces_path));
if (rename(traces_path, dump_traces_path)) {
fprintf(stderr, "rename(%s, %s): %s\n", traces_path, dump_traces_path, strerror(errno));
return NULL;
}
/* replace the saved [ANR] traces.txt file */
rename(anr_traces_path, traces_path);
return dump_traces_path;
}
void play_sound(const char* path) {
run_command(NULL, 5, "/system/bin/stagefright", "-o", "-a", path, NULL);
}

19
cmds/dumpsys/Android.mk Normal file
View File

@ -0,0 +1,19 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SRC_FILES:= \
dumpsys.cpp
LOCAL_SHARED_LIBRARIES := \
libutils \
libbinder
ifeq ($(TARGET_OS),linux)
LOCAL_CFLAGS += -DXP_UNIX
#LOCAL_SHARED_LIBRARIES += librt
endif
LOCAL_MODULE:= dumpsys
include $(BUILD_EXECUTABLE)

View File

190
cmds/dumpsys/NOTICE Normal file
View File

@ -0,0 +1,190 @@
Copyright (c) 2005-2008, The Android Open Source Project
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

85
cmds/dumpsys/dumpsys.cpp Normal file
View File

@ -0,0 +1,85 @@
/*
* Command that dumps interesting system state to the log.
*
*/
#define LOG_TAG "dumpsys"
#include <utils/Log.h>
#include <binder/Parcel.h>
#include <binder/ProcessState.h>
#include <binder/IServiceManager.h>
#include <utils/TextOutput.h>
#include <utils/Vector.h>
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
using namespace android;
static int sort_func(const String16* lhs, const String16* rhs)
{
return lhs->compare(*rhs);
}
int main(int argc, char* const argv[])
{
sp<IServiceManager> sm = defaultServiceManager();
fflush(stdout);
if (sm == NULL) {
ALOGE("Unable to get default service manager!");
aerr << "dumpsys: Unable to get default service manager!" << endl;
return 20;
}
Vector<String16> services;
Vector<String16> args;
if (argc == 1) {
services = sm->listServices();
services.sort(sort_func);
args.add(String16("-a"));
} else {
services.add(String16(argv[1]));
for (int i=2; i<argc; i++) {
args.add(String16(argv[i]));
}
}
const size_t N = services.size();
if (N > 1) {
// first print a list of the current services
aout << "Currently running services:" << endl;
for (size_t i=0; i<N; i++) {
sp<IBinder> service = sm->checkService(services[i]);
if (service != NULL) {
aout << " " << services[i] << endl;
}
}
}
for (size_t i=0; i<N; i++) {
sp<IBinder> service = sm->checkService(services[i]);
if (service != NULL) {
if (N > 1) {
aout << "------------------------------------------------------------"
"-------------------" << endl;
aout << "DUMP OF SERVICE " << services[i] << ":" << endl;
}
int err = service->dump(STDOUT_FILENO, args);
if (err != 0) {
aerr << "Error dumping service info: (" << strerror(err)
<< ") " << services[i] << endl;
}
} else {
aerr << "Can't find service: " << services[i] << endl;
}
}
return 0;
}