Merge "metricsd: Relicense as Apache 2."
diff --git a/.gitignore b/.gitignore
index b25c15b..2f836aa 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,2 @@
*~
+*.pyc
diff --git a/adb/adb.cpp b/adb/adb.cpp
index dd6c555..dd1868b 100644
--- a/adb/adb.cpp
+++ b/adb/adb.cpp
@@ -71,6 +71,14 @@
#endif
}
+std::string adb_version() {
+ // Don't change the format of this --- it's parsed by ddmlib.
+ return android::base::StringPrintf("Android Debug Bridge version %d.%d.%d\n"
+ "Revision %s\n",
+ ADB_VERSION_MAJOR, ADB_VERSION_MINOR, ADB_SERVER_VERSION,
+ ADB_REVISION);
+}
+
void fatal(const char *fmt, ...) {
va_list ap;
va_start(ap, fmt);
@@ -192,21 +200,20 @@
}
void adb_trace_init(char** argv) {
+#if !ADB_HOST
// Don't open log file if no tracing, since this will block
// the crypto unmount of /data
- const std::string trace_setting = get_trace_setting();
- if (trace_setting.empty()) {
- return;
- }
-
-#if !ADB_HOST
- if (isatty(STDOUT_FILENO) == 0) {
- start_device_log();
+ if (!get_trace_setting().empty()) {
+ if (isatty(STDOUT_FILENO) == 0) {
+ start_device_log();
+ }
}
#endif
setup_trace_mask();
android::base::InitLogging(argv, AdbLogger);
+
+ D("%s", adb_version().c_str());
}
apacket* get_apacket(void)
@@ -630,7 +637,7 @@
ZeroMemory( &startup, sizeof(startup) );
startup.cb = sizeof(startup);
startup.hStdInput = nul_read;
- startup.hStdOutput = pipe_write;
+ startup.hStdOutput = nul_write;
startup.hStdError = nul_write;
startup.dwFlags = STARTF_USESTDHANDLES;
@@ -645,9 +652,23 @@
SystemErrorCodeToString(GetLastError()).c_str());
return -1;
}
+
+ // Verify that the pipe_write handle value can be passed on the command line
+ // as %d and that the rest of adb code can pass it around in an int.
+ const int pipe_write_as_int = cast_handle_to_int(pipe_write);
+ if (cast_int_to_handle(pipe_write_as_int) != pipe_write) {
+ // If this fires, either handle values are larger than 32-bits or else
+ // there is a bug in our casting.
+ // https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
+ fprintf(stderr, "CreatePipe handle value too large: 0x%p\n",
+ pipe_write);
+ return -1;
+ }
+
WCHAR args[64];
snwprintf(args, arraysize(args),
- L"adb -P %d fork-server server", server_port);
+ L"adb -P %d fork-server server --reply-fd %d", server_port,
+ pipe_write_as_int);
ret = CreateProcessW(
program_path, /* program path */
args,
diff --git a/adb/adb.h b/adb/adb.h
index b0e53f0..016cb11 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -46,6 +46,8 @@
#define ADB_VERSION_MAJOR 1
#define ADB_VERSION_MINOR 0
+std::string adb_version();
+
// Increment this when we want to force users to start a new adb server.
#define ADB_SERVER_VERSION 32
diff --git a/adb/client/main.cpp b/adb/client/main.cpp
index af3a6a1..7469744 100644
--- a/adb/client/main.cpp
+++ b/adb/client/main.cpp
@@ -88,13 +88,8 @@
DWORD nchars = GetTempPathW(arraysize(temp_path), temp_path);
if ((nchars >= arraysize(temp_path)) || (nchars == 0)) {
// If string truncation or some other error.
- // TODO(danalbert): Log the error message from
- // FormatMessage(GetLastError()). Pure Windows APIs only touch
- // GetLastError(), C Runtime APIs touch errno, so maybe there should be
- // WPLOG or PLOGW (which would read GetLastError() instead of errno),
- // in addition to PLOG, or maybe better to just ignore it and add a
- // simplified version of FormatMessage() for use in log messages.
- LOG(ERROR) << "Error creating log file";
+ fatal("cannot retrieve temporary file path: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
}
return narrow(temp_path) + log_name;
@@ -109,19 +104,28 @@
static void close_stdin() {
int fd = unix_open(kNullFileName, O_RDONLY);
- CHECK_NE(fd, -1);
- dup2(fd, STDIN_FILENO);
+ if (fd == -1) {
+ fatal("cannot open '%s': %s", kNullFileName, strerror(errno));
+ }
+ if (dup2(fd, STDIN_FILENO) == -1) {
+ fatal("cannot redirect stdin: %s", strerror(errno));
+ }
unix_close(fd);
}
static void setup_daemon_logging(void) {
- int fd = unix_open(GetLogFilePath().c_str(), O_WRONLY | O_CREAT | O_APPEND,
+ const std::string log_file_path(GetLogFilePath());
+ int fd = unix_open(log_file_path.c_str(), O_WRONLY | O_CREAT | O_APPEND,
0640);
if (fd == -1) {
- fd = unix_open(kNullFileName, O_WRONLY);
+ fatal("cannot open '%s': %s", log_file_path.c_str(), strerror(errno));
}
- dup2(fd, STDOUT_FILENO);
- dup2(fd, STDERR_FILENO);
+ if (dup2(fd, STDOUT_FILENO) == -1) {
+ fatal("cannot redirect stdout: %s", strerror(errno));
+ }
+ if (dup2(fd, STDERR_FILENO) == -1) {
+ fatal("cannot redirect stderr: %s", strerror(errno));
+ }
unix_close(fd);
#ifdef _WIN32
@@ -160,16 +164,24 @@
// Inform our parent that we are up and running.
if (is_daemon) {
#if defined(_WIN32)
- // Change stdout mode to binary so \n => \r\n translation does not
- // occur. In a moment stdout will be reopened to the daemon log file
- // anyway.
- _setmode(ack_reply_fd, _O_BINARY);
-#endif
+ const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
+ const CHAR ack[] = "OK\n";
+ const DWORD bytes_to_write = arraysize(ack) - 1;
+ DWORD written = 0;
+ if (!WriteFile(ack_reply_handle, ack, bytes_to_write, &written, NULL)) {
+ fatal("adb: cannot write ACK to handle 0x%p: %s", ack_reply_handle,
+ SystemErrorCodeToString(GetLastError()).c_str());
+ }
+ if (written != bytes_to_write) {
+ fatal("adb: cannot write %lu bytes of ACK: only wrote %lu bytes",
+ bytes_to_write, written);
+ }
+ CloseHandle(ack_reply_handle);
+#else
// TODO(danalbert): Can't use SendOkay because we're sending "OK\n", not
// "OKAY".
android::base::WriteStringToFd("OK\n", ack_reply_fd);
-#if !defined(_WIN32)
- adb_close(ack_reply_fd);
+ unix_close(ack_reply_fd);
#endif
close_stdin();
setup_daemon_logging();
diff --git a/adb/commandline.cpp b/adb/commandline.cpp
index 2e182e8..0ac3556 100644
--- a/adb/commandline.cpp
+++ b/adb/commandline.cpp
@@ -65,16 +65,9 @@
gProductOutPath.c_str(), OS_PATH_SEPARATOR_STR, extra);
}
-static void version(FILE* out) {
- fprintf(out, "Android Debug Bridge version %d.%d.%d\nRevision %s\n",
- ADB_VERSION_MAJOR, ADB_VERSION_MINOR, ADB_SERVER_VERSION, ADB_REVISION);
-}
-
static void help() {
- version(stderr);
-
+ fprintf(stderr, "%s\n", adb_version().c_str());
fprintf(stderr,
- "\n"
" -a - directs adb to listen on all interfaces for a connection\n"
" -d - directs command to the only connected USB device\n"
" returns an error if more than one USB device is present.\n"
@@ -953,14 +946,7 @@
int is_server = 0;
int r;
TransportType transport_type = kTransportAny;
-
-#if defined(_WIN32)
- // TODO(compareandswap): Windows should use a separate reply fd too.
- int ack_reply_fd = STDOUT_FILENO;
-#else
int ack_reply_fd = -1;
-#endif
-
// If defined, this should be an absolute path to
// the directory containing all of the various system images
@@ -1003,7 +989,14 @@
argc--;
argv++;
ack_reply_fd = strtol(reply_fd_str, nullptr, 10);
+#ifdef _WIN32
+ const HANDLE ack_reply_handle = cast_int_to_handle(ack_reply_fd);
+ if ((GetStdHandle(STD_INPUT_HANDLE) == ack_reply_handle) ||
+ (GetStdHandle(STD_OUTPUT_HANDLE) == ack_reply_handle) ||
+ (GetStdHandle(STD_ERROR_HANDLE) == ack_reply_handle)) {
+#else
if (ack_reply_fd <= 2) { // Disallow stdin, stdout, and stderr.
+#endif
fprintf(stderr, "adb: invalid reply fd \"%s\"\n", reply_fd_str);
return usage();
}
@@ -1084,7 +1077,7 @@
if (is_server) {
if (no_daemon || is_daemon) {
- if (ack_reply_fd == -1) {
+ if (is_daemon && (ack_reply_fd == -1)) {
fprintf(stderr, "reply fd for adb server to client communication not specified.\n");
return usage();
}
@@ -1449,7 +1442,7 @@
return 0;
}
else if (!strcmp(argv[0], "version")) {
- version(stdout);
+ fprintf(stdout, "%s", adb_version().c_str());
return 0;
}
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index 9189955..6f3c443 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -338,6 +338,23 @@
char** narrow_args;
};
+// Windows HANDLE values only use 32-bits of the type, even on 64-bit machines,
+// so they can fit in an int. To convert back, we just need to sign-extend.
+// https://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
+// Note that this does not make a HANDLE value work with APIs like open(), nor
+// does this make a value from open() passable to APIs taking a HANDLE. This
+// just lets you take a HANDLE, pass it around as an int, and then use it again
+// as a HANDLE.
+inline int cast_handle_to_int(const HANDLE h) {
+ // truncate
+ return static_cast<int>(reinterpret_cast<INT_PTR>(h));
+}
+
+inline HANDLE cast_int_to_handle(const int fd) {
+ // sign-extend
+ return reinterpret_cast<HANDLE>(static_cast<INT_PTR>(fd));
+}
+
#else /* !_WIN32 a.k.a. Unix */
#include "fdevent.h"
diff --git a/adb/test_track_devices.cpp b/adb/test_track_devices.cpp
index f78daeb..6f658f6 100644
--- a/adb/test_track_devices.cpp
+++ b/adb/test_track_devices.cpp
@@ -1,12 +1,13 @@
// TODO: replace this with a shell/python script.
/* a simple test program, connects to ADB server, and opens a track-devices session */
-#include <netdb.h>
-#include <sys/socket.h>
-#include <stdio.h>
-#include <stdlib.h>
#include <errno.h>
#include <memory.h>
+#include <netdb.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <unistd.h>
#include <base/file.h>
diff --git a/adb/usb_windows.cpp b/adb/usb_windows.cpp
index 4c9a152..b8cc5cf 100644
--- a/adb/usb_windows.cpp
+++ b/adb/usb_windows.cpp
@@ -33,6 +33,10 @@
/** Structure usb_handle describes our connection to the usb device via
AdbWinApi.dll. This structure is returned from usb_open() routine and
is expected in each subsequent call that is accessing the device.
+
+ Most members are protected by usb_lock, except for adb_{read,write}_pipe which
+ rely on AdbWinApi.dll's handle validation and AdbCloseHandle(endpoint)'s
+ ability to break a thread out of pipe IO.
*/
struct usb_handle {
/// Previous entry in the list of opened usb handles
@@ -86,6 +90,9 @@
/// registers usb transport for them.
void find_devices();
+/// Kicks all USB devices
+static void kick_devices();
+
/// Entry point for thread that polls (every second) for new usb interfaces.
/// This routine calls find_devices in infinite loop.
void* device_poll_thread(void* unused);
@@ -111,9 +118,6 @@
/// Closes opened usb handle
int usb_close(usb_handle* handle);
-/// Gets interface (device) name for an opened usb handle
-const char *usb_name(usb_handle* handle);
-
int known_device_locked(const char* dev_name) {
usb_handle* usb;
@@ -177,17 +181,99 @@
return NULL;
}
+static LRESULT CALLBACK _power_window_proc(HWND hwnd, UINT uMsg, WPARAM wParam,
+ LPARAM lParam) {
+ switch (uMsg) {
+ case WM_POWERBROADCAST:
+ switch (wParam) {
+ case PBT_APMRESUMEAUTOMATIC:
+ // Resuming from sleep or hibernation, so kick all existing USB devices
+ // and then allow the device_poll_thread to redetect USB devices from
+ // scratch. If we don't do this, existing USB devices will never respond
+ // to us because they'll be waiting for the connect/auth handshake.
+ D("Received (WM_POWERBROADCAST, PBT_APMRESUMEAUTOMATIC) notification, "
+ "so kicking all USB devices\n");
+ kick_devices();
+ return TRUE;
+ }
+ }
+ return DefWindowProcW(hwnd, uMsg, wParam, lParam);
+}
+
+static void* _power_notification_thread(void* unused) {
+ // This uses a thread with its own window message pump to get power
+ // notifications. If adb runs from a non-interactive service account, this
+ // might not work (not sure). If that happens to not work, we could use
+ // heavyweight WMI APIs to get power notifications. But for the common case
+ // of a developer's interactive session, a window message pump is more
+ // appropriate.
+ D("Created power notification thread\n");
+
+ // Window class names are process specific.
+ static const WCHAR kPowerNotificationWindowClassName[] =
+ L"PowerNotificationWindow";
+
+ // Get the HINSTANCE corresponding to the module that _power_window_proc
+ // is in (the main module).
+ const HINSTANCE instance = GetModuleHandleW(NULL);
+ if (!instance) {
+ // This is such a common API call that this should never fail.
+ fatal("GetModuleHandleW failed: %s",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ }
+
+ WNDCLASSEXW wndclass;
+ memset(&wndclass, 0, sizeof(wndclass));
+ wndclass.cbSize = sizeof(wndclass);
+ wndclass.lpfnWndProc = _power_window_proc;
+ wndclass.hInstance = instance;
+ wndclass.lpszClassName = kPowerNotificationWindowClassName;
+ if (!RegisterClassExW(&wndclass)) {
+ fatal("RegisterClassExW failed: %s",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ }
+
+ if (!CreateWindowExW(WS_EX_NOACTIVATE, kPowerNotificationWindowClassName,
+ L"ADB Power Notification Window", WS_POPUP, 0, 0, 0, 0,
+ NULL, NULL, instance, NULL)) {
+ fatal("CreateWindowExW failed: %s",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ }
+
+ MSG msg;
+ while (GetMessageW(&msg, NULL, 0, 0)) {
+ TranslateMessage(&msg);
+ DispatchMessageW(&msg);
+ }
+
+ // GetMessageW() will return false if a quit message is posted. We don't
+ // do that, but it might be possible for that to occur when logging off or
+ // shutting down. Not a big deal since the whole process will be going away
+ // soon anyway.
+ D("Power notification thread exiting\n");
+
+ return NULL;
+}
+
void usb_init() {
if (!adb_thread_create(device_poll_thread, nullptr)) {
- fatal_errno("cannot create input thread");
+ fatal_errno("cannot create device poll thread");
+ }
+ if (!adb_thread_create(_power_notification_thread, nullptr)) {
+ fatal_errno("cannot create power notification thread");
}
}
usb_handle* do_usb_open(const wchar_t* interface_name) {
+ unsigned long name_len = 0;
+
// Allocate our handle
- usb_handle* ret = (usb_handle*)malloc(sizeof(usb_handle));
- if (NULL == ret)
- return NULL;
+ usb_handle* ret = (usb_handle*)calloc(1, sizeof(usb_handle));
+ if (NULL == ret) {
+ D("Could not allocate %u bytes for usb_handle: %s\n", sizeof(usb_handle),
+ strerror(errno));
+ goto fail;
+ }
// Set linkers back to the handle
ret->next = ret;
@@ -195,11 +281,10 @@
// Create interface.
ret->adb_interface = AdbCreateInterfaceByName(interface_name);
-
if (NULL == ret->adb_interface) {
- free(ret);
- errno = GetLastError();
- return NULL;
+ D("AdbCreateInterfaceByName failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ goto fail;
}
// Open read pipe (endpoint)
@@ -207,45 +292,60 @@
AdbOpenDefaultBulkReadEndpoint(ret->adb_interface,
AdbOpenAccessTypeReadWrite,
AdbOpenSharingModeReadWrite);
- if (NULL != ret->adb_read_pipe) {
- // Open write pipe (endpoint)
- ret->adb_write_pipe =
- AdbOpenDefaultBulkWriteEndpoint(ret->adb_interface,
- AdbOpenAccessTypeReadWrite,
- AdbOpenSharingModeReadWrite);
- if (NULL != ret->adb_write_pipe) {
- // Save interface name
- unsigned long name_len = 0;
-
- // First get expected name length
- AdbGetInterfaceName(ret->adb_interface,
- NULL,
- &name_len,
- true);
- if (0 != name_len) {
- ret->interface_name = (char*)malloc(name_len);
-
- if (NULL != ret->interface_name) {
- // Now save the name
- if (AdbGetInterfaceName(ret->adb_interface,
- ret->interface_name,
- &name_len,
- true)) {
- // We're done at this point
- return ret;
- }
- } else {
- SetLastError(ERROR_OUTOFMEMORY);
- }
- }
- }
+ if (NULL == ret->adb_read_pipe) {
+ D("AdbOpenDefaultBulkReadEndpoint failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ goto fail;
}
- // Something went wrong.
- int saved_errno = GetLastError();
- usb_cleanup_handle(ret);
- free(ret);
- SetLastError(saved_errno);
+ // Open write pipe (endpoint)
+ ret->adb_write_pipe =
+ AdbOpenDefaultBulkWriteEndpoint(ret->adb_interface,
+ AdbOpenAccessTypeReadWrite,
+ AdbOpenSharingModeReadWrite);
+ if (NULL == ret->adb_write_pipe) {
+ D("AdbOpenDefaultBulkWriteEndpoint failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ goto fail;
+ }
+
+ // Save interface name
+ // First get expected name length
+ AdbGetInterfaceName(ret->adb_interface,
+ NULL,
+ &name_len,
+ true);
+ if (0 == name_len) {
+ D("AdbGetInterfaceName returned name length of zero: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ goto fail;
+ }
+
+ ret->interface_name = (char*)malloc(name_len);
+ if (NULL == ret->interface_name) {
+ D("Could not allocate %lu bytes for interface_name: %s\n", name_len,
+ strerror(errno));
+ goto fail;
+ }
+
+ // Now save the name
+ if (!AdbGetInterfaceName(ret->adb_interface,
+ ret->interface_name,
+ &name_len,
+ true)) {
+ D("AdbGetInterfaceName failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ goto fail;
+ }
+
+ // We're done at this point
+ return ret;
+
+fail:
+ if (NULL != ret) {
+ usb_cleanup_handle(ret);
+ free(ret);
+ }
return NULL;
}
@@ -253,92 +353,130 @@
int usb_write(usb_handle* handle, const void* data, int len) {
unsigned long time_out = 5000;
unsigned long written = 0;
- int ret;
+ int err = 0;
D("usb_write %d\n", len);
- if (NULL != handle) {
- // Perform write
- ret = AdbWriteEndpointSync(handle->adb_write_pipe,
- (void*)data,
- (unsigned long)len,
- &written,
- time_out);
- int saved_errno = GetLastError();
-
- if (ret) {
- // Make sure that we've written what we were asked to write
- D("usb_write got: %ld, expected: %d\n", written, len);
- if (written == (unsigned long)len) {
- if(handle->zero_mask && (len & handle->zero_mask) == 0) {
- // Send a zero length packet
- AdbWriteEndpointSync(handle->adb_write_pipe,
- (void*)data,
- 0,
- &written,
- time_out);
- }
- return 0;
- }
- } else {
- // assume ERROR_INVALID_HANDLE indicates we are disconnected
- if (saved_errno == ERROR_INVALID_HANDLE)
- usb_kick(handle);
- }
- errno = saved_errno;
- } else {
- D("usb_write NULL handle\n");
- SetLastError(ERROR_INVALID_HANDLE);
+ if (NULL == handle) {
+ D("usb_write was passed NULL handle\n");
+ err = EINVAL;
+ goto fail;
}
- D("usb_write failed: %d\n", errno);
+ // Perform write
+ if (!AdbWriteEndpointSync(handle->adb_write_pipe,
+ (void*)data,
+ (unsigned long)len,
+ &written,
+ time_out)) {
+ D("AdbWriteEndpointSync failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ err = EIO;
+ goto fail;
+ }
+ // Make sure that we've written what we were asked to write
+ D("usb_write got: %ld, expected: %d\n", written, len);
+ if (written != (unsigned long)len) {
+ // If this occurs, this code should be changed to repeatedly call
+ // AdbWriteEndpointSync() until all bytes are written.
+ D("AdbWriteEndpointSync was supposed to write %d, but only wrote %ld\n",
+ len, written);
+ err = EIO;
+ goto fail;
+ }
+
+ if (handle->zero_mask && (len & handle->zero_mask) == 0) {
+ // Send a zero length packet
+ if (!AdbWriteEndpointSync(handle->adb_write_pipe,
+ (void*)data,
+ 0,
+ &written,
+ time_out)) {
+ D("AdbWriteEndpointSync of zero length packet failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ err = EIO;
+ goto fail;
+ }
+ }
+
+ return 0;
+
+fail:
+ // Any failure should cause us to kick the device instead of leaving it a
+ // zombie state with potential to hang.
+ if (NULL != handle) {
+ D("Kicking device due to error in usb_write\n");
+ usb_kick(handle);
+ }
+
+ D("usb_write failed\n");
+ errno = err;
return -1;
}
int usb_read(usb_handle *handle, void* data, int len) {
unsigned long time_out = 0;
unsigned long read = 0;
+ int err = 0;
D("usb_read %d\n", len);
- if (handle != nullptr) {
- while (len > 0) {
- int ret = AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read, time_out);
- int saved_errno = GetLastError();
- D("usb_write got: %ld, expected: %d, errno: %d\n", read, len, saved_errno);
- if (ret) {
- data = (char *)data + read;
- len -= read;
-
- if (len == 0)
- return 0;
- } else {
- // assume ERROR_INVALID_HANDLE indicates we are disconnected
- if (saved_errno == ERROR_INVALID_HANDLE)
- usb_kick(handle);
- break;
- }
- errno = saved_errno;
- }
- } else {
- D("usb_read NULL handle\n");
- SetLastError(ERROR_INVALID_HANDLE);
+ if (NULL == handle) {
+ D("usb_read was passed NULL handle\n");
+ err = EINVAL;
+ goto fail;
}
- D("usb_read failed: %d\n", errno);
+ while (len > 0) {
+ if (!AdbReadEndpointSync(handle->adb_read_pipe, data, len, &read,
+ time_out)) {
+ D("AdbReadEndpointSync failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ err = EIO;
+ goto fail;
+ }
+ D("usb_read got: %ld, expected: %d\n", read, len);
+ data = (char *)data + read;
+ len -= read;
+ }
+
+ return 0;
+
+fail:
+ // Any failure should cause us to kick the device instead of leaving it a
+ // zombie state with potential to hang.
+ if (NULL != handle) {
+ D("Kicking device due to error in usb_read\n");
+ usb_kick(handle);
+ }
+
+ D("usb_read failed\n");
+ errno = err;
return -1;
}
+// Wrapper around AdbCloseHandle() that logs diagnostics.
+static void _adb_close_handle(ADBAPIHANDLE adb_handle) {
+ if (!AdbCloseHandle(adb_handle)) {
+ D("AdbCloseHandle(%p) failed: %s\n", adb_handle,
+ SystemErrorCodeToString(GetLastError()).c_str());
+ }
+}
+
void usb_cleanup_handle(usb_handle* handle) {
+ D("usb_cleanup_handle\n");
if (NULL != handle) {
if (NULL != handle->interface_name)
free(handle->interface_name);
+ // AdbCloseHandle(pipe) will break any threads out of pending IO calls and
+ // wait until the pipe no longer uses the interface. Then we can
+ // AdbCloseHandle() the interface.
if (NULL != handle->adb_write_pipe)
- AdbCloseHandle(handle->adb_write_pipe);
+ _adb_close_handle(handle->adb_write_pipe);
if (NULL != handle->adb_read_pipe)
- AdbCloseHandle(handle->adb_read_pipe);
+ _adb_close_handle(handle->adb_read_pipe);
if (NULL != handle->adb_interface)
- AdbCloseHandle(handle->adb_interface);
+ _adb_close_handle(handle->adb_interface);
handle->interface_name = NULL;
handle->adb_write_pipe = NULL;
@@ -347,16 +485,22 @@
}
}
+static void usb_kick_locked(usb_handle* handle) {
+ // The reason the lock must be acquired before calling this function is in
+ // case multiple threads are trying to kick the same device at the same time.
+ usb_cleanup_handle(handle);
+}
+
void usb_kick(usb_handle* handle) {
+ D("usb_kick\n");
if (NULL != handle) {
adb_mutex_lock(&usb_lock);
- usb_cleanup_handle(handle);
+ usb_kick_locked(handle);
adb_mutex_unlock(&usb_lock);
} else {
- SetLastError(ERROR_INVALID_HANDLE);
- errno = ERROR_INVALID_HANDLE;
+ errno = EINVAL;
}
}
@@ -384,16 +528,6 @@
return 0;
}
-const char *usb_name(usb_handle* handle) {
- if (NULL == handle) {
- SetLastError(ERROR_INVALID_HANDLE);
- errno = ERROR_INVALID_HANDLE;
- return NULL;
- }
-
- return (const char*)handle->interface_name;
-}
-
int recognized_device(usb_handle* handle) {
if (NULL == handle)
return 0;
@@ -403,6 +537,8 @@
if (!AdbGetUsbDeviceDescriptor(handle->adb_interface,
&device_desc)) {
+ D("AdbGetUsbDeviceDescriptor failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
return 0;
}
@@ -411,6 +547,8 @@
if (!AdbGetUsbInterfaceDescriptor(handle->adb_interface,
&interf_desc)) {
+ D("AdbGetUsbInterfaceDescriptor failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
return 0;
}
@@ -427,6 +565,10 @@
// assuming zero is a valid bulk endpoint ID
if (AdbGetEndpointInformation(handle->adb_interface, 0, &endpoint_info)) {
handle->zero_mask = endpoint_info.max_packet_size - 1;
+ D("device zero_mask: 0x%x\n", handle->zero_mask);
+ } else {
+ D("AdbGetEndpointInformation failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
}
}
@@ -448,8 +590,11 @@
ADBAPIHANDLE enum_handle =
AdbEnumInterfaces(usb_class_id, true, true, true);
- if (NULL == enum_handle)
+ if (NULL == enum_handle) {
+ D("AdbEnumInterfaces failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
return;
+ }
while (AdbNextInterface(enum_handle, next_interface, &entry_buffer_size)) {
// TODO: FIXME - temp hack converting wchar_t into char.
@@ -486,7 +631,8 @@
free(handle);
}
} else {
- D("cannot get serial number\n");
+ D("cannot get serial number: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
usb_cleanup_handle(handle);
free(handle);
}
@@ -500,5 +646,21 @@
entry_buffer_size = sizeof(entry_buffer);
}
- AdbCloseHandle(enum_handle);
+ if (GetLastError() != ERROR_NO_MORE_ITEMS) {
+ // Only ERROR_NO_MORE_ITEMS is expected at the end of enumeration.
+ D("AdbNextInterface failed: %s\n",
+ SystemErrorCodeToString(GetLastError()).c_str());
+ }
+
+ _adb_close_handle(enum_handle);
+}
+
+static void kick_devices() {
+ // Need to acquire lock to safely walk the list which might be modified
+ // by another thread.
+ adb_mutex_lock(&usb_lock);
+ for (usb_handle* usb = handle_list.next; usb != &handle_list; usb = usb->next) {
+ usb_kick_locked(usb);
+ }
+ adb_mutex_unlock(&usb_lock);
}
diff --git a/fastboot/fastboot.cpp b/fastboot/fastboot.cpp
index b964a36..5d7b151 100644
--- a/fastboot/fastboot.cpp
+++ b/fastboot/fastboot.cpp
@@ -189,25 +189,16 @@
return load_fd(fd, _sz);
}
-int match_fastboot_with_serial(usb_ifc_info *info, const char *local_serial)
-{
- if(!(vendor_id && (info->dev_vendor == vendor_id)) &&
- (info->dev_vendor != 0x18d1) && // Google
- (info->dev_vendor != 0x8087) && // Intel
- (info->dev_vendor != 0x0451) &&
- (info->dev_vendor != 0x0502) &&
- (info->dev_vendor != 0x0fce) && // Sony Ericsson
- (info->dev_vendor != 0x05c6) && // Qualcomm
- (info->dev_vendor != 0x22b8) && // Motorola
- (info->dev_vendor != 0x0955) && // Nvidia
- (info->dev_vendor != 0x413c) && // DELL
- (info->dev_vendor != 0x2314) && // INQ Mobile
- (info->dev_vendor != 0x0b05) && // Asus
- (info->dev_vendor != 0x0bb4)) // HTC
- return -1;
- if(info->ifc_class != 0xff) return -1;
- if(info->ifc_subclass != 0x42) return -1;
- if(info->ifc_protocol != 0x03) return -1;
+int match_fastboot_with_serial(usb_ifc_info* info, const char* local_serial) {
+ // Require a matching vendor id if the user specified one with -i.
+ if (vendor_id != 0 && info->dev_vendor != vendor_id) {
+ return -1;
+ }
+
+ if (info->ifc_class != 0xff || info->ifc_subclass != 0x42 || info->ifc_protocol != 0x03) {
+ return -1;
+ }
+
// require matching serial number or device path if requested
// at the command line with the -s option.
if (local_serial && (strcmp(local_serial, info->serial_number) != 0 &&
diff --git a/healthd/BatteryMonitor.cpp b/healthd/BatteryMonitor.cpp
index 7ea8250..ed773d0 100644
--- a/healthd/BatteryMonitor.cpp
+++ b/healthd/BatteryMonitor.cpp
@@ -24,11 +24,13 @@
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
+#include <sys/types.h>
#include <unistd.h>
+
#include <batteryservice/BatteryService.h>
#include <cutils/klog.h>
#include <cutils/properties.h>
-#include <sys/types.h>
+#include <log/log_read.h>
#include <utils/Errors.h>
#include <utils/String8.h>
#include <utils/Vector.h>
@@ -265,10 +267,32 @@
"battery none");
}
- KLOG_WARNING(LOG_TAG, "%s chg=%s%s%s\n", dmesgline,
- props.chargerAcOnline ? "a" : "",
- props.chargerUsbOnline ? "u" : "",
- props.chargerWirelessOnline ? "w" : "");
+ size_t len = strlen(dmesgline);
+ snprintf(dmesgline + len, sizeof(dmesgline) - len, " chg=%s%s%s",
+ props.chargerAcOnline ? "a" : "",
+ props.chargerUsbOnline ? "u" : "",
+ props.chargerWirelessOnline ? "w" : "");
+
+ log_time realtime(CLOCK_REALTIME);
+ time_t t = realtime.tv_sec;
+ struct tm *tmp = gmtime(&t);
+ if (tmp) {
+ static const char fmt[] = " %Y-%m-%d %H:%M:%S.XXXXXXXXX UTC";
+ len = strlen(dmesgline);
+ if ((len < (sizeof(dmesgline) - sizeof(fmt) - 8)) // margin
+ && strftime(dmesgline + len, sizeof(dmesgline) - len,
+ fmt, tmp)) {
+ char *usec = strchr(dmesgline + len, 'X');
+ if (usec) {
+ len = usec - dmesgline;
+ snprintf(dmesgline + len, sizeof(dmesgline) - len,
+ "%09u", realtime.tv_nsec);
+ usec[9] = ' ';
+ }
+ }
+ }
+
+ KLOG_WARNING(LOG_TAG, "%s\n", dmesgline);
}
healthd_mode_ops->battery_update(&props);
diff --git a/init/Android.mk b/init/Android.mk
index 6737be4..58bff58 100644
--- a/init/Android.mk
+++ b/init/Android.mk
@@ -53,6 +53,7 @@
LOCAL_STATIC_LIBRARIES := libbase
LOCAL_MODULE := libinit
+LOCAL_SANITIZE := integer
LOCAL_CLANG := true
include $(BUILD_STATIC_LIBRARY)
@@ -100,6 +101,7 @@
ln -sf ../init $(TARGET_ROOT_OUT)/sbin/ueventd; \
ln -sf ../init $(TARGET_ROOT_OUT)/sbin/watchdogd
+LOCAL_SANITIZE := integer
LOCAL_CLANG := true
include $(BUILD_EXECUTABLE)
@@ -117,5 +119,6 @@
libbase \
LOCAL_STATIC_LIBRARIES := libinit
+LOCAL_SANITIZE := integer
LOCAL_CLANG := true
include $(BUILD_NATIVE_TEST)
diff --git a/init/init_parser.cpp b/init/init_parser.cpp
index 3ed1d58..12f44f7 100644
--- a/init/init_parser.cpp
+++ b/init/init_parser.cpp
@@ -315,10 +315,14 @@
int nargs = 0;
+ //TODO: Use a parser with const input and remove this copy
+ std::vector<char> data_copy(data.begin(), data.end());
+ data_copy.push_back('\0');
+
parse_state state;
state.filename = fn;
state.line = 0;
- state.ptr = strdup(data.c_str()); // TODO: fix this code!
+ state.ptr = &data_copy[0];
state.nexttoken = 0;
state.parse_line = parse_line_no_op;
diff --git a/init/service.cpp b/init/service.cpp
index 5c2a0cb..a370d25 100644
--- a/init/service.cpp
+++ b/init/service.cpp
@@ -20,6 +20,7 @@
#include <sys/stat.h>
#include <sys/types.h>
#include <termios.h>
+#include <unistd.h>
#include <selinux/selinux.h>
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 0f5071b..b9e8973 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -218,18 +218,25 @@
}
// If we're using more than 256K of memory for log entries, prune
-// at least 10% of the log entries.
+// at least 10% of the log entries. For sizes above 1M, prune at
+// least 1% of the log entries.
//
// mLogElementsLock must be held when this function is called.
void LogBuffer::maybePrune(log_id_t id) {
size_t sizes = stats.sizes(id);
- if (sizes > log_buffer_size(id)) {
- size_t sizeOver90Percent = sizes - ((log_buffer_size(id) * 9) / 10);
- size_t elements = stats.elements(id);
- unsigned long pruneRows = elements * sizeOver90Percent / sizes;
- elements /= 10;
- if (pruneRows <= elements) {
- pruneRows = elements;
+ unsigned long maxSize = log_buffer_size(id);
+ if (sizes > maxSize) {
+ size_t sizeOver, minElements, elements = stats.elements(id);
+ if (maxSize > (4 * LOG_BUFFER_SIZE)) {
+ sizeOver = sizes - ((maxSize * 99) / 100);
+ minElements = elements / 100;
+ } else {
+ sizeOver = sizes - ((maxSize * 9) / 10);
+ minElements = elements / 10;
+ }
+ unsigned long pruneRows = elements * sizeOver / sizes;
+ if (pruneRows <= minElements) {
+ pruneRows = minElements;
}
prune(id, pruneRows);
}
diff --git a/logd/LogKlog.cpp b/logd/LogKlog.cpp
index eff26f5..1e6f55f 100644
--- a/logd/LogKlog.cpp
+++ b/logd/LogKlog.cpp
@@ -254,6 +254,7 @@
if ((cp = now.strptime(*buf, "[ %s.%q]"))) {
static const char suspend[] = "PM: suspend entry ";
static const char resume[] = "PM: suspend exit ";
+ static const char healthd[] = "healthd: battery ";
static const char suspended[] = "Suspended for ";
if (isspace(*cp)) {
@@ -263,6 +264,15 @@
calculateCorrection(now, cp + sizeof(suspend) - 1);
} else if (!strncmp(cp, resume, sizeof(resume) - 1)) {
calculateCorrection(now, cp + sizeof(resume) - 1);
+ } else if (!strncmp(cp, healthd, sizeof(healthd) - 1)) {
+ // look for " 2???-??-?? ??:??:??.????????? ???"
+ const char *tp;
+ for (tp = cp + sizeof(healthd) - 1; *tp && (*tp != '\n'); ++tp) {
+ if ((tp[0] == ' ') && (tp[1] == '2') && (tp[5] == '-')) {
+ calculateCorrection(now, tp + 1);
+ break;
+ }
+ }
} else if (!strncmp(cp, suspended, sizeof(suspended) - 1)) {
log_time real;
char *endp;
diff --git a/metricsd/Android.mk b/metricsd/Android.mk
index 17fb278..9edba6e 100644
--- a/metricsd/Android.mk
+++ b/metricsd/Android.mk
@@ -14,6 +14,8 @@
LOCAL_PATH := $(call my-dir)
+ifeq ($(HOST_OS),linux)
+
metrics_cpp_extension := .cc
libmetrics_sources := \
c_metrics_library.cc \
@@ -110,3 +112,5 @@
LOCAL_SRC_FILES := $(metrics_daemon_sources)
LOCAL_STATIC_LIBRARIES := metrics_daemon_protos
include $(BUILD_EXECUTABLE)
+
+endif # HOST_OS == linux
diff --git a/toolbox/Android.mk b/toolbox/Android.mk
index aa92af7..ae880c3 100644
--- a/toolbox/Android.mk
+++ b/toolbox/Android.mk
@@ -56,7 +56,6 @@
stop \
top \
uptime \
- watchprops \
ALL_TOOLS = $(BSD_TOOLS) $(OUR_TOOLS)
diff --git a/toolbox/watchprops.c b/toolbox/watchprops.c
deleted file mode 100644
index cd62922..0000000
--- a/toolbox/watchprops.c
+++ /dev/null
@@ -1,92 +0,0 @@
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <time.h>
-#include <errno.h>
-
-#include <cutils/properties.h>
-#include <cutils/hashmap.h>
-
-#define _REALLY_INCLUDE_SYS__SYSTEM_PROPERTIES_H_
-#include <sys/_system_properties.h>
-
-static int str_hash(void *key)
-{
- return hashmapHash(key, strlen(key));
-}
-
-static bool str_equals(void *keyA, void *keyB)
-{
- return strcmp(keyA, keyB) == 0;
-}
-
-static void announce(char *name, char *value)
-{
- unsigned char *x;
-
- for(x = (unsigned char *)value; *x; x++) {
- if((*x < 32) || (*x > 127)) *x = '.';
- }
-
- fprintf(stderr,"%10d %s = '%s'\n", (int) time(0), name, value);
-}
-
-static void add_to_watchlist(Hashmap *watchlist, const char *name,
- const prop_info *pi)
-{
- char *key = strdup(name);
- unsigned *value = malloc(sizeof(unsigned));
- if (!key || !value)
- exit(1);
-
- *value = __system_property_serial(pi);
- hashmapPut(watchlist, key, value);
-}
-
-static void populate_watchlist(const prop_info *pi, void *cookie)
-{
- Hashmap *watchlist = cookie;
- char name[PROP_NAME_MAX];
- char value_unused[PROP_VALUE_MAX];
-
- __system_property_read(pi, name, value_unused);
- add_to_watchlist(watchlist, name, pi);
-}
-
-static void update_watchlist(const prop_info *pi, void *cookie)
-{
- Hashmap *watchlist = cookie;
- char name[PROP_NAME_MAX];
- char value[PROP_VALUE_MAX];
- unsigned *serial;
-
- __system_property_read(pi, name, value);
- serial = hashmapGet(watchlist, name);
- if (!serial) {
- add_to_watchlist(watchlist, name, pi);
- announce(name, value);
- } else {
- unsigned tmp = __system_property_serial(pi);
- if (*serial != tmp) {
- *serial = tmp;
- announce(name, value);
- }
- }
-}
-
-int watchprops_main(int argc, char *argv[])
-{
- unsigned serial;
-
- Hashmap *watchlist = hashmapCreate(1024, str_hash, str_equals);
- if (!watchlist)
- exit(1);
-
- __system_property_foreach(populate_watchlist, watchlist);
-
- for(serial = 0;;) {
- serial = __system_property_wait_any(serial);
- __system_property_foreach(update_watchlist, watchlist);
- }
- return 0;
-}