Merge "Change the 64 bit map address format."
diff --git a/adb/adb.cpp b/adb/adb.cpp
index 2c959a4..9c1ead5 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -721,56 +721,50 @@
return 1;
}
- if (!strncmp(service, "forward:",8) ||
- !strncmp(service, "killforward:",12)) {
- char *local, *remote;
- atransport *transport;
-
- int createForward = strncmp(service, "kill", 4);
- int no_rebind = 0;
-
- local = strchr(service, ':') + 1;
-
- // Handle forward:norebind:<local>... here
- if (createForward && !strncmp(local, "norebind:", 9)) {
- no_rebind = 1;
- local = strchr(local, ':') + 1;
+ if (!strncmp(service, "forward:", 8) || !strncmp(service, "killforward:", 12)) {
+ // killforward:local
+ // forward:(norebind:)?local;remote
+ bool kill_forward = false;
+ bool no_rebind = false;
+ if (android::base::StartsWith(service, "killforward:")) {
+ kill_forward = true;
+ service += 12;
+ if (android::base::StartsWith(service, "norebind:")) {
+ no_rebind = true;
+ service += 9;
+ }
+ } else {
+ service += 8;
}
- remote = strchr(local,';');
+ std::vector<std::string> pieces = android::base::Split(service, ";");
- if (createForward) {
- // Check forward: parameter format: '<local>;<remote>'
- if(remote == 0) {
- SendFail(reply_fd, "malformed forward spec");
- return 1;
- }
-
- *remote++ = 0;
- if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')) {
- SendFail(reply_fd, "malformed forward spec");
+ if (kill_forward) {
+ // Check killforward: parameter format: '<local>'
+ if (pieces.size() != 1 || pieces[0].empty()) {
+ SendFail(reply_fd, android::base::StringPrintf("bad killforward: %s", service));
return 1;
}
} else {
- // Check killforward: parameter format: '<local>'
- if (local[0] == 0) {
- SendFail(reply_fd, "malformed forward spec");
+ // Check forward: parameter format: '<local>;<remote>'
+ if (pieces.size() != 2 || pieces[0].empty() || pieces[1].empty() || pieces[1][0] == '*') {
+ SendFail(reply_fd, android::base::StringPrintf("bad forward: %s", service));
return 1;
}
}
std::string error_msg;
- transport = acquire_one_transport(kCsAny, type, serial, &error_msg);
+ atransport* transport = acquire_one_transport(kCsAny, type, serial, &error_msg);
if (!transport) {
SendFail(reply_fd, error_msg);
return 1;
}
InstallStatus r;
- if (createForward) {
- r = install_listener(local, remote, transport, no_rebind);
+ if (kill_forward) {
+ r = remove_listener(pieces[0].c_str(), transport);
} else {
- r = remove_listener(local, transport);
+ r = install_listener(pieces[0], pieces[1].c_str(), transport, no_rebind);
}
if (r == INSTALL_STATUS_OK) {
#if ADB_HOST
@@ -783,7 +777,7 @@
std::string message;
switch (r) {
- case INSTALL_STATUS_OK: message = " "; break;
+ case INSTALL_STATUS_OK: message = "success (!)"; break;
case INSTALL_STATUS_INTERNAL_ERROR: message = "internal error"; break;
case INSTALL_STATUS_CANNOT_BIND:
message = android::base::StringPrintf("cannot bind to socket: %s", strerror(errno));
@@ -791,7 +785,9 @@
case INSTALL_STATUS_CANNOT_REBIND:
message = android::base::StringPrintf("cannot rebind existing socket: %s", strerror(errno));
break;
- case INSTALL_STATUS_LISTENER_NOT_FOUND: message = "listener not found"; break;
+ case INSTALL_STATUS_LISTENER_NOT_FOUND:
+ message = android::base::StringPrintf("listener '%s' not found", service);
+ break;
}
SendFail(reply_fd, message);
return 1;
diff --git a/adb/adb_client.cpp b/adb/adb_client.cpp
index c73d737..ef9a586 100644
--- a/adb/adb_client.cpp
+++ b/adb/adb_client.cpp
@@ -256,19 +256,21 @@
}
-int adb_command(const std::string& service, std::string* error) {
- int fd = adb_connect(service, error);
+bool adb_command(const std::string& service) {
+ std::string error;
+ int fd = adb_connect(service, &error);
if (fd < 0) {
- fprintf(stderr, "error: %s\n", error->c_str());
- return -1;
+ fprintf(stderr, "error: %s\n", error.c_str());
+ return false;
}
- if (!adb_status(fd, error)) {
+ if (!adb_status(fd, &error)) {
+ fprintf(stderr, "error: %s\n", error.c_str());
adb_close(fd);
- return -1;
+ return false;
}
- return 0;
+ return true;
}
bool adb_query(const std::string& service, std::string* result, std::string* error) {
diff --git a/adb/adb_client.h b/adb/adb_client.h
index 9895c49..5de0638 100644
--- a/adb/adb_client.h
+++ b/adb/adb_client.h
@@ -26,9 +26,9 @@
int adb_connect(const std::string& service, std::string* error);
int _adb_connect(const std::string& service, std::string* error);
-// Connect to adb, connect to the named service, return 0 if the connection
-// succeeded AND the service returned OKAY.
-int adb_command(const std::string& service, std::string* error);
+// Connect to adb, connect to the named service, returns true if the connection
+// succeeded AND the service returned OKAY. Outputs any returned error otherwise.
+bool adb_command(const std::string& service);
// Connects to the named adb service and fills 'result' with the response.
// Returns true on success; returns false and fills 'error' on failure.
diff --git a/adb/adb_listeners.cpp b/adb/adb_listeners.cpp
index cf193ab..a335eec 100644
--- a/adb/adb_listeners.cpp
+++ b/adb/adb_listeners.cpp
@@ -26,13 +26,12 @@
int gListenAll = 0; /* Not static because it is used in commandline.c. */
-alistener listener_list = {
+static alistener listener_list = {
.next = &listener_list,
.prev = &listener_list,
};
-void ss_listener_event_func(int _fd, unsigned ev, void *_l)
-{
+static void ss_listener_event_func(int _fd, unsigned ev, void *_l) {
asocket *s;
if(ev & FDE_READ) {
@@ -56,7 +55,7 @@
}
}
-void listener_event_func(int _fd, unsigned ev, void* _l)
+static void listener_event_func(int _fd, unsigned ev, void* _l)
{
alistener* listener = reinterpret_cast<alistener*>(_l);
asocket *s;
@@ -106,38 +105,27 @@
free(l);
}
-void listener_disconnect(void* listener, atransport* t)
-{
+static void listener_disconnect(void* listener, atransport* t) {
free_listener(reinterpret_cast<alistener*>(listener));
}
-int local_name_to_fd(const char *name)
-{
- int port;
-
- if(!strncmp("tcp:", name, 4)){
- int ret;
- port = atoi(name + 4);
-
+static int local_name_to_fd(const char* name) {
+ if (!strncmp("tcp:", name, 4)) {
+ int port = atoi(name + 4);
if (gListenAll > 0) {
- ret = socket_inaddr_any_server(port, SOCK_STREAM);
+ return socket_inaddr_any_server(port, SOCK_STREAM);
} else {
- ret = socket_loopback_server(port, SOCK_STREAM);
+ return socket_loopback_server(port, SOCK_STREAM);
}
-
- return ret;
}
#ifndef HAVE_WIN32_IPC /* no Unix-domain sockets on Win32 */
- // It's non-sensical to support the "reserved" space on the adb host side
- if(!strncmp(name, "local:", 6)) {
- return socket_local_server(name + 6,
- ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
- } else if(!strncmp(name, "localabstract:", 14)) {
- return socket_local_server(name + 14,
- ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
- } else if(!strncmp(name, "localfilesystem:", 16)) {
- return socket_local_server(name + 16,
- ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
+ // It's nonsensical to support the "reserved" space on the adb host side
+ if (!strncmp(name, "local:", 6)) {
+ return socket_local_server(name + 6, ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
+ } else if (!strncmp(name, "localabstract:", 14)) {
+ return socket_local_server(name + 14, ANDROID_SOCKET_NAMESPACE_ABSTRACT, SOCK_STREAM);
+ } else if (!strncmp(name, "localfilesystem:", 16)) {
+ return socket_local_server(name + 16, ANDROID_SOCKET_NAMESPACE_FILESYSTEM, SOCK_STREAM);
}
#endif
diff --git a/adb/adb_listeners.h b/adb/adb_listeners.h
index 9a7ded1..67deb21 100644
--- a/adb/adb_listeners.h
+++ b/adb/adb_listeners.h
@@ -30,12 +30,6 @@
INSTALL_STATUS_LISTENER_NOT_FOUND = -4,
};
-extern alistener listener_list;
-
-void listener_disconnect(void* _l, atransport* t);
-void listener_event_func(int _fd, unsigned ev, void *_l);
-void ss_listener_event_func(int _fd, unsigned ev, void *_l);
-
InstallStatus install_listener(const std::string& local_name,
const char* connect_to,
atransport* transport,
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index d7bee91..7fbca31 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -680,14 +680,7 @@
}
std::string cmd = format_host_command(service, t, serial);
- std::string error;
- if (adb_command(cmd, &error)) {
- D("failure: %s *\n", error.c_str());
- fprintf(stderr,"error: %s\n", error.c_str());
- return false;
- }
-
- return true;
+ return adb_command(cmd);
}
static int send_shell_command(TransportType transport_type, const char* serial,
@@ -1249,90 +1242,50 @@
if (argc != 1) return usage();
return send_shell_command(transport_type, serial, "shell:bugreport");
}
- /* adb_command() wrapper commands */
else if (!strcmp(argv[0], "forward") || !strcmp(argv[0], "reverse")) {
- std::string cmd;
- char host_prefix[64];
- char reverse = (char) !strcmp(argv[0], "reverse");
- char remove = 0;
- char remove_all = 0;
- char list = 0;
- char no_rebind = 0;
-
- // Parse options here.
- while (argc > 1 && argv[1][0] == '-') {
- if (!strcmp(argv[1], "--list"))
- list = 1;
- else if (!strcmp(argv[1], "--remove"))
- remove = 1;
- else if (!strcmp(argv[1], "--remove-all"))
- remove_all = 1;
- else if (!strcmp(argv[1], "--no-rebind"))
- no_rebind = 1;
- else {
- return usage();
- }
- argc--;
- argv++;
- }
-
- // Ensure we can only use one option at a time.
- if (list + remove + remove_all + no_rebind > 1) {
- return usage();
- }
+ bool reverse = !strcmp(argv[0], "reverse");
+ ++argv;
+ --argc;
+ if (argc < 1) return usage();
// Determine the <host-prefix> for this command.
+ std::string host_prefix;
if (reverse) {
- snprintf(host_prefix, sizeof host_prefix, "reverse");
+ host_prefix = "reverse";
} else {
if (serial) {
- snprintf(host_prefix, sizeof host_prefix, "host-serial:%s",
- serial);
+ host_prefix = android::base::StringPrintf("host-serial:%s", serial);
} else if (transport_type == kTransportUsb) {
- snprintf(host_prefix, sizeof host_prefix, "host-usb");
+ host_prefix = "host-usb";
} else if (transport_type == kTransportLocal) {
- snprintf(host_prefix, sizeof host_prefix, "host-local");
+ host_prefix = "host-local";
} else {
- snprintf(host_prefix, sizeof host_prefix, "host");
+ host_prefix = "host";
}
}
- // Implement forward --list
- if (list) {
- if (argc != 1) {
- return usage();
- }
-
- std::string query = android::base::StringPrintf("%s:list-forward", host_prefix);
- return adb_query_command(query);
- }
-
- // Implement forward --remove-all
- else if (remove_all) {
+ std::string cmd;
+ if (strcmp(argv[0], "--list") == 0) {
if (argc != 1) return usage();
- cmd = android::base::StringPrintf("%s:killforward-all", host_prefix);
- }
-
- // Implement forward --remove <local>
- else if (remove) {
+ return adb_query_command(host_prefix + ":list-forward");
+ } else if (strcmp(argv[0], "--remove-all") == 0) {
+ if (argc != 1) return usage();
+ cmd = host_prefix + ":killforward-all";
+ } else if (strcmp(argv[0], "--remove") == 0) {
+ // forward --remove <local>
if (argc != 2) return usage();
- cmd = android::base::StringPrintf("%s:killforward:%s", host_prefix, argv[1]);
- }
- // Or implement one of:
- // forward <local> <remote>
- // forward --no-rebind <local> <remote>
- else {
+ cmd = host_prefix + ":killforward:" + argv[1];
+ } else if (strcmp(argv[0], "--no-rebind") == 0) {
+ // forward --no-rebind <local> <remote>
if (argc != 3) return usage();
- const char* command = no_rebind ? "forward:norebind" : "forward";
- cmd = android::base::StringPrintf("%s:%s:%s;%s", host_prefix, command, argv[1], argv[2]);
+ cmd = host_prefix + ":forward:norebind:" + argv[1] + ";" + argv[2];
+ } else {
+ // forward <local> <remote>
+ if (argc != 2) return usage();
+ cmd = host_prefix + ":forward:" + argv[0] + ";" + argv[1];
}
- std::string error;
- if (adb_command(cmd, &error)) {
- fprintf(stderr, "error: %s\n", error.c_str());
- return 1;
- }
- return 0;
+ return adb_command(cmd) ? 0 : 1;
}
/* do_sync_*() commands */
else if (!strcmp(argv[0], "ls")) {
diff --git a/fastboot/Android.mk b/fastboot/Android.mk
index dee471a..1808042 100644
--- a/fastboot/Android.mk
+++ b/fastboot/Android.mk
@@ -14,6 +14,8 @@
LOCAL_PATH:= $(call my-dir)
+fastboot_version := $(shell git -C $(LOCAL_PATH) rev-parse --short=12 HEAD 2>/dev/null)-android
+
include $(CLEAR_VARS)
LOCAL_C_INCLUDES := $(LOCAL_PATH)/../mkbootimg \
@@ -25,14 +27,15 @@
LOCAL_CONLYFLAGS += -std=gnu99
LOCAL_CFLAGS += -Wall -Wextra -Werror
+LOCAL_CFLAGS += -DFASTBOOT_REVISION='"$(fastboot_version)"'
+
ifeq ($(HOST_OS),linux)
LOCAL_SRC_FILES += usb_linux.c util_linux.c
endif
ifeq ($(HOST_OS),darwin)
LOCAL_SRC_FILES += usb_osx.c util_osx.c
- LOCAL_LDLIBS += -lpthread -framework CoreFoundation -framework IOKit \
- -framework Carbon
+ LOCAL_LDLIBS += -lpthread -framework CoreFoundation -framework IOKit -framework Carbon
LOCAL_CFLAGS += -Wno-unused-parameter
endif
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index 7acfd6e..5ad55d4 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -59,7 +59,6 @@
char cur_product[FB_RESPONSE_SZ + 1];
-static usb_handle *usb = 0;
static const char *serial = 0;
static const char *product = 0;
static const char *cmdline = 0;
@@ -619,7 +618,7 @@
* erase partitions of type ext4 before flashing a filesystem so no stale
* inodes are left lying around. Otherwise, e2fsck gets very upset.
*/
-static int needs_erase(const char *part)
+static int needs_erase(usb_handle* usb, const char *part)
{
/* The function fb_format_supported() currently returns the value
* we want, so just call it.
@@ -733,18 +732,19 @@
setup_requirements(reinterpret_cast<char*>(data), sz);
- for (size_t i = 0; i < ARRAY_SIZE(images); i++) {
+ for (size_t i = 0; i < ARRAY_SIZE(images); ++i) {
int fd = unzip_to_file(zip, images[i].img_name);
- if (fd < 0) {
- if (images[i].is_optional)
+ if (fd == -1) {
+ if (images[i].is_optional) {
continue;
- die("update package missing %s", images[i].img_name);
+ }
+ exit(1); // unzip_to_file already explained why.
}
fastboot_buffer buf;
int rc = load_buf_fd(usb, fd, &buf);
if (rc) die("cannot load %s from flash", images[i].img_name);
do_update_signature(zip, images[i].sig_name);
- if (erase_first && needs_erase(images[i].part_name)) {
+ if (erase_first && needs_erase(usb, images[i].part_name)) {
fb_queue_erase(images[i].part_name);
}
flash_buf(images[i].part_name, &buf);
@@ -799,7 +799,7 @@
die("could not load %s\n", images[i].img_name);
}
do_send_signature(fname);
- if (erase_first && needs_erase(images[i].part_name)) {
+ if (erase_first && needs_erase(usb, images[i].part_name)) {
fb_queue_erase(images[i].part_name);
}
flash_buf(images[i].part_name, &buf);
@@ -867,7 +867,8 @@
return num;
}
-void fb_perform_format(const char *partition, int skip_if_not_supported,
+void fb_perform_format(usb_handle* usb,
+ const char *partition, int skip_if_not_supported,
const char *type_override, const char *size_override)
{
char pTypeBuff[FB_RESPONSE_SZ + 1], pSizeBuff[FB_RESPONSE_SZ + 1];
@@ -971,8 +972,9 @@
{"page_size", required_argument, 0, 'n'},
{"ramdisk_offset", required_argument, 0, 'r'},
{"tags_offset", required_argument, 0, 't'},
- {"help", 0, 0, 'h'},
- {"unbuffered", 0, 0, 0},
+ {"help", no_argument, 0, 'h'},
+ {"unbuffered", no_argument, 0, 0},
+ {"version", no_argument, 0, 0},
{0, 0, 0, 0}
};
@@ -1044,6 +1046,9 @@
if (strcmp("unbuffered", longopts[longindex].name) == 0) {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
+ } else if (strcmp("version", longopts[longindex].name) == 0) {
+ fprintf(stdout, "fastboot version %s\n", FASTBOOT_REVISION);
+ return 0;
}
break;
default:
@@ -1070,7 +1075,7 @@
return 0;
}
- usb = open_device();
+ usb_handle* usb = open_device();
while (argc > 0) {
if(!strcmp(*argv, "getvar")) {
@@ -1112,10 +1117,10 @@
}
if (type_override && !type_override[0]) type_override = NULL;
if (size_override && !size_override[0]) size_override = NULL;
- if (erase_first && needs_erase(argv[1])) {
+ if (erase_first && needs_erase(usb, argv[1])) {
fb_queue_erase(argv[1]);
}
- fb_perform_format(argv[1], 0, type_override, size_override);
+ fb_perform_format(usb, argv[1], 0, type_override, size_override);
skip(2);
} else if(!strcmp(*argv, "signature")) {
require(2);
@@ -1175,7 +1180,7 @@
skip(2);
}
if (fname == 0) die("cannot determine image filename for '%s'", pname);
- if (erase_first && needs_erase(pname)) {
+ if (erase_first && needs_erase(usb, pname)) {
fb_queue_erase(pname);
}
do_flash(usb, pname, fname);
@@ -1230,9 +1235,9 @@
if (wants_wipe) {
fb_queue_erase("userdata");
- fb_perform_format("userdata", 1, NULL, NULL);
+ fb_perform_format(usb, "userdata", 1, NULL, NULL);
fb_queue_erase("cache");
- fb_perform_format("cache", 1, NULL, NULL);
+ fb_perform_format(usb, "cache", 1, NULL, NULL);
}
if (wants_reboot) {
fb_queue_reboot();
diff --git a/include/system/audio.h b/include/system/audio.h
index 8d9ec88..ced2005 100644
--- a/include/system/audio.h
+++ b/include/system/audio.h
@@ -1354,7 +1354,7 @@
}
/* converts device address to string sent to audio HAL via set_parameters */
-static char *audio_device_address_to_parameter(audio_devices_t device, const char *address)
+static inline char *audio_device_address_to_parameter(audio_devices_t device, const char *address)
{
const size_t kSize = AUDIO_DEVICE_MAX_ADDRESS_LEN + sizeof("a2dp_sink_address=");
char param[kSize];
diff --git a/init/init.cpp b/init/init.cpp
index 60fcf64..2500985 100644
--- a/init/init.cpp
+++ b/init/init.cpp
@@ -380,7 +380,8 @@
if ((svc->flags & SVC_EXEC) != 0) {
INFO("SVC_EXEC pid %d (uid %d gid %d+%zu context %s) started; waiting...\n",
- svc->pid, svc->uid, svc->gid, svc->nr_supp_gids, svc->seclabel);
+ svc->pid, svc->uid, svc->gid, svc->nr_supp_gids,
+ svc->seclabel ? : "default");
waiting_for_exec = true;
}
diff --git a/init/init_parser.cpp b/init/init_parser.cpp
index df049ed..f975b6c 100644
--- a/init/init_parser.cpp
+++ b/init/init_parser.cpp
@@ -664,6 +664,7 @@
service* make_exec_oneshot_service(int nargs, char** args) {
// Parse the arguments: exec [SECLABEL [UID [GID]*] --] COMMAND ARGS...
+ // SECLABEL can be a - to denote default
int command_arg = 1;
for (int i = 1; i < nargs; ++i) {
if (strcmp(args[i], "--") == 0) {
@@ -689,7 +690,7 @@
return NULL;
}
- if (command_arg > 2) {
+ if ((command_arg > 2) && strcmp(args[1], "-")) {
svc->seclabel = args[1];
}
if (command_arg > 3) {
diff --git a/init/readme.txt b/init/readme.txt
index 6b9c42d..c213041 100644
--- a/init/readme.txt
+++ b/init/readme.txt
@@ -180,7 +180,7 @@
Fork and execute command with the given arguments. The command starts
after "--" so that an optional security context, user, and supplementary
groups can be provided. No other commands will be run until this one
- finishes.
+ finishes. <seclabel> can be a - to denote default.
export <name> <value>
Set the environment variable <name> equal to <value> in the
diff --git a/libbacktrace/BacktraceCurrent.cpp b/libbacktrace/BacktraceCurrent.cpp
index 95cd4d1..2714d93 100644
--- a/libbacktrace/BacktraceCurrent.cpp
+++ b/libbacktrace/BacktraceCurrent.cpp
@@ -96,7 +96,7 @@
static void SignalHandler(int, siginfo_t*, void* sigcontext) {
ThreadEntry* entry = ThreadEntry::Get(getpid(), gettid(), false);
if (!entry) {
- BACK_LOGW("Unable to find pid %d tid %d information", getpid(), gettid());
+ BACK_LOGE("pid %d, tid %d entry not found", getpid(), gettid());
return;
}
@@ -109,9 +109,14 @@
// the thread run ahead causing problems.
// The number indicates that we are waiting for the second Wake() call
// overall which is made by the thread requesting an unwind.
- entry->Wait(2);
-
- ThreadEntry::Remove(entry);
+ if (entry->Wait(2)) {
+ // Do not remove the entry here because that can result in a deadlock
+ // if the code cannot properly send a signal to the thread under test.
+ entry->Wake();
+ } else {
+ // At this point, it is possible that entry has been freed, so just exit.
+ BACK_LOGE("Timed out waiting for unwind thread to indicate it completed.");
+ }
}
bool BacktraceCurrent::UnwindThread(size_t num_ignore_frames) {
@@ -128,17 +133,15 @@
act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
sigemptyset(&act.sa_mask);
if (sigaction(THREAD_SIGNAL, &act, &oldact) != 0) {
- BACK_LOGW("sigaction failed %s", strerror(errno));
- entry->Unlock();
+ BACK_LOGE("sigaction failed: %s", strerror(errno));
ThreadEntry::Remove(entry);
pthread_mutex_unlock(&g_sigaction_mutex);
return false;
}
if (tgkill(Pid(), Tid(), THREAD_SIGNAL) != 0) {
- BACK_LOGW("tgkill %d failed: %s", Tid(), strerror(errno));
+ BACK_LOGE("tgkill %d failed: %s", Tid(), strerror(errno));
sigaction(THREAD_SIGNAL, &oldact, nullptr);
- entry->Unlock();
ThreadEntry::Remove(entry);
pthread_mutex_unlock(&g_sigaction_mutex);
return false;
@@ -146,17 +149,30 @@
// Wait for the thread to get the ucontext. The number indicates
// that we are waiting for the first Wake() call made by the thread.
- entry->Wait(1);
+ bool wait_completed = entry->Wait(1);
// After the thread has received the signal, allow other unwinders to
// continue.
sigaction(THREAD_SIGNAL, &oldact, nullptr);
pthread_mutex_unlock(&g_sigaction_mutex);
- bool unwind_done = UnwindFromContext(num_ignore_frames, entry->GetUcontext());
+ bool unwind_done = false;
+ if (wait_completed) {
+ unwind_done = UnwindFromContext(num_ignore_frames, entry->GetUcontext());
- // Tell the signal handler to exit and release the entry.
- entry->Wake();
+ // Tell the signal handler to exit and release the entry.
+ entry->Wake();
+
+ // Wait for the thread to indicate it is done with the ThreadEntry.
+ if (!entry->Wait(3)) {
+ // Send a warning, but do not mark as a failure to unwind.
+ BACK_LOGW("Timed out waiting for signal handler to indicate it finished.");
+ }
+ } else {
+ BACK_LOGE("Timed out waiting for signal handler to get ucontext data.");
+ }
+
+ ThreadEntry::Remove(entry);
return unwind_done;
}
diff --git a/libbacktrace/BacktraceLog.h b/libbacktrace/BacktraceLog.h
index 1632ec2..5c39f1c 100644
--- a/libbacktrace/BacktraceLog.h
+++ b/libbacktrace/BacktraceLog.h
@@ -25,4 +25,7 @@
#define BACK_LOGW(format, ...) \
ALOGW("%s: " format, __PRETTY_FUNCTION__, ##__VA_ARGS__)
+#define BACK_LOGE(format, ...) \
+ ALOGE("%s: " format, __PRETTY_FUNCTION__, ##__VA_ARGS__)
+
#endif // _LIBBACKTRACE_BACKTRACE_LOG_H
diff --git a/libbacktrace/ThreadEntry.cpp b/libbacktrace/ThreadEntry.cpp
index e8b60c8..084c1aa 100644
--- a/libbacktrace/ThreadEntry.cpp
+++ b/libbacktrace/ThreadEntry.cpp
@@ -69,7 +69,7 @@
}
void ThreadEntry::Remove(ThreadEntry* entry) {
- pthread_mutex_unlock(&entry->mutex_);
+ entry->Unlock();
pthread_mutex_lock(&ThreadEntry::list_mutex_);
if (--entry->ref_count_ == 0) {
@@ -96,20 +96,24 @@
pthread_cond_destroy(&wait_cond_);
}
-void ThreadEntry::Wait(int value) {
+bool ThreadEntry::Wait(int value) {
timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
- ts.tv_sec += 10;
+ ts.tv_sec += 5;
+ bool wait_completed = true;
pthread_mutex_lock(&wait_mutex_);
while (wait_value_ != value) {
int ret = pthread_cond_timedwait(&wait_cond_, &wait_mutex_, &ts);
if (ret != 0) {
- BACK_LOGW("pthread_cond_timedwait failed: %s", strerror(ret));
+ BACK_LOGW("pthread_cond_timedwait for value %d failed: %s", value, strerror(ret));
+ wait_completed = false;
break;
}
}
pthread_mutex_unlock(&wait_mutex_);
+
+ return wait_completed;
}
void ThreadEntry::Wake() {
diff --git a/libbacktrace/ThreadEntry.h b/libbacktrace/ThreadEntry.h
index 94becf2..11924a3 100644
--- a/libbacktrace/ThreadEntry.h
+++ b/libbacktrace/ThreadEntry.h
@@ -29,7 +29,7 @@
void Wake();
- void Wait(int);
+ bool Wait(int);
void CopyUcontextFromSigcontext(void*);
diff --git a/liblog/log_time.cpp b/liblog/log_time.cpp
index 50742df..9d5ea0e 100644
--- a/liblog/log_time.cpp
+++ b/liblog/log_time.cpp
@@ -22,7 +22,7 @@
#include <log/log_read.h>
-const char log_time::default_format[] = "%m-%d %H:%M:%S.%3q";
+const char log_time::default_format[] = "%m-%d %H:%M:%S.%q";
const timespec log_time::EPOCH = { 0, 0 };
// Add %#q for fractional seconds to standard strptime function
diff --git a/libziparchive/Android.mk b/libziparchive/Android.mk
index 559c48b..a3087ee 100644
--- a/libziparchive/Android.mk
+++ b/libziparchive/Android.mk
@@ -42,8 +42,8 @@
include $(CLEAR_VARS)
LOCAL_CPP_EXTENSION := .cc
LOCAL_SRC_FILES := ${source_files}
-LOCAL_STATIC_LIBRARIES := libutils
-LOCAL_SHARED_LIBRARIES := libz-host liblog libbase
+LOCAL_STATIC_LIBRARIES := libz libutils
+LOCAL_SHARED_LIBRARIES := liblog libbase
LOCAL_MODULE:= libziparchive-host
LOCAL_CFLAGS := -Werror
LOCAL_MULTILIB := both
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index 79c4c53..b2a9f88 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -1008,8 +1008,13 @@
// entry. Note that the call to ftruncate below will change the file size but
// will not allocate space on disk and this call to fallocate will not
// change the file size.
+ // Note: fallocate is only supported by the following filesystems -
+ // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
+ // EOPNOTSUPP error when issued in other filesystems.
+ // Hence, check for the return error code before concluding that the
+ // disk does not have enough space.
result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
- if (result == -1) {
+ if (result == -1 && errno == ENOSPC) {
ALOGW("Zip: unable to allocate space for file to %" PRId64 ": %s",
static_cast<int64_t>(declared_length + current_offset), strerror(errno));
return std::unique_ptr<FileWriter>(nullptr);
diff --git a/logcat/Android.mk b/logcat/Android.mk
index f46a4de..7115f9b 100644
--- a/logcat/Android.mk
+++ b/logcat/Android.mk
@@ -5,7 +5,7 @@
LOCAL_SRC_FILES:= logcat.cpp event.logtags
-LOCAL_SHARED_LIBRARIES := liblog
+LOCAL_SHARED_LIBRARIES := liblog libbase libcutils
LOCAL_MODULE := logcat
diff --git a/logcat/logcat.cpp b/logcat/logcat.cpp
index 2c2d785..6d7740e 100644
--- a/logcat/logcat.cpp
+++ b/logcat/logcat.cpp
@@ -1,29 +1,38 @@
// Copyright 2006-2015 The Android Open Source Project
+#include <arpa/inet.h>
#include <assert.h>
#include <ctype.h>
+#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
+#include <sched.h>
+#include <signal.h>
+#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
-#include <stdarg.h>
#include <string.h>
-#include <signal.h>
-#include <time.h>
-#include <unistd.h>
#include <sys/cdefs.h>
#include <sys/socket.h>
#include <sys/stat.h>
-#include <arpa/inet.h>
+#include <sys/types.h>
+#include <time.h>
+#include <unistd.h>
+#include <memory>
+#include <string>
+
+#include <base/file.h>
+#include <base/strings.h>
+#include <cutils/sched_policy.h>
#include <cutils/sockets.h>
+#include <log/event_tag_map.h>
#include <log/log.h>
#include <log/log_read.h>
-#include <log/logger.h>
#include <log/logd.h>
+#include <log/logger.h>
#include <log/logprint.h>
-#include <log/event_tag_map.h>
#define DEFAULT_MAX_ROTATED_LOGS 4
@@ -202,7 +211,15 @@
g_outFD = STDOUT_FILENO;
} else {
- struct stat statbuf;
+ if (set_sched_policy(0, SP_BACKGROUND) < 0) {
+ fprintf(stderr, "failed to set background scheduling policy\n");
+ }
+
+ struct sched_param param;
+ memset(¶m, 0, sizeof(param));
+ if (sched_setscheduler((pid_t) 0, SCHED_BATCH, ¶m) < 0) {
+ fprintf(stderr, "failed to set to batch scheduler\n");
+ }
g_outFD = openLogFile (g_outputFileName);
@@ -210,6 +227,7 @@
logcat_panic(false, "couldn't open output file");
}
+ struct stat statbuf;
if (fstat(g_outFD, &statbuf) == -1) {
close(g_outFD);
logcat_panic(false, "couldn't get output file stat\n");
@@ -231,7 +249,7 @@
fprintf(stderr, "options include:\n"
" -s Set default filter to silent.\n"
" Like specifying filterspec '*:S'\n"
- " -f <filename> Log to file. Default to stdout\n"
+ " -f <filename> Log to file. Default is stdout\n"
" -r <kbytes> Rotate log every kbytes. Requires -f\n"
" -n <count> Sets max number of rotated logs to <count>, default 4\n"
" -v <format> Sets the log print format, where <format> is:\n\n"
@@ -352,6 +370,86 @@
exit(EXIT_FAILURE);
}
+static const char g_defaultTimeFormat[] = "%m-%d %H:%M:%S.%q";
+
+// Find last logged line in gestalt of all matching existing output files
+static log_time lastLogTime(char *outputFileName) {
+ log_time retval(log_time::EPOCH);
+ if (!outputFileName) {
+ return retval;
+ }
+
+ log_time now(CLOCK_REALTIME);
+
+ std::string directory;
+ char *file = strrchr(outputFileName, '/');
+ if (!file) {
+ directory = ".";
+ file = outputFileName;
+ } else {
+ *file = '\0';
+ directory = outputFileName;
+ *file = '/';
+ ++file;
+ }
+ size_t len = strlen(file);
+ log_time modulo(0, NS_PER_SEC);
+ std::unique_ptr<DIR, int(*)(DIR*)>dir(opendir(directory.c_str()), closedir);
+ struct dirent *dp;
+ while ((dp = readdir(dir.get())) != NULL) {
+ if ((dp->d_type != DT_REG)
+ || strncmp(dp->d_name, file, len)
+ || (dp->d_name[len]
+ && ((dp->d_name[len] != '.')
+ || !isdigit(dp->d_name[len+1])))) {
+ continue;
+ }
+
+ std::string file_name = directory;
+ file_name += "/";
+ file_name += dp->d_name;
+ std::string file;
+ if (!android::base::ReadFileToString(file_name, &file)) {
+ continue;
+ }
+
+ bool found = false;
+ for (const auto& line : android::base::Split(file, "\n")) {
+ log_time t(log_time::EPOCH);
+ char *ep = t.strptime(line.c_str(), g_defaultTimeFormat);
+ if (!ep || (*ep != ' ')) {
+ continue;
+ }
+ // determine the time precision of the logs (eg: msec or usec)
+ for (unsigned long mod = 1UL; mod < modulo.tv_nsec; mod *= 10) {
+ if (t.tv_nsec % (mod * 10)) {
+ modulo.tv_nsec = mod;
+ break;
+ }
+ }
+ // We filter any times later than current as we may not have the
+ // year stored with each log entry. Also, since it is possible for
+ // entries to be recorded out of order (very rare) we select the
+ // maximum we find just in case.
+ if ((t < now) && (t > retval)) {
+ retval = t;
+ found = true;
+ }
+ }
+ // We count on the basename file to be the definitive end, so stop here.
+ if (!dp->d_name[len] && found) {
+ break;
+ }
+ }
+ if (retval == log_time::EPOCH) {
+ return retval;
+ }
+ // tail_time prints matching or higher, round up by the modulo to prevent
+ // a replay of the last entry we have just checked.
+ retval += modulo;
+ return retval;
+}
+
} /* namespace android */
@@ -417,12 +515,11 @@
/* FALLTHRU */
case 'T':
if (strspn(optarg, "0123456789") != strlen(optarg)) {
- char *cp = tail_time.strptime(optarg,
- log_time::default_format);
+ char *cp = tail_time.strptime(optarg, g_defaultTimeFormat);
if (!cp) {
logcat_panic(false,
"-%c \"%s\" not in \"%s\" time format\n",
- ret, optarg, log_time::default_format);
+ ret, optarg, g_defaultTimeFormat);
}
if (*cp) {
char c = *cp;
@@ -545,9 +642,11 @@
break;
case 'f':
+ if ((tail_time == log_time::EPOCH) && (tail_lines != 0)) {
+ tail_time = lastLogTime(optarg);
+ }
// redirect output to a file
g_outputFileName = optarg;
-
break;
case 'r':
diff --git a/logd/Android.mk b/logd/Android.mk
index 73da8dc..615d030 100644
--- a/logd/Android.mk
+++ b/logd/Android.mk
@@ -41,4 +41,15 @@
include $(BUILD_EXECUTABLE)
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := logpersist.start
+LOCAL_MODULE_TAGS := debug
+LOCAL_MODULE_CLASS := EXECUTABLES
+LOCAL_MODULE_PATH := $(bin_dir)
+LOCAL_SRC_FILES := logpersist
+ALL_TOOLS := logpersist.start logpersist.stop logpersist.cat
+LOCAL_POST_INSTALL_CMD := $(hide) $(foreach t,$(filter-out $(LOCAL_MODULE),$(ALL_TOOLS)),ln -sf $(LOCAL_MODULE) $(TARGET_OUT)/bin/$(t);)
+include $(BUILD_PREBUILT)
+
include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 8c0a0be..1da52d8 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -388,7 +388,6 @@
bool kick = false;
bool leading = true;
LogBufferElementLast last;
- log_time start(log_time::EPOCH);
for(it = mLogElements.begin(); it != mLogElements.end();) {
LogBufferElement *e = *it;
@@ -417,8 +416,6 @@
continue;
}
- leading = false;
-
if (hasBlacklist && mPrune.naughty(e)) {
last.clear(e);
it = erase(it);
@@ -448,29 +445,24 @@
}
if (e->getUid() != worst) {
- if (start != log_time::EPOCH) {
+ if (leading) {
static const timespec too_old = {
EXPIRE_HOUR_THRESHOLD * 60 * 60, 0
};
- start = e->getRealTime() + too_old;
+ LogBufferElementCollection::iterator last;
+ last = mLogElements.end();
+ --last;
+ if ((e->getRealTime() < ((*last)->getRealTime() - too_old))
+ || (e->getRealTime() > (*last)->getRealTime())) {
+ break;
+ }
}
+ leading = false;
last.clear(e);
++it;
continue;
}
- if ((start != log_time::EPOCH) && (e->getRealTime() > start)) {
- // KISS. Really a heuristic rather than algorithmically strong,
- // a crude mechanism, the following loops will move the oldest
- // watermark possibly wiping out the extra EXPIRE_HOUR_THRESHOLD
- // we just thought we were preserving. We count on the typical
- // pruneRows of 10% of total not being a sledgehammer.
- // A stronger algorithm would have us loop back to the top if
- // we have worst-UID enabled and we start expiring messages
- // below less than EXPIRE_HOUR_THRESHOLD old.
- break;
- }
-
pruneRows--;
if (pruneRows == 0) {
break;
@@ -479,15 +471,21 @@
kick = true;
unsigned short len = e->getMsgLen();
- stats.drop(e);
- e->setDropped(1);
- if (last.merge(e, 1)) {
- it = mLogElements.erase(it);
- stats.erase(e);
- delete e;
+
+ // do not create any leading drops
+ if (leading) {
+ it = erase(it);
} else {
- last.add(e);
- ++it;
+ stats.drop(e);
+ e->setDropped(1);
+ if (last.merge(e, 1)) {
+ it = mLogElements.erase(it);
+ stats.erase(e);
+ delete e;
+ } else {
+ last.add(e);
+ ++it;
+ }
}
if (worst_sizes < second_worst_sizes) {
break;
@@ -526,7 +524,7 @@
break;
}
- if (hasWhitelist && mPrune.nice(e)) { // WhiteListed
+ if (hasWhitelist && !e->getDropped() && mPrune.nice(e)) { // WhiteListed
whitelist = true;
it++;
continue;
diff --git a/logd/README.property b/logd/README.property
index ad7d0cd..a472efd 100644
--- a/logd/README.property
+++ b/logd/README.property
@@ -10,6 +10,8 @@
default false
ro.build.type string if user, logd.statistics & logd.klogd
default false
+persist.logd.logpersistd string Enable logpersist daemon, "logcatd"
+ turns on logcat -f in logd context
persist.logd.size number 256K default size of the buffer for all
log ids at initial startup, at runtime
use: logcat -b all -G <value>
diff --git a/logd/logpersist b/logd/logpersist
new file mode 100755
index 0000000..215e1e2
--- /dev/null
+++ b/logd/logpersist
@@ -0,0 +1,36 @@
+#! /system/bin/sh
+# logpersist cat start and stop handlers
+data=/data/misc/logd
+property=persist.logd.logpersistd
+service=logcatd
+progname="${0##*/}"
+if [ X"${1}" = "-h" -o X"${1}" = X"--help" ]; then
+ echo "${progname%.*}.cat - dump current ${service%d} logs"
+ echo "${progname%.*}.start - start ${service} service"
+ echo "${progname%.*}.stop [--clear] - stop ${service} service"
+ exit 0
+fi
+case ${progname} in
+*.cat)
+ su 1036 ls "${data}" |
+ tr -d '\r' |
+ sort -ru |
+ sed "s#^#${data}/#" |
+ su 1036 xargs cat
+ ;;
+*.start)
+ su 0 setprop ${property} ${service}
+ getprop ${property}
+ sleep 1
+ ps -t | grep "${data##*/}.*${service%d}"
+ ;;
+*.stop)
+ su 0 stop ${service}
+ su 0 setprop ${property} ""
+ [ X"${1}" != X"-c" -a X"${1}" != X"--clear" ] ||
+ ( sleep 1 ; su 1036,9998 rm -rf "${data}" )
+ ;;
+*)
+ echo "Unexpected command ${0##*/} ${@}" >&2
+ exit 1
+esac
diff --git a/logd/tests/logd_test.cpp b/logd/tests/logd_test.cpp
index 46bd9c0..3266360 100644
--- a/logd/tests/logd_test.cpp
+++ b/logd/tests/logd_test.cpp
@@ -93,53 +93,42 @@
static char *find_benchmark_spam(char *cp)
{
// liblog_benchmarks has been run designed to SPAM. The signature of
- // a noisiest UID statistics is one of the following:
+ // a noisiest UID statistics is:
//
- // main: UID/PID Total size/num Now UID/PID[?] Total
- // 0 7500306/304207 71608/3183 0/4225? 7454388/303656
- // <wrap> 93432/1012
- // -or-
- // 0/gone 7454388/303656 93432/1012
+ // Chattiest UIDs in main log buffer: Size Pruned
+ // UID PACKAGE BYTES LINES
+ // 0 root 54164 147569
//
- // basically if we see a *large* number of 0/????? entries
- unsigned long value;
+ char *benchmark = NULL;
do {
- char *benchmark = strstr(cp, " 0/");
- char *benchmark_newline = strstr(cp, "\n0/");
+ static const char signature[] = "\n0 root ";
+
+ benchmark = strstr(cp, signature);
if (!benchmark) {
- benchmark = benchmark_newline;
- }
- if (benchmark_newline && (benchmark > benchmark_newline)) {
- benchmark = benchmark_newline;
- }
- cp = benchmark;
- if (!cp) {
break;
}
- cp += 3;
- while (isdigit(*cp) || (*cp == 'g') || (*cp == 'o') || (*cp == 'n')) {
+ cp = benchmark + sizeof(signature);
+ while (isspace(*cp)) {
++cp;
}
- value = 0;
- // ###? or gone
- if ((*cp == '?') || (*cp == 'e')) {
- while (*++cp == ' ');
- while (isdigit(*cp)) {
- value = value * 10ULL + *cp - '0';
- ++cp;
- }
- if (*cp != '/') {
- value = 0;
- continue;
- }
- while (isdigit(*++cp));
- while (*cp == ' ') ++cp;
- if (!isdigit(*cp)) {
- value = 0;
- }
+ benchmark = cp;
+ while (isdigit(*cp)) {
+ ++cp;
}
- } while ((value < 900000ULL) && *cp);
- return cp;
+ while (isspace(*cp)) {
+ ++cp;
+ }
+ unsigned long value = 0;
+ while (isdigit(*cp)) {
+ value = value * 10ULL + *cp - '0';
+ ++cp;
+ }
+ if (value > 100000UL) {
+ break;
+ }
+ benchmark = NULL;
+ } while (*cp);
+ return benchmark;
}
TEST(logd, statistics) {
@@ -179,16 +168,16 @@
EXPECT_EQ(0, truncated);
#ifdef TARGET_USES_LOGD
- char *main_logs = strstr(cp, "\nmain:");
+ char *main_logs = strstr(cp, "\nChattiest UIDs in main ");
EXPECT_TRUE(NULL != main_logs);
- char *radio_logs = strstr(cp, "\nradio:");
+ char *radio_logs = strstr(cp, "\nChattiest UIDs in radio ");
EXPECT_TRUE(NULL != radio_logs);
- char *system_logs = strstr(cp, "\nsystem:");
+ char *system_logs = strstr(cp, "\nChattiest UIDs in system ");
EXPECT_TRUE(NULL != system_logs);
- char *events_logs = strstr(cp, "\nevents:");
+ char *events_logs = strstr(cp, "\nChattiest UIDs in events ");
EXPECT_TRUE(NULL != events_logs);
#endif
@@ -431,13 +420,13 @@
}
#ifdef TARGET_USES_LOGD
- EXPECT_GE(100000UL, ns[log_maximum_retry]); // 42777 user
+ EXPECT_GE(200000UL, ns[log_maximum_retry]); // 104734 user
#else
EXPECT_GE(10000UL, ns[log_maximum_retry]); // 5636 kernel
#endif
#ifdef TARGET_USES_LOGD
- EXPECT_GE(30000UL, ns[log_maximum]); // 27305 user
+ EXPECT_GE(90000UL, ns[log_maximum]); // 46913 user
#else
EXPECT_GE(10000UL, ns[log_maximum]); // 5637 kernel
#endif
@@ -445,13 +434,13 @@
EXPECT_GE(4096UL, ns[clock_overhead]); // 4095
#ifdef TARGET_USES_LOGD
- EXPECT_GE(250000UL, ns[log_overhead]); // 121876 user
+ EXPECT_GE(250000UL, ns[log_overhead]); // 126886 user
#else
EXPECT_GE(100000UL, ns[log_overhead]); // 50945 kernel
#endif
#ifdef TARGET_USES_LOGD
- EXPECT_GE(7500UL, ns[log_latency]); // 3718 user space
+ EXPECT_GE(10000UL, ns[log_latency]); // 5669 user space
#else
EXPECT_GE(500000UL, ns[log_latency]); // 254200 kernel
#endif
@@ -483,8 +472,7 @@
ASSERT_TRUE(benchmark_statistics_found != NULL);
// Check how effective the SPAM filter is, parse out Now size.
- // Total Now
- // 0/4225? 7454388/303656 31488/755
+ // 0 root 54164 147569
// ^-- benchmark_statistics_found
unsigned long nowSpamSize = atol(benchmark_statistics_found);
diff --git a/mkbootimg/Android.mk b/mkbootimg/Android.mk
index 0c9b0c6..8661d7d 100644
--- a/mkbootimg/Android.mk
+++ b/mkbootimg/Android.mk
@@ -2,12 +2,10 @@
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
-LOCAL_SRC_FILES := mkbootimg.c
-LOCAL_STATIC_LIBRARIES := libmincrypt
-LOCAL_CFLAGS := -Werror
+LOCAL_SRC_FILES := mkbootimg
+LOCAL_MODULE_CLASS := EXECUTABLES
+LOCAL_IS_HOST_MODULE := true
LOCAL_MODULE := mkbootimg
-include $(BUILD_HOST_EXECUTABLE)
-
-$(call dist-for-goals,dist_files,$(LOCAL_BUILT_MODULE))
+include $(BUILD_PREBUILT)
diff --git a/mkbootimg/mkbootimg b/mkbootimg/mkbootimg
new file mode 100755
index 0000000..1e09f4d
--- /dev/null
+++ b/mkbootimg/mkbootimg
@@ -0,0 +1,140 @@
+#!/usr/bin/env python
+# Copyright 2015, 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.
+
+from __future__ import print_function
+from sys import argv, exit, stderr
+from argparse import ArgumentParser, FileType, Action
+from os import fstat
+from struct import pack
+from hashlib import sha1
+
+def filesize(f):
+ if f is None:
+ return 0
+ try:
+ return fstat(f.fileno()).st_size
+ except OSError:
+ return 0
+
+
+def update_sha(sha, f):
+ if f:
+ sha.update(f.read())
+ f.seek(0)
+ sha.update(pack('I', filesize(f)))
+ else:
+ sha.update(pack('I', 0))
+
+
+def pad_file(f, padding):
+ pad = (padding - (f.tell() & (padding - 1))) & (padding - 1)
+ f.write(pack(str(pad) + 'x'))
+
+
+def write_header(args):
+ BOOT_MAGIC = 'ANDROID!'.encode()
+ args.output.write(pack('8s', BOOT_MAGIC))
+ args.output.write(pack('8I',
+ filesize(args.kernel), # size in bytes
+ args.base + args.kernel_offset, # physical load addr
+ filesize(args.ramdisk), # size in bytes
+ args.base + args.ramdisk_offset, # physical load addr
+ filesize(args.second), # size in bytes
+ args.base + args.second_offset, # physical load addr
+ args.base + args.tags_offset, # physical addr for kernel tags
+ args.pagesize)) # flash page size we assume
+ args.output.write(pack('8x')) # future expansion: should be 0
+ args.output.write(pack('16s', args.board.encode())) # asciiz product name
+ args.output.write(pack('512s', args.cmdline[:512].encode()))
+
+ sha = sha1()
+ update_sha(sha, args.kernel)
+ update_sha(sha, args.ramdisk)
+ update_sha(sha, args.second)
+ img_id = pack('32s', sha.digest())
+
+ args.output.write(img_id)
+ args.output.write(pack('1024s', args.cmdline[512:].encode()))
+ pad_file(args.output, args.pagesize)
+ return img_id
+
+
+class ValidateStrLenAction(Action):
+ def __init__(self, option_strings, dest, nargs=None, **kwargs):
+ if 'maxlen' not in kwargs:
+ raise ValueError('maxlen must be set')
+ self.maxlen = int(kwargs['maxlen'])
+ del kwargs['maxlen']
+ super(ValidateStrLenAction, self).__init__(option_strings, dest, **kwargs)
+
+ def __call__(self, parser, namespace, values, option_string=None):
+ if len(values) > self.maxlen:
+ raise ValueError('String argument too long: max {0:d}, got {1:d}'.
+ format(self.maxlen, len(values)))
+ setattr(namespace, self.dest, values)
+
+
+def write_padded_file(f_out, f_in, padding):
+ if f_in is None:
+ return
+ f_out.write(f_in.read())
+ pad_file(f_out, padding)
+
+
+def parse_int(x):
+ return int(x,0)
+
+
+def parse_cmdline():
+ parser = ArgumentParser()
+ parser.add_argument('--kernel', help='path to the kernel', type=FileType('rb'),
+ required=True)
+ parser.add_argument('--ramdisk', help='path to the ramdisk', type=FileType('rb'))
+ parser.add_argument('--second', help='path to the 2nd bootloader', type=FileType('rb'))
+ parser.add_argument('--cmdline', help='extra arguments to be passed on the '
+ 'kernel command line', default='', action=ValidateStrLenAction, maxlen=1536)
+ parser.add_argument('--base', help='base address', type=parse_int, default=0x10000000)
+ parser.add_argument('----kernel_offset', help='kernel offset', type=parse_int, default=0x00008000)
+ parser.add_argument('--ramdisk_offset', help='ramdisk offset', type=parse_int, default=0x01000000)
+ parser.add_argument('--second_offset', help='2nd bootloader offset', type=parse_int,
+ default=0x00f00000)
+ parser.add_argument('--tags_offset', help='tags offset', type=parse_int, default=0x00000100)
+ parser.add_argument('--board', help='board name', default='', action=ValidateStrLenAction,
+ maxlen=16)
+ parser.add_argument('--pagesize', help='page size', type=parse_int,
+ choices=[2**i for i in range(11,15)], default=2048)
+ parser.add_argument('--id', help='print the image ID on standard output',
+ action='store_true')
+ parser.add_argument('-o', '--output', help='output file name', type=FileType('wb'),
+ required=True)
+ return parser.parse_args()
+
+
+def write_data(args):
+ write_padded_file(args.output, args.kernel, args.pagesize)
+ write_padded_file(args.output, args.ramdisk, args.pagesize)
+ write_padded_file(args.output, args.second, args.pagesize)
+
+
+def main():
+ args = parse_cmdline()
+ img_id = write_header(args)
+ write_data(args)
+ if args.id:
+ print('0x' + ''.join('{:02x}'.format(ord(c)) for c in img_id))
+
+
+if __name__ == '__main__':
+ main()
diff --git a/mkbootimg/mkbootimg.c b/mkbootimg/mkbootimg.c
deleted file mode 100644
index 40e5261..0000000
--- a/mkbootimg/mkbootimg.c
+++ /dev/null
@@ -1,297 +0,0 @@
-/* tools/mkbootimg/mkbootimg.c
-**
-** Copyright 2007, 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 <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <stdbool.h>
-
-#include "mincrypt/sha.h"
-#include "bootimg.h"
-
-static void *load_file(const char *fn, unsigned *_sz)
-{
- char *data;
- int sz;
- int fd;
-
- data = 0;
- fd = open(fn, O_RDONLY);
- if(fd < 0) return 0;
-
- sz = lseek(fd, 0, SEEK_END);
- if(sz < 0) goto oops;
-
- if(lseek(fd, 0, SEEK_SET) != 0) goto oops;
-
- data = (char*) malloc(sz);
- if(data == 0) goto oops;
-
- if(read(fd, data, sz) != sz) goto oops;
- close(fd);
-
- if(_sz) *_sz = sz;
- return data;
-
-oops:
- close(fd);
- if(data != 0) free(data);
- return 0;
-}
-
-int usage(void)
-{
- fprintf(stderr,"usage: mkbootimg\n"
- " --kernel <filename>\n"
- " --ramdisk <filename>\n"
- " [ --second <2ndbootloader-filename> ]\n"
- " [ --cmdline <kernel-commandline> ]\n"
- " [ --board <boardname> ]\n"
- " [ --base <address> ]\n"
- " [ --pagesize <pagesize> ]\n"
- " [ --id ]\n"
- " -o|--output <filename>\n"
- );
- return 1;
-}
-
-
-
-static unsigned char padding[16384] = { 0, };
-
-static void print_id(const uint8_t *id, size_t id_len) {
- printf("0x");
- for (unsigned i = 0; i < id_len; i++) {
- printf("%02x", id[i]);
- }
- printf("\n");
-}
-
-int write_padding(int fd, unsigned pagesize, unsigned itemsize)
-{
- unsigned pagemask = pagesize - 1;
- ssize_t count;
-
- if((itemsize & pagemask) == 0) {
- return 0;
- }
-
- count = pagesize - (itemsize & pagemask);
-
- if(write(fd, padding, count) != count) {
- return -1;
- } else {
- return 0;
- }
-}
-
-int main(int argc, char **argv)
-{
- boot_img_hdr hdr;
-
- char *kernel_fn = NULL;
- void *kernel_data = NULL;
- char *ramdisk_fn = NULL;
- void *ramdisk_data = NULL;
- char *second_fn = NULL;
- void *second_data = NULL;
- char *cmdline = "";
- char *bootimg = NULL;
- char *board = "";
- uint32_t pagesize = 2048;
- int fd;
- SHA_CTX ctx;
- const uint8_t* sha;
- uint32_t base = 0x10000000U;
- uint32_t kernel_offset = 0x00008000U;
- uint32_t ramdisk_offset = 0x01000000U;
- uint32_t second_offset = 0x00f00000U;
- uint32_t tags_offset = 0x00000100U;
- size_t cmdlen;
-
- argc--;
- argv++;
-
- memset(&hdr, 0, sizeof(hdr));
-
- bool get_id = false;
- while(argc > 0){
- char *arg = argv[0];
- if (!strcmp(arg, "--id")) {
- get_id = true;
- argc -= 1;
- argv += 1;
- } else if(argc >= 2) {
- char *val = argv[1];
- argc -= 2;
- argv += 2;
- if(!strcmp(arg, "--output") || !strcmp(arg, "-o")) {
- bootimg = val;
- } else if(!strcmp(arg, "--kernel")) {
- kernel_fn = val;
- } else if(!strcmp(arg, "--ramdisk")) {
- ramdisk_fn = val;
- } else if(!strcmp(arg, "--second")) {
- second_fn = val;
- } else if(!strcmp(arg, "--cmdline")) {
- cmdline = val;
- } else if(!strcmp(arg, "--base")) {
- base = strtoul(val, 0, 16);
- } else if(!strcmp(arg, "--kernel_offset")) {
- kernel_offset = strtoul(val, 0, 16);
- } else if(!strcmp(arg, "--ramdisk_offset")) {
- ramdisk_offset = strtoul(val, 0, 16);
- } else if(!strcmp(arg, "--second_offset")) {
- second_offset = strtoul(val, 0, 16);
- } else if(!strcmp(arg, "--tags_offset")) {
- tags_offset = strtoul(val, 0, 16);
- } else if(!strcmp(arg, "--board")) {
- board = val;
- } else if(!strcmp(arg,"--pagesize")) {
- pagesize = strtoul(val, 0, 10);
- if ((pagesize != 2048) && (pagesize != 4096)
- && (pagesize != 8192) && (pagesize != 16384)) {
- fprintf(stderr,"error: unsupported page size %d\n", pagesize);
- return -1;
- }
- } else {
- return usage();
- }
- } else {
- return usage();
- }
- }
- hdr.page_size = pagesize;
-
- hdr.kernel_addr = base + kernel_offset;
- hdr.ramdisk_addr = base + ramdisk_offset;
- hdr.second_addr = base + second_offset;
- hdr.tags_addr = base + tags_offset;
-
- if(bootimg == 0) {
- fprintf(stderr,"error: no output filename specified\n");
- return usage();
- }
-
- if(kernel_fn == 0) {
- fprintf(stderr,"error: no kernel image specified\n");
- return usage();
- }
-
- if(ramdisk_fn == 0) {
- fprintf(stderr,"error: no ramdisk image specified\n");
- return usage();
- }
-
- if(strlen(board) >= BOOT_NAME_SIZE) {
- fprintf(stderr,"error: board name too large\n");
- return usage();
- }
-
- strcpy((char *) hdr.name, board);
-
- memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);
-
- cmdlen = strlen(cmdline);
- if(cmdlen > (BOOT_ARGS_SIZE + BOOT_EXTRA_ARGS_SIZE - 2)) {
- fprintf(stderr,"error: kernel commandline too large\n");
- return 1;
- }
- /* Even if we need to use the supplemental field, ensure we
- * are still NULL-terminated */
- strncpy((char *)hdr.cmdline, cmdline, BOOT_ARGS_SIZE - 1);
- hdr.cmdline[BOOT_ARGS_SIZE - 1] = '\0';
- if (cmdlen >= (BOOT_ARGS_SIZE - 1)) {
- cmdline += (BOOT_ARGS_SIZE - 1);
- strncpy((char *)hdr.extra_cmdline, cmdline, BOOT_EXTRA_ARGS_SIZE);
- }
-
- kernel_data = load_file(kernel_fn, &hdr.kernel_size);
- if(kernel_data == 0) {
- fprintf(stderr,"error: could not load kernel '%s'\n", kernel_fn);
- return 1;
- }
-
- if(!strcmp(ramdisk_fn,"NONE")) {
- ramdisk_data = 0;
- hdr.ramdisk_size = 0;
- } else {
- ramdisk_data = load_file(ramdisk_fn, &hdr.ramdisk_size);
- if(ramdisk_data == 0) {
- fprintf(stderr,"error: could not load ramdisk '%s'\n", ramdisk_fn);
- return 1;
- }
- }
-
- if(second_fn) {
- second_data = load_file(second_fn, &hdr.second_size);
- if(second_data == 0) {
- fprintf(stderr,"error: could not load secondstage '%s'\n", second_fn);
- return 1;
- }
- }
-
- /* put a hash of the contents in the header so boot images can be
- * differentiated based on their first 2k.
- */
- SHA_init(&ctx);
- SHA_update(&ctx, kernel_data, hdr.kernel_size);
- SHA_update(&ctx, &hdr.kernel_size, sizeof(hdr.kernel_size));
- SHA_update(&ctx, ramdisk_data, hdr.ramdisk_size);
- SHA_update(&ctx, &hdr.ramdisk_size, sizeof(hdr.ramdisk_size));
- SHA_update(&ctx, second_data, hdr.second_size);
- SHA_update(&ctx, &hdr.second_size, sizeof(hdr.second_size));
- sha = SHA_final(&ctx);
- memcpy(hdr.id, sha,
- SHA_DIGEST_SIZE > sizeof(hdr.id) ? sizeof(hdr.id) : SHA_DIGEST_SIZE);
-
- fd = open(bootimg, O_CREAT | O_TRUNC | O_WRONLY, 0644);
- if(fd < 0) {
- fprintf(stderr,"error: could not create '%s'\n", bootimg);
- return 1;
- }
-
- if(write(fd, &hdr, sizeof(hdr)) != sizeof(hdr)) goto fail;
- if(write_padding(fd, pagesize, sizeof(hdr))) goto fail;
-
- if(write(fd, kernel_data, hdr.kernel_size) != (ssize_t) hdr.kernel_size) goto fail;
- if(write_padding(fd, pagesize, hdr.kernel_size)) goto fail;
-
- if(write(fd, ramdisk_data, hdr.ramdisk_size) != (ssize_t) hdr.ramdisk_size) goto fail;
- if(write_padding(fd, pagesize, hdr.ramdisk_size)) goto fail;
-
- if(second_data) {
- if(write(fd, second_data, hdr.second_size) != (ssize_t) hdr.second_size) goto fail;
- if(write_padding(fd, pagesize, hdr.second_size)) goto fail;
- }
-
- if (get_id) {
- print_id((uint8_t *) hdr.id, sizeof(hdr.id));
- }
-
- return 0;
-
-fail:
- unlink(bootimg);
- close(fd);
- fprintf(stderr,"error: failed writing '%s': %s\n", bootimg,
- strerror(errno));
- return 1;
-}
diff --git a/rootdir/init.rc b/rootdir/init.rc
index 0966038..1f421c5 100644
--- a/rootdir/init.rc
+++ b/rootdir/init.rc
@@ -649,3 +649,17 @@
class late_start
user root
oneshot
+
+on property:persist.logd.logpersistd=logcatd
+ # all exec/services are called with umask(077), so no gain beyond 0700
+ mkdir /data/misc/logd 0700 logd log
+ # logd for write to /data/misc/logd, log group for read from pstore (-L)
+ exec - logd log -- /system/bin/logcat -L -b all -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 64 -n 256
+ start logcatd
+
+service logcatd /system/bin/logcat -b all -v threadtime -v usec -v printable -D -f /data/misc/logd/logcat -r 64 -n 256
+ class late_start
+ disabled
+ # logd for write to /data/misc/logd, log group for read from log daemon
+ user logd
+ group log
diff --git a/rootdir/init.trace.rc b/rootdir/init.trace.rc
index cd8d350..50944e6 100644
--- a/rootdir/init.trace.rc
+++ b/rootdir/init.trace.rc
@@ -1,6 +1,6 @@
## Permissions to allow system-wide tracing to the kernel trace buffer.
##
-on early-boot
+on boot
# Allow writing to the kernel trace log.
chmod 0222 /sys/kernel/debug/tracing/trace_marker