Merge "Kill HAVE_PTHREADS."
diff --git a/adb/Android.mk b/adb/Android.mk
index 8ebcbf0..7317339 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -5,6 +5,35 @@
 
 LOCAL_PATH:= $(call my-dir)
 
+# libadb
+# =========================================================
+
+# Much of adb is duplicated in bootable/recovery/minadb and fastboot. Changes
+# made to adb rarely get ported to the other two, so the trees have diverged a
+# bit. We'd like to stop this because it is a maintenance nightmare, but the
+# divergence makes this difficult to do all at once. For now, we will start
+# small by moving common files into a static library. Hopefully some day we can
+# get enough of adb in here that we no longer need minadb. https://b/17626262
+LIBADB_SRC_FILES :=
+LIBADB_C_FLAGS := -Wall -Werror -D_XOPEN_SOURCE -D_GNU_SOURCE
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libadb
+LOCAL_CFLAGS := $(LIBADB_CFLAGS) -DADB_HOST=0
+LOCAL_SRC_FILES := $(LIBADB_SRC_FILES) fdevent.cpp
+include $(BUILD_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libadb
+LOCAL_CFLAGS := $(LIBADB_CFLAGS) -DADB_HOST=1
+LOCAL_SRC_FILES := $(LIBADB_SRC_FILES)
+ifeq ($(HOST_OS),windows)
+    LOCAL_SRC_FILES += sysdeps_win32.c
+else
+    LOCAL_SRC_FILES += fdevent.cpp
+endif
+include $(BUILD_HOST_STATIC_LIBRARY)
+
 # adb host tool
 # =========================================================
 include $(CLEAR_VARS)
@@ -37,10 +66,6 @@
   USB_SRCS := usb_windows.c
   EXTRA_SRCS := get_my_path_windows.c
   EXTRA_STATIC_LIBS := AdbWinApi
-  ifneq ($(strip $(USE_CYGWIN)),)
-    # Pure cygwin case
-    LOCAL_LDLIBS += -lpthread -lgdi32
-  endif
   ifneq ($(strip $(USE_MINGW)),)
     # MinGW under Linux case
     LOCAL_LDLIBS += -lws2_32 -lgdi32
@@ -66,8 +91,6 @@
 
 ifneq ($(USE_SYSDEPS_WIN32),)
   LOCAL_SRC_FILES += sysdeps_win32.c
-else
-  LOCAL_SRC_FILES += fdevent.c
 endif
 
 LOCAL_CFLAGS += -O2 -g -DADB_HOST=1 -Wall -Wno-unused-parameter -Werror
@@ -75,7 +98,12 @@
 LOCAL_MODULE := adb
 LOCAL_MODULE_TAGS := debug
 
-LOCAL_STATIC_LIBRARIES := libzipfile libz libcrypto_static $(EXTRA_STATIC_LIBS)
+LOCAL_STATIC_LIBRARIES := \
+    libadb \
+    libzipfile \
+    libcrypto_static \
+    $(EXTRA_STATIC_LIBS) \
+
 ifeq ($(USE_SYSDEPS_WIN32),)
 	LOCAL_STATIC_LIBRARIES += libcutils
 endif
@@ -99,7 +127,6 @@
 
 LOCAL_SRC_FILES := \
 	adb.c \
-	fdevent.c \
 	transport.c \
 	transport_local.c \
 	transport_usb.c \
@@ -136,55 +163,16 @@
 LOCAL_UNSTRIPPED_PATH := $(TARGET_ROOT_OUT_SBIN_UNSTRIPPED)
 LOCAL_C_INCLUDES += system/extras/ext4_utils system/core/fs_mgr/include
 
-LOCAL_STATIC_LIBRARIES := liblog \
-	libfs_mgr \
-	libcutils \
-	libc \
-	libmincrypt \
-	libselinux \
-	libext4_utils_static
+LOCAL_STATIC_LIBRARIES := \
+    libadb \
+    libfs_mgr \
+    liblog \
+    libcutils \
+    libc \
+    libmincrypt \
+    libselinux \
+    libext4_utils_static \
 
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 
 include $(BUILD_EXECUTABLE)
-
-
-# adb host tool for device-as-host
-# =========================================================
-ifneq ($(SDK_ONLY),true)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := \
-	adb.c \
-	console.c \
-	transport.c \
-	transport_local.c \
-	transport_usb.c \
-	commandline.c \
-	adb_client.c \
-	adb_auth_host.c \
-	sockets.c \
-	services.c \
-	file_sync_client.c \
-	get_my_path_linux.c \
-	usb_linux.c \
-	fdevent.c
-
-LOCAL_CFLAGS := \
-	-O2 \
-	-g \
-	-DADB_HOST=1 \
-	-DADB_HOST_ON_TARGET=1 \
-	-Wall -Wno-unused-parameter -Werror \
-	-D_XOPEN_SOURCE \
-	-D_GNU_SOURCE
-
-LOCAL_MODULE := adb
-
-LOCAL_STATIC_LIBRARIES := libzipfile libz libcutils liblog
-
-LOCAL_SHARED_LIBRARIES := libcrypto
-
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
-include $(BUILD_EXECUTABLE)
-endif
diff --git a/adb/adb.h b/adb/adb.h
index a37fd5b..6ac4731 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -20,6 +20,7 @@
 #include <limits.h>
 
 #include "adb_trace.h"
+#include "fdevent.h"
 #include "transport.h"  /* readx(), writex() */
 
 #define MAX_PAYLOAD 4096
diff --git a/adb/commandline.c b/adb/commandline.c
index 44541b7..a06885b 100644
--- a/adb/commandline.c
+++ b/adb/commandline.c
@@ -472,7 +472,7 @@
     }
 
     int opt = CHUNK_SIZE;
-    opt = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
+    opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
 
     total = sz;
     ptr = data;
@@ -581,7 +581,7 @@
     }
 
     int opt = SIDELOAD_HOST_BLOCK_SIZE;
-    opt = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
+    opt = adb_setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
 
     int last_percent = -1;
     for (;;) {
diff --git a/adb/fdevent.c b/adb/fdevent.cpp
similarity index 97%
rename from adb/fdevent.c
rename to adb/fdevent.cpp
index f5ecd14..bd0f3b2 100644
--- a/adb/fdevent.c
+++ b/adb/fdevent.cpp
@@ -88,6 +88,12 @@
 static fdevent list_pending = {
     .next = &list_pending,
     .prev = &list_pending,
+    .fd = -1,
+    .force_eof = 0,
+    .state = 0,
+    .events = 0,
+    .func = nullptr,
+    .arg = nullptr,
 };
 
 static fdevent **fd_table = 0;
@@ -312,7 +318,7 @@
 }
 
 #if !DEBUG
-static inline void dump_all_fds(const char *extra_msg) {}
+static inline void dump_all_fds(const char* /* extra_msg */) {}
 #else
 static void dump_all_fds(const char *extra_msg)
 {
@@ -434,7 +440,8 @@
         while(fd_table_max <= fde->fd) {
             fd_table_max *= 2;
         }
-        fd_table = realloc(fd_table, sizeof(fdevent*) * fd_table_max);
+        fd_table = reinterpret_cast<fdevent**>(
+            realloc(fd_table, sizeof(fdevent*) * fd_table_max));
         if(fd_table == 0) {
             FATAL("could not expand fd_table to %d entries\n", fd_table_max);
         }
@@ -505,7 +512,8 @@
     fde->func(fde->fd, events, fde->arg);
 }
 
-static void fdevent_subproc_event_func(int fd, unsigned ev, void *userdata)
+static void fdevent_subproc_event_func(int fd, unsigned ev,
+                                       void* /* userdata */)
 {
 
     D("subproc handling on fd=%d ev=%04x\n", fd, ev);
diff --git a/adb/fdevent.h b/adb/fdevent.h
index a0ebe2a..a8102ca 100644
--- a/adb/fdevent.h
+++ b/adb/fdevent.h
@@ -19,6 +19,10 @@
 
 #include <stdint.h>  /* for int64_t */
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /* events that may be observed */
 #define FDE_READ              0x0001
 #define FDE_WRITE             0x0002
@@ -64,20 +68,22 @@
 */
 void fdevent_loop();
 
-struct fdevent 
-{
+struct fdevent {
     fdevent *next;
     fdevent *prev;
 
     int fd;
     int force_eof;
 
-    unsigned short state;
-    unsigned short events;
+    uint16_t state;
+    uint16_t events;
 
     fd_func func;
     void *arg;
 };
 
+#ifdef __cplusplus
+}
+#endif
 
 #endif
diff --git a/adb/set_verity_enable_state_service.c b/adb/set_verity_enable_state_service.c
index 2660ddd..184674d 100644
--- a/adb/set_verity_enable_state_service.c
+++ b/adb/set_verity_enable_state_service.c
@@ -14,24 +14,29 @@
  * limitations under the License.
  */
 
-#include "sysdeps.h"
+#include <fcntl.h>
+#include <inttypes.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdio.h>
+#include <sys/stat.h>
 
 #define  TRACE_TAG  TRACE_ADB
 #include "adb.h"
-
-#include <stdio.h>
-#include <stdarg.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <inttypes.h>
-
 #include "cutils/properties.h"
 #include "ext4_sb.h"
-#include <fs_mgr.h>
+#include "fs_mgr.h"
+#include "sysdeps.h"
 
 #define FSTAB_PREFIX "/fstab."
 struct fstab *fstab;
 
+#ifdef ALLOW_ADBD_DISABLE_VERITY
+static const bool kAllowDisableVerity = true;
+#else
+static const bool kAllowDisableVerity = false;
+#endif
+
 __attribute__((__format__(printf, 2, 3))) __nonnull((2))
 static void write_console(int fd, const char* format, ...)
 {
@@ -44,7 +49,6 @@
     adb_write(fd, buffer, strnlen(buffer, sizeof(buffer)));
 }
 
-#ifdef ALLOW_ADBD_DISABLE_VERITY
 static int get_target_device_size(int fd, const char *blk_device,
                                   uint64_t *device_size)
 {
@@ -148,10 +152,10 @@
     }
 
     if (adb_write(device, &new_magic, sizeof(new_magic)) != sizeof(new_magic)) {
-        write_console(fd, "Could not set verity %s flag on device %s with error %s\n",
-                      enable ? "enabled" : "disabled",
-                      block_device,
-                      strerror(errno));
+        write_console(
+            fd, "Could not set verity %s flag on device %s with error %s\n",
+            enable ? "enabled" : "disabled",
+            block_device, strerror(errno));
         goto errout;
     }
 
@@ -164,58 +168,60 @@
         adb_close(device);
     return retval;
 }
-#endif
 
 void set_verity_enabled_state_service(int fd, void* cookie)
 {
     bool enable = (cookie != NULL);
-#ifdef ALLOW_ADBD_DISABLE_VERITY
-    char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
-    char propbuf[PROPERTY_VALUE_MAX];
-    int i;
-    bool any_changed = false;
+    if (kAllowDisableVerity) {
+        char fstab_filename[PROPERTY_VALUE_MAX + sizeof(FSTAB_PREFIX)];
+        char propbuf[PROPERTY_VALUE_MAX];
+        int i;
+        bool any_changed = false;
 
-    property_get("ro.secure", propbuf, "0");
-    if (strcmp(propbuf, "1")) {
-        write_console(fd, "verity not enabled - ENG build\n");
-        goto errout;
+        property_get("ro.secure", propbuf, "0");
+        if (strcmp(propbuf, "1")) {
+            write_console(fd, "verity not enabled - ENG build\n");
+            goto errout;
+        }
+
+        property_get("ro.debuggable", propbuf, "0");
+        if (strcmp(propbuf, "1")) {
+            write_console(
+                fd, "verity cannot be disabled/enabled - USER build\n");
+            goto errout;
+        }
+
+        property_get("ro.hardware", propbuf, "");
+        snprintf(fstab_filename, sizeof(fstab_filename), FSTAB_PREFIX"%s",
+                 propbuf);
+
+        fstab = fs_mgr_read_fstab(fstab_filename);
+        if (!fstab) {
+            write_console(fd, "Failed to open %s\nMaybe run adb root?\n",
+                          fstab_filename);
+            goto errout;
+        }
+
+        /* Loop through entries looking for ones that vold manages */
+        for (i = 0; i < fstab->num_entries; i++) {
+            if(fs_mgr_is_verified(&fstab->recs[i])) {
+                if (!set_verity_enabled_state(fd, fstab->recs[i].blk_device,
+                                              fstab->recs[i].mount_point,
+                                              enable)) {
+                    any_changed = true;
+                }
+           }
+        }
+
+        if (any_changed) {
+            write_console(
+                fd, "Now reboot your device for settings to take effect\n");
+        }
+    } else {
+        write_console(fd, "%s-verity only works for userdebug builds\n",
+                      enable ? "enable" : "disable");
     }
 
-    property_get("ro.debuggable", propbuf, "0");
-    if (strcmp(propbuf, "1")) {
-        write_console(fd, "verity cannot be disabled/enabled - USER build\n");
-        goto errout;
-    }
-
-    property_get("ro.hardware", propbuf, "");
-    snprintf(fstab_filename, sizeof(fstab_filename), FSTAB_PREFIX"%s", propbuf);
-
-    fstab = fs_mgr_read_fstab(fstab_filename);
-    if (!fstab) {
-        write_console(fd, "Failed to open %s\nMaybe run adb root?\n",
-                      fstab_filename);
-        goto errout;
-    }
-
-    /* Loop through entries looking for ones that vold manages */
-    for (i = 0; i < fstab->num_entries; i++) {
-        if(fs_mgr_is_verified(&fstab->recs[i])) {
-            if (!set_verity_enabled_state(fd, fstab->recs[i].blk_device,
-                                          fstab->recs[i].mount_point, enable)) {
-                any_changed = true;
-            }
-       }
-    }
-
-    if (any_changed) {
-        write_console(fd,
-                      "Now reboot your device for settings to take effect\n");
-    }
 errout:
-#else
-    write_console(fd, "%s-verity only works for userdebug builds\n",
-                  enable ? "enable" : "disable");
-#endif
-
     adb_close(fd);
 }
diff --git a/adb/sysdeps.h b/adb/sysdeps.h
index 8d63d14..086dd61 100644
--- a/adb/sysdeps.h
+++ b/adb/sysdeps.h
@@ -26,16 +26,18 @@
 
 #ifdef _WIN32
 
+#include <ctype.h>
+#include <direct.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <io.h>
+#include <process.h>
+#include <sys/stat.h>
 #include <winsock2.h>
 #include <windows.h>
 #include <ws2tcpip.h>
-#include <process.h>
-#include <fcntl.h>
-#include <io.h>
-#include <sys/stat.h>
-#include <errno.h>
-#include <ctype.h>
-#include <direct.h>
+
+#include "fdevent.h"
 
 #define OS_PATH_SEPARATOR '\\'
 #define OS_PATH_SEPARATOR_STR "\\"
@@ -87,8 +89,6 @@
     /* nothing really */
 }
 
-extern void  disable_tcp_nagle(int  fd);
-
 #define  lstat    stat   /* no symlinks on Win32 */
 
 #define  S_ISLNK(m)   0   /* no symlinks on Win32 */
@@ -187,8 +187,6 @@
 #define FDE_ERROR             0x0004
 #define FDE_DONT_CLOSE        0x0080
 
-typedef struct fdevent fdevent;
-
 typedef void (*fd_func)(int fd, unsigned events, void *userdata);
 
 fdevent *fdevent_create(int fd, fd_func func, void *arg);
@@ -200,20 +198,6 @@
 void     fdevent_del(fdevent *fde, unsigned events);
 void     fdevent_loop();
 
-struct fdevent {
-    fdevent *next;
-    fdevent *prev;
-
-    int fd;
-    int force_eof;
-
-    unsigned short state;
-    unsigned short events;
-
-    fd_func func;
-    void *arg;
-};
-
 static __inline__ void  adb_sleep_ms( int  mseconds )
 {
     Sleep( mseconds );
@@ -224,10 +208,21 @@
 #undef   accept
 #define  accept  ___xxx_accept
 
+extern int  adb_setsockopt(int  fd, int  level, int  optname, const void*  optval, socklen_t  optlen);
+
+#undef   setsockopt
+#define  setsockopt  ___xxx_setsockopt
+
 static __inline__  int  adb_socket_setbufsize( int   fd, int  bufsize )
 {
     int opt = bufsize;
-    return setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*)&opt, sizeof(opt));
+    return adb_setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const void*)&opt, sizeof(opt));
+}
+
+static __inline__ void  disable_tcp_nagle( int  fd )
+{
+    int  on = 1;
+    adb_setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (const void*)&on, sizeof(on));
 }
 
 extern int  adb_socketpair( int  sv[2] );
@@ -464,6 +459,13 @@
     setsockopt( fd, IPPROTO_TCP, TCP_NODELAY, (void*)&on, sizeof(on) );
 }
 
+static __inline__ int  adb_setsockopt( int  fd, int  level, int  optname, const void*  optval, socklen_t  optlen )
+{
+    return setsockopt( fd, level, optname, optval, optlen );
+}
+
+#undef   setsockopt
+#define  setsockopt  ___xxx_setsockopt
 
 static __inline__ int  unix_socketpair( int  d, int  type, int  protocol, int sv[2] )
 {
diff --git a/adb/sysdeps_win32.c b/adb/sysdeps_win32.c
index e69ec2b..f132b8c 100644
--- a/adb/sysdeps_win32.c
+++ b/adb/sysdeps_win32.c
@@ -440,7 +440,8 @@
 {
     FH   f = _fh_from_int(fd);
 
-    if (!f) {
+    if (!f || f->clazz != &_fh_socket_class) {
+        D("adb_shutdown: invalid fd %d\n", fd);
         return -1;
     }
 
@@ -471,6 +472,8 @@
 /**************************************************************************/
 /**************************************************************************/
 
+#undef setsockopt
+
 static void
 _socket_set_errno( void )
 {
@@ -786,15 +789,16 @@
 }
 
 
-void  disable_tcp_nagle(int fd)
+int  adb_setsockopt( int  fd, int  level, int  optname, const void*  optval, socklen_t  optlen )
 {
     FH   fh = _fh_from_int(fd);
-    int  on = 1;
 
-    if ( !fh || fh->clazz != &_fh_socket_class )
-        return;
+    if ( !fh || fh->clazz != &_fh_socket_class ) {
+        D("adb_setsockopt: invalid fd %d\n", fd);
+        return -1;
+    }
 
-    setsockopt( fh->fh_socket, IPPROTO_TCP, TCP_NODELAY, (const char*)&on, sizeof(on) );
+    return setsockopt( fh->fh_socket, level, optname, optval, optlen );
 }
 
 /**************************************************************************/
diff --git a/adb/transport.h b/adb/transport.h
index 992e052..c1b8ff3 100644
--- a/adb/transport.h
+++ b/adb/transport.h
@@ -17,10 +17,19 @@
 #ifndef __TRANSPORT_H
 #define __TRANSPORT_H
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
 /* convenience wrappers around read/write that will retry on
 ** EINTR and/or short read/write.  Returns 0 on success, -1
 ** on error or EOF.
 */
 int readx(int fd, void *ptr, size_t len);
 int writex(int fd, const void *ptr, size_t len);
+
+#ifdef __cplusplus
+}
+#endif
+
 #endif   /* __TRANSPORT_H */
diff --git a/debuggerd/mips/machine.cpp b/debuggerd/mips/machine.cpp
index 97834c7..1145963 100644
--- a/debuggerd/mips/machine.cpp
+++ b/debuggerd/mips/machine.cpp
@@ -29,22 +29,10 @@
 
 #define R(x) (static_cast<unsigned int>(x))
 
-// The MIPS uapi ptrace.h has the wrong definition for pt_regs. PTRACE_GETREGS
-// writes 64-bit quantities even though the public struct uses 32-bit ones.
-struct pt_regs_mips_t {
-  uint64_t regs[32];
-  uint64_t lo;
-  uint64_t hi;
-  uint64_t cp0_epc;
-  uint64_t cp0_badvaddr;
-  uint64_t cp0_status;
-  uint64_t cp0_cause;
-};
-
 // If configured to do so, dump memory around *all* registers
 // for the crashing thread.
 void dump_memory_and_code(log_t* log, pid_t tid) {
-  pt_regs_mips_t r;
+  pt_regs r;
   if (ptrace(PTRACE_GETREGS, tid, 0, &r)) {
     return;
   }
@@ -85,7 +73,7 @@
 }
 
 void dump_registers(log_t* log, pid_t tid) {
-  pt_regs_mips_t r;
+  pt_regs r;
   if(ptrace(PTRACE_GETREGS, tid, 0, &r)) {
     _LOG(log, logtype::ERROR, "cannot get registers: %s\n", strerror(errno));
     return;