merge in master-release history after reset to d8698d739f68a201d272d2b8cc3c3ab0ad3f621b
diff --git a/adb/Android.mk b/adb/Android.mk
index 62f012c..50e28a6 100644
--- a/adb/Android.mk
+++ b/adb/Android.mk
@@ -74,7 +74,7 @@
   LOCAL_SRC_FILES += fdevent.c
 endif
 
-LOCAL_CFLAGS += -O2 -g -DADB_HOST=1  -Wall -Wno-unused-parameter
+LOCAL_CFLAGS += -O2 -g -DADB_HOST=1 -Wall -Wno-unused-parameter -Werror
 LOCAL_CFLAGS += -D_XOPEN_SOURCE -D_GNU_SOURCE
 LOCAL_MODULE := adb
 LOCAL_MODULE_TAGS := debug
@@ -116,7 +116,7 @@
 	remount_service.c \
 	usb_linux_client.c
 
-LOCAL_CFLAGS := -O2 -g -DADB_HOST=0 -Wall -Wno-unused-parameter
+LOCAL_CFLAGS := -O2 -g -DADB_HOST=0 -Wall -Wno-unused-parameter -Werror
 LOCAL_CFLAGS += -D_XOPEN_SOURCE -D_GNU_SOURCE
 
 ifneq (,$(filter userdebug eng,$(TARGET_BUILD_VARIANT)))
@@ -138,8 +138,6 @@
 ifneq ($(SDK_ONLY),true)
 include $(CLEAR_VARS)
 
-LOCAL_LDLIBS := -lrt -ldl -lpthread
-
 LOCAL_SRC_FILES := \
 	adb.c \
 	console.c \
@@ -162,8 +160,7 @@
 	-g \
 	-DADB_HOST=1 \
 	-DADB_HOST_ON_TARGET=1 \
-	-Wall \
-	-Wno-unused-parameter \
+	-Wall -Wno-unused-parameter -Werror \
 	-D_XOPEN_SOURCE \
 	-D_GNU_SOURCE
 
diff --git a/adb/backup_service.c b/adb/backup_service.c
index 669ff86..654e0f3 100644
--- a/adb/backup_service.c
+++ b/adb/backup_service.c
@@ -52,15 +52,12 @@
     pid_t pid;
     int s[2];
     char* operation;
-    int socketnum;
 
-    // Command string and choice of stdin/stdout for the pipe depend on our invocation
+    // Command string depends on our invocation
     if (op == BACKUP) {
         operation = "backup";
-        socketnum = STDOUT_FILENO;
     } else {
         operation = "restore";
-        socketnum = STDIN_FILENO;
     }
 
     D("backup_service(%s, %s)\n", operation, args);
diff --git a/adb/commandline.c b/adb/commandline.c
index 5df5796..a3eaf43 100644
--- a/adb/commandline.c
+++ b/adb/commandline.c
@@ -408,7 +408,7 @@
     }
 
     int opt = CHUNK_SIZE;
-    opt = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt));
+    opt = setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const void *) &opt, sizeof(opt));
 
     total = sz;
     ptr = data;
@@ -683,10 +683,10 @@
     return 0;
 }
 
-static int mkdirs(char *path)
+static int mkdirs(const char *path)
 {
     int ret;
-    char *x = path + 1;
+    char *x = (char *)path + 1;
 
     for(;;) {
         x = adb_dirstart(x);
@@ -729,7 +729,7 @@
     if (argc < 2) return usage();
 
     adb_unlink(filename);
-    mkdirs((char *)filename);
+    mkdirs(filename);
     outFd = adb_creat(filename, 0640);
     if (outFd < 0) {
         fprintf(stderr, "adb: unable to open file %s\n", filename);
diff --git a/adb/file_sync_client.c b/adb/file_sync_client.c
index 3da54c4..d3cb113 100644
--- a/adb/file_sync_client.c
+++ b/adb/file_sync_client.c
@@ -459,10 +459,10 @@
     return -1;
 }
 
-static int mkdirs(char *name)
+static int mkdirs(const char *name)
 {
     int ret;
-    char *x = name + 1;
+    char *x = (char *)name + 1;
 
     for(;;) {
         x = adb_dirstart(x);
@@ -524,7 +524,7 @@
 
     if((id == ID_DATA) || (id == ID_DONE)) {
         adb_unlink(lpath);
-        mkdirs((char *)lpath);
+        mkdirs(lpath);
         lfd = adb_creat(lpath, 0644);
         if(lfd < 0) {
             fprintf(stderr,"cannot create '%s': %s\n", lpath, strerror(errno));
diff --git a/adb/remount_service.c b/adb/remount_service.c
index ad61284..d3a649b 100644
--- a/adb/remount_service.c
+++ b/adb/remount_service.c
@@ -14,13 +14,13 @@
  * limitations under the License.
  */
 
-#include <stdlib.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <fcntl.h>
-#include <sys/mount.h>
 #include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mount.h>
+#include <unistd.h>
 
 #include "sysdeps.h"
 
@@ -35,7 +35,6 @@
 {
     int fd;
     int res;
-    int size;
     char *token = NULL;
     const char delims[] = "\n";
     char buf[4096];
@@ -45,7 +44,7 @@
         return NULL;
 
     buf[sizeof(buf) - 1] = '\0';
-    size = adb_read(fd, buf, sizeof(buf) - 1);
+    adb_read(fd, buf, sizeof(buf) - 1);
     adb_close(fd);
 
     token = strtok(buf, delims);
diff --git a/adb/sysdeps_win32.c b/adb/sysdeps_win32.c
index 2105b16..b0cb048 100644
--- a/adb/sysdeps_win32.c
+++ b/adb/sysdeps_win32.c
@@ -956,7 +956,7 @@
             avail = len;
 
         memcpy( bip->buff + bip->a_end, src, avail );
-        src   += avail;
+        src   = (const char *)src + avail;
         count += avail;
         len   -= avail;
 
@@ -1049,7 +1049,7 @@
         avail = len;
 
     memcpy( dst, bip->buff + bip->a_start, avail );
-    dst   += avail;
+    dst   = (char *)dst + avail;
     count += avail;
     len   -= avail;
 
diff --git a/adb/usb_windows.c b/adb/usb_windows.c
index 4936b77..1309a78 100644
--- a/adb/usb_windows.c
+++ b/adb/usb_windows.c
@@ -310,14 +310,14 @@
       int xfer = (len > 4096) ? 4096 : len;
 
       ret = AdbReadEndpointSync(handle->adb_read_pipe,
-                                  (void*)data,
+                                  data,
                                   (unsigned long)xfer,
                                   &read,
                                   time_out);
       int saved_errno = GetLastError();
       D("usb_write got: %ld, expected: %d, errno: %d\n", read, xfer, saved_errno);
       if (ret) {
-        data += read;
+        data = (char *)data + read;
         len -= read;
 
         if (len == 0)
diff --git a/debuggerd/mips/machine.cpp b/debuggerd/mips/machine.cpp
index 7b4e29e..ab34182 100644
--- a/debuggerd/mips/machine.cpp
+++ b/debuggerd/mips/machine.cpp
@@ -22,8 +22,6 @@
 #include <sys/types.h>
 #include <sys/ptrace.h>
 
-#include <corkscrew/ptrace.h>
-
 #include <sys/user.h>
 
 #include "../utility.h"
@@ -37,7 +35,7 @@
 // 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, int scope_flags) {
-  pt_regs_mips_t r;
+  pt_regs r;
   if (ptrace(PTRACE_GETREGS, tid, 0, &r)) {
     return;
   }
@@ -80,7 +78,7 @@
 }
 
 void dump_registers(log_t* log, pid_t tid, int scope_flags) {
-  pt_regs_mips_t r;
+  pt_regs r;
   if(ptrace(PTRACE_GETREGS, tid, 0, &r)) {
     _LOG(log, scope_flags, "cannot get registers: %s\n", strerror(errno));
     return;
diff --git a/fs_mgr/Android.mk b/fs_mgr/Android.mk
index 165ebd4..7cffc37 100644
--- a/fs_mgr/Android.mk
+++ b/fs_mgr/Android.mk
@@ -11,6 +11,7 @@
 LOCAL_STATIC_LIBRARIES := liblogwrap libmincrypt libext4_utils_static
 LOCAL_C_INCLUDES += system/extras/ext4_utils
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+LOCAL_CFLAGS := -Werror
 
 include $(BUILD_STATIC_LIBRARY)
 
@@ -31,5 +32,7 @@
 
 LOCAL_STATIC_LIBRARIES := libfs_mgr liblogwrap libcutils liblog libc libmincrypt libext4_utils_static
 
+LOCAL_CFLAGS := -Werror
+
 include $(BUILD_EXECUTABLE)
 
diff --git a/fs_mgr/fs_mgr_fstab.c b/fs_mgr/fs_mgr_fstab.c
index 98a2af4..6c21425 100644
--- a/fs_mgr/fs_mgr_fstab.c
+++ b/fs_mgr/fs_mgr_fstab.c
@@ -168,7 +168,6 @@
         p = strtok_r(NULL, ",", &savep);
     }
 
-out:
     if (fs_options && fs_options[0]) {
         /* remove the last trailing comma from the list of options */
         fs_options[strlen(fs_options) - 1] = '\0';
@@ -187,7 +186,6 @@
     const char *delim = " \t";
     char *save_ptr, *p;
     struct fstab *fstab = NULL;
-    struct fstab_rec *recs;
     struct fs_mgr_flag_values flag_vals;
 #define FS_OPTIONS_LEN 1024
     char tmp_fs_options[FS_OPTIONS_LEN];
diff --git a/fs_mgr/fs_mgr_verity.c b/fs_mgr/fs_mgr_verity.c
index aa3b1dd..b79a4a8 100644
--- a/fs_mgr/fs_mgr_verity.c
+++ b/fs_mgr/fs_mgr_verity.c
@@ -86,7 +86,6 @@
 
 static int verify_table(char *signature, char *table, int table_length)
 {
-    int fd;
     RSAPublicKey *key;
     uint8_t hash_buf[SHA_DIGEST_SIZE];
     int retval = -1;
diff --git a/gpttool/Android.mk b/gpttool/Android.mk
index b8f9844..64ad945 100644
--- a/gpttool/Android.mk
+++ b/gpttool/Android.mk
@@ -5,6 +5,7 @@
 
 LOCAL_SRC_FILES := gpttool.c
 LOCAL_STATIC_LIBRARIES := libz
+LOCAL_CFLAGS := -Werror
 
 LOCAL_MODULE := gpttool
 
diff --git a/gpttool/gpttool.c b/gpttool/gpttool.c
index d3f08fe..398362f 100644
--- a/gpttool/gpttool.c
+++ b/gpttool/gpttool.c
@@ -1,5 +1,4 @@
-/* system/core/gpttool/gpttool.c
-**
+/*
 ** Copyright 2011, The Android Open Source Project
 **
 ** Licensed under the Apache License, Version 2.0 (the "License");
@@ -15,18 +14,18 @@
 ** limitations under the License.
 */
 
+#include <fcntl.h>
 #include <stdio.h>
 #include <stdlib.h>
-#include <unistd.h>
 #include <string.h>
-#include <fcntl.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <unistd.h>
 
 #include <zlib.h>
 
 #include <linux/fs.h>
 
-#include <sys/stat.h>
-
 typedef unsigned char u8;
 typedef unsigned short u16;
 typedef unsigned int u32;
@@ -252,11 +251,9 @@
 int main(int argc, char **argv)
 {
 	struct ptable ptbl;
-	struct efi_entry *entry;
 	struct efi_header *hdr = &ptbl.header;
-	struct stat s;
 	u32 n;
-	u64 sz, blk;
+	u64 sz;
 	int fd;
 	const char *device;
 	int real_disk = 0;
diff --git a/include/backtrace/Backtrace.h b/include/backtrace/Backtrace.h
index 3c3a482..e07d322 100644
--- a/include/backtrace/Backtrace.h
+++ b/include/backtrace/Backtrace.h
@@ -47,6 +47,14 @@
 // Forward declarations.
 class BacktraceImpl;
 
+#if defined(__APPLE__)
+struct __darwin_ucontext;
+typedef __darwin_ucontext ucontext_t;
+#else
+struct ucontext;
+typedef ucontext ucontext_t;
+#endif
+
 class Backtrace {
 public:
   // Create the correct Backtrace object based on what is to be unwound.
@@ -64,7 +72,7 @@
   virtual ~Backtrace();
 
   // Get the current stack trace and store in the backtrace_ structure.
-  virtual bool Unwind(size_t num_ignore_frames);
+  virtual bool Unwind(size_t num_ignore_frames, ucontext_t* context = NULL);
 
   // Get the function name and offset into the function given the pc.
   // If the string is empty, then no valid function name was found.
diff --git a/include/utils/RefBase.h b/include/utils/RefBase.h
index cbfe13a..8e15c19 100644
--- a/include/utils/RefBase.h
+++ b/include/utils/RefBase.h
@@ -203,6 +203,13 @@
     mutable volatile int32_t mCount;
 };
 
+// This is a wrapper around LightRefBase that simply enforces a virtual
+// destructor to eliminate the template requirement of LightRefBase
+class VirtualLightRefBase : public LightRefBase<VirtualLightRefBase> {
+public:
+    virtual ~VirtualLightRefBase() {}
+};
+
 // ---------------------------------------------------------------------------
 
 template <typename T>
diff --git a/libbacktrace/Android.mk b/libbacktrace/Android.mk
index a7305da..fa79221 100755
--- a/libbacktrace/Android.mk
+++ b/libbacktrace/Android.mk
@@ -105,10 +105,8 @@
 	GetPss.cpp \
 	thread_utils.c \
 
-backtrace_test_ldlibs := \
-	-lpthread \
-
 backtrace_test_ldlibs_host := \
+	-lpthread \
 	-lrt \
 
 backtrace_test_shared_libraries := \
@@ -118,6 +116,9 @@
 backtrace_test_shared_libraries_target := \
 	libcutils \
 
+backtrace_test_static_libraries_host := \
+	libcutils \
+
 module := backtrace_test
 module_tag := debug
 build_type := target
diff --git a/libbacktrace/BacktraceImpl.cpp b/libbacktrace/BacktraceImpl.cpp
index 05007d9..405b042 100644
--- a/libbacktrace/BacktraceImpl.cpp
+++ b/libbacktrace/BacktraceImpl.cpp
@@ -19,6 +19,7 @@
 #include <string.h>
 #include <sys/ptrace.h>
 #include <sys/types.h>
+#include <ucontext.h>
 #include <unistd.h>
 
 #include <string>
@@ -55,8 +56,8 @@
   }
 }
 
-bool Backtrace::Unwind(size_t num_ignore_frames) {
-  return impl_->Unwind(num_ignore_frames);
+bool Backtrace::Unwind(size_t num_ignore_frames, ucontext_t* ucontext) {
+  return impl_->Unwind(num_ignore_frames, ucontext);
 }
 
 extern "C" char* __cxa_demangle(const char* mangled, char* buf, size_t* len,
diff --git a/libbacktrace/BacktraceImpl.h b/libbacktrace/BacktraceImpl.h
index 7b31c38..d34ad05 100755
--- a/libbacktrace/BacktraceImpl.h
+++ b/libbacktrace/BacktraceImpl.h
@@ -26,7 +26,7 @@
 public:
   virtual ~BacktraceImpl() { }
 
-  virtual bool Unwind(size_t num_ignore_frames) = 0;
+  virtual bool Unwind(size_t num_ignore_frames, ucontext_t* ucontext) = 0;
 
   // The name returned is not demangled, Backtrace::GetFunctionName()
   // takes care of demangling the name.
diff --git a/libbacktrace/BacktraceThread.cpp b/libbacktrace/BacktraceThread.cpp
index e0bab24..018d51f 100644
--- a/libbacktrace/BacktraceThread.cpp
+++ b/libbacktrace/BacktraceThread.cpp
@@ -16,10 +16,15 @@
 
 #include <errno.h>
 #include <inttypes.h>
+#include <limits.h>
+#include <linux/futex.h>
 #include <pthread.h>
 #include <signal.h>
 #include <string.h>
+#include <sys/syscall.h>
+#include <sys/time.h>
 #include <sys/types.h>
+#include <ucontext.h>
 
 #include <cutils/atomic.h>
 
@@ -27,190 +32,173 @@
 #include "BacktraceThread.h"
 #include "thread_utils.h"
 
+static inline int futex(volatile int* uaddr, int op, int val, const struct timespec* ts, volatile int* uaddr2, int val3) {
+  return syscall(__NR_futex, uaddr, op, val, ts, uaddr2, val3);
+}
+
 //-------------------------------------------------------------------------
 // ThreadEntry implementation.
 //-------------------------------------------------------------------------
-static ThreadEntry* g_list = NULL;
-static pthread_mutex_t g_entry_mutex = PTHREAD_MUTEX_INITIALIZER;
-static pthread_mutex_t g_sigaction_mutex = PTHREAD_MUTEX_INITIALIZER;
+ThreadEntry* ThreadEntry::list_ = NULL;
+pthread_mutex_t ThreadEntry::list_mutex_ = PTHREAD_MUTEX_INITIALIZER;
 
-ThreadEntry::ThreadEntry(
-    BacktraceThreadInterface* intf, pid_t pid, pid_t tid, size_t num_ignore_frames)
-    : thread_intf(intf), pid(pid), tid(tid), next(NULL), prev(NULL),
-      state(STATE_WAITING), num_ignore_frames(num_ignore_frames) {
+// Assumes that ThreadEntry::list_mutex_ has already been locked before
+// creating a ThreadEntry object.
+ThreadEntry::ThreadEntry(pid_t pid, pid_t tid)
+    : pid_(pid), tid_(tid), futex_(0), ref_count_(1), mutex_(PTHREAD_MUTEX_INITIALIZER), next_(ThreadEntry::list_), prev_(NULL) {
+  // Add ourselves to the list.
+  if (ThreadEntry::list_) {
+    ThreadEntry::list_->prev_ = this;
+  }
+  ThreadEntry::list_ = this;
 }
 
-ThreadEntry::~ThreadEntry() {
-  pthread_mutex_lock(&g_entry_mutex);
-  if (g_list == this) {
-    g_list = next;
+ThreadEntry* ThreadEntry::Get(pid_t pid, pid_t tid, bool create) {
+  pthread_mutex_lock(&ThreadEntry::list_mutex_);
+  ThreadEntry* entry = list_;
+  while (entry != NULL) {
+    if (entry->Match(pid, tid)) {
+      break;
+    }
+    entry = entry->next_;
+  }
+
+  if (!entry) {
+    if (create) {
+      entry = new ThreadEntry(pid, tid);
+    }
   } else {
-    if (next) {
-      next->prev = prev;
-    }
-    prev->next = next;
+    entry->ref_count_++;
   }
-  pthread_mutex_unlock(&g_entry_mutex);
-
-  next = NULL;
-  prev = NULL;
-}
-
-ThreadEntry* ThreadEntry::AddThreadToUnwind(
-    BacktraceThreadInterface* intf, pid_t pid, pid_t tid, size_t num_ignore_frames) {
-  ThreadEntry* entry = new ThreadEntry(intf, pid, tid, num_ignore_frames);
-
-  pthread_mutex_lock(&g_entry_mutex);
-  ThreadEntry* cur_entry = g_list;
-  while (cur_entry != NULL) {
-    if (cur_entry->Match(pid, tid)) {
-      // There is already an entry for this pid/tid, this is bad.
-      BACK_LOGW("Entry for pid %d tid %d already exists.", pid, tid);
-
-      pthread_mutex_unlock(&g_entry_mutex);
-      return NULL;
-    }
-    cur_entry = cur_entry->next;
-  }
-
-  // Add the entry to the list.
-  entry->next = g_list;
-  if (g_list) {
-    g_list->prev = entry;
-  }
-  g_list = entry;
-  pthread_mutex_unlock(&g_entry_mutex);
+  pthread_mutex_unlock(&ThreadEntry::list_mutex_);
 
   return entry;
 }
 
+void ThreadEntry::Remove(ThreadEntry* entry) {
+  pthread_mutex_unlock(&entry->mutex_);
+
+  pthread_mutex_lock(&ThreadEntry::list_mutex_);
+  if (--entry->ref_count_ == 0) {
+    delete entry;
+  }
+  pthread_mutex_unlock(&ThreadEntry::list_mutex_);
+}
+
+// Assumes that ThreadEntry::list_mutex_ has already been locked before
+// deleting a ThreadEntry object.
+ThreadEntry::~ThreadEntry() {
+  if (list_ == this) {
+    list_ = next_;
+  } else {
+    if (next_) {
+      next_->prev_ = prev_;
+    }
+    prev_->next_ = next_;
+  }
+
+  next_ = NULL;
+  prev_ = NULL;
+}
+
+void ThreadEntry::Wait(int value) {
+  timespec ts;
+  ts.tv_sec = 10;
+  ts.tv_nsec = 0;
+  errno = 0;
+  futex(&futex_, FUTEX_WAIT, value, &ts, NULL, 0);
+  if (errno != 0 && errno != EWOULDBLOCK) {
+    BACK_LOGW("futex wait failed, futex = %d: %s", futex_, strerror(errno));
+  }
+}
+
+void ThreadEntry::Wake() {
+  futex_++;
+  futex(&futex_, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
+}
+
 //-------------------------------------------------------------------------
 // BacktraceThread functions.
 //-------------------------------------------------------------------------
-static void SignalHandler(int n __attribute__((unused)), siginfo_t* siginfo,
-                          void* sigcontext) {
-  if (pthread_mutex_lock(&g_entry_mutex) == 0) {
-    pid_t pid = getpid();
-    pid_t tid = gettid();
-    ThreadEntry* cur_entry = g_list;
-    while (cur_entry) {
-      if (cur_entry->Match(pid, tid)) {
-        break;
-      }
-      cur_entry = cur_entry->next;
-    }
-    pthread_mutex_unlock(&g_entry_mutex);
-    if (!cur_entry) {
-      BACK_LOGW("Unable to find pid %d tid %d information", pid, tid);
-      return;
-    }
+static pthread_mutex_t g_sigaction_mutex = PTHREAD_MUTEX_INITIALIZER;
 
-    if (android_atomic_acquire_cas(STATE_WAITING, STATE_DUMPING, &cur_entry->state) == 0) {
-      cur_entry->thread_intf->ThreadUnwind(siginfo, sigcontext,
-                                           cur_entry->num_ignore_frames);
-    }
-    android_atomic_release_store(STATE_DONE, &cur_entry->state);
+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());
+    return;
   }
+
+  entry->CopyUcontext(reinterpret_cast<ucontext_t*>(sigcontext));
+
+  // Indicate the ucontext is now valid.
+  entry->Wake();
+
+  // Pause the thread until the unwind is complete. This avoids having
+  // the thread run ahead causing problems.
+  entry->Wait(1);
+
+  ThreadEntry::Remove(entry);
 }
 
-BacktraceThread::BacktraceThread(
-    BacktraceImpl* impl, BacktraceThreadInterface* thread_intf, pid_t tid,
-    BacktraceMap* map)
-    : BacktraceCurrent(impl, map), thread_intf_(thread_intf) {
+BacktraceThread::BacktraceThread(BacktraceImpl* impl, pid_t tid, BacktraceMap* map)
+    : BacktraceCurrent(impl, map) {
   tid_ = tid;
 }
 
 BacktraceThread::~BacktraceThread() {
 }
 
-void BacktraceThread::FinishUnwind() {
-  for (std::vector<backtrace_frame_data_t>::iterator it = frames_.begin();
-       it != frames_.end(); ++it) {
-    it->map = FindMap(it->pc);
-
-    it->func_offset = 0;
-    it->func_name = GetFunctionName(it->pc, &it->func_offset);
-  }
-}
-
-bool BacktraceThread::TriggerUnwindOnThread(ThreadEntry* entry) {
-  entry->state = STATE_WAITING;
-
-  if (tgkill(Pid(), Tid(), THREAD_SIGNAL) != 0) {
-    BACK_LOGW("tgkill failed %s", strerror(errno));
-    return false;
-  }
-
-  // Allow up to ten seconds for the dump to start.
-  int wait_millis = 10000;
-  int32_t state;
-  while (true) {
-    state = android_atomic_acquire_load(&entry->state);
-    if (state != STATE_WAITING) {
-      break;
-    }
-    if (wait_millis--) {
-      usleep(1000);
-    } else {
-      break;
-    }
-  }
-
-  bool cancelled = false;
-  if (state == STATE_WAITING) {
-    if (android_atomic_acquire_cas(state, STATE_CANCEL, &entry->state) == 0) {
-      BACK_LOGW("Cancelled dump of thread %d", entry->tid);
-      state = STATE_CANCEL;
-      cancelled = true;
-    } else {
-      state = android_atomic_acquire_load(&entry->state);
-    }
-  }
-
-  // Wait for at most ten seconds for the cancel or dump to finish.
-  wait_millis = 10000;
-  while (android_atomic_acquire_load(&entry->state) != STATE_DONE) {
-    if (wait_millis--) {
-      usleep(1000);
-    } else {
-      BACK_LOGW("Didn't finish thread unwind in 60 seconds.");
-      break;
-    }
-  }
-  return !cancelled;
-}
-
-bool BacktraceThread::Unwind(size_t num_ignore_frames) {
-  ThreadEntry* entry = ThreadEntry::AddThreadToUnwind(
-      thread_intf_, Pid(), Tid(), num_ignore_frames);
-  if (!entry) {
-    return false;
+bool BacktraceThread::Unwind(size_t num_ignore_frames, ucontext_t* ucontext) {
+  if (ucontext) {
+    // Unwind using an already existing ucontext.
+    return impl_->Unwind(num_ignore_frames, ucontext);
   }
 
   // Prevent multiple threads trying to set the trigger action on different
   // threads at the same time.
-  bool retval = false;
-  if (pthread_mutex_lock(&g_sigaction_mutex) == 0) {
-    struct sigaction act, oldact;
-    memset(&act, 0, sizeof(act));
-    act.sa_sigaction = SignalHandler;
-    act.sa_flags = SA_RESTART | SA_SIGINFO | SA_ONSTACK;
-    sigemptyset(&act.sa_mask);
-    if (sigaction(THREAD_SIGNAL, &act, &oldact) == 0) {
-      retval = TriggerUnwindOnThread(entry);
-      sigaction(THREAD_SIGNAL, &oldact, NULL);
-    } else {
-      BACK_LOGW("sigaction failed %s", strerror(errno));
-    }
+  if (pthread_mutex_lock(&g_sigaction_mutex) < 0) {
+    BACK_LOGW("sigaction failed: %s", strerror(errno));
+    return false;
+  }
+
+  ThreadEntry* entry = ThreadEntry::Get(Pid(), Tid());
+  entry->Lock();
+
+  struct sigaction act, oldact;
+  memset(&act, 0, sizeof(act));
+  act.sa_sigaction = SignalHandler;
+  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();
+    ThreadEntry::Remove(entry);
     pthread_mutex_unlock(&g_sigaction_mutex);
-  } else {
-    BACK_LOGW("unable to acquire sigaction mutex.");
+    return false;
   }
 
-  if (retval) {
-    FinishUnwind();
+  if (tgkill(Pid(), Tid(), THREAD_SIGNAL) != 0) {
+    BACK_LOGW("tgkill %d failed: %s", Tid(), strerror(errno));
+    sigaction(THREAD_SIGNAL, &oldact, NULL);
+    entry->Unlock();
+    ThreadEntry::Remove(entry);
+    pthread_mutex_unlock(&g_sigaction_mutex);
+    return false;
   }
-  delete entry;
 
-  return retval;
+  // Wait for the thread to get the ucontext.
+  entry->Wait(0);
+
+  // After the thread has received the signal, allow other unwinders to
+  // continue.
+  sigaction(THREAD_SIGNAL, &oldact, NULL);
+  pthread_mutex_unlock(&g_sigaction_mutex);
+
+  bool unwind_done = impl_->Unwind(num_ignore_frames, entry->GetUcontext());
+
+  // Tell the signal handler to exit and release the entry.
+  entry->Wake();
+
+  return unwind_done;
 }
diff --git a/libbacktrace/BacktraceThread.h b/libbacktrace/BacktraceThread.h
index 9310a44..a75a807 100644
--- a/libbacktrace/BacktraceThread.h
+++ b/libbacktrace/BacktraceThread.h
@@ -18,18 +18,14 @@
 #define _LIBBACKTRACE_BACKTRACE_THREAD_H
 
 #include <inttypes.h>
+#include <pthread.h>
 #include <signal.h>
+#include <string.h>
 #include <sys/types.h>
+#include <ucontext.h>
 
 #include "BacktraceImpl.h"
 
-enum state_e {
-  STATE_WAITING = 0,
-  STATE_DUMPING,
-  STATE_DONE,
-  STATE_CANCEL,
-};
-
 // The signal used to cause a thread to dump the stack.
 #if defined(__GLIBC__)
 // GLIBC reserves __SIGRTMIN signals, so use SIGRTMIN to avoid errors.
@@ -38,62 +34,57 @@
 #define THREAD_SIGNAL (__SIGRTMIN+1)
 #endif
 
-class BacktraceThreadInterface;
+class ThreadEntry {
+public:
+  static ThreadEntry* Get(pid_t pid, pid_t tid, bool create = true);
 
-struct ThreadEntry {
-  ThreadEntry(
-      BacktraceThreadInterface* impl, pid_t pid, pid_t tid,
-      size_t num_ignore_frames);
+  static void Remove(ThreadEntry* entry);
+
+  inline void CopyUcontext(ucontext_t* ucontext) {
+    memcpy(&ucontext_, ucontext, sizeof(ucontext_));
+  }
+
+  void Wake();
+
+  void Wait(int);
+
+  inline void Lock() {
+    pthread_mutex_lock(&mutex_);
+    // Reset the futex value in case of multiple unwinds of the same thread.
+    futex_ = 0;
+  }
+
+  inline void Unlock() {
+    pthread_mutex_unlock(&mutex_);
+  }
+
+  inline ucontext_t* GetUcontext() { return &ucontext_; }
+
+private:
+  ThreadEntry(pid_t pid, pid_t tid);
   ~ThreadEntry();
 
-  bool Match(pid_t chk_pid, pid_t chk_tid) { return (chk_pid == pid && chk_tid == tid); }
+  bool Match(pid_t chk_pid, pid_t chk_tid) { return (chk_pid == pid_ && chk_tid == tid_); }
 
-  static ThreadEntry* AddThreadToUnwind(
-      BacktraceThreadInterface* thread_intf, pid_t pid, pid_t tid,
-      size_t num_ignored_frames);
+  pid_t pid_;
+  pid_t tid_;
+  int futex_;
+  int ref_count_;
+  pthread_mutex_t mutex_;
+  ThreadEntry* next_;
+  ThreadEntry* prev_;
+  ucontext_t ucontext_;
 
-  BacktraceThreadInterface* thread_intf;
-  pid_t pid;
-  pid_t tid;
-  ThreadEntry* next;
-  ThreadEntry* prev;
-  int32_t state;
-  int num_ignore_frames;
-};
-
-// Interface class that does not contain any local storage, only defines
-// virtual functions to be defined by subclasses.
-class BacktraceThreadInterface {
-public:
-  virtual ~BacktraceThreadInterface() { }
-
-  virtual void ThreadUnwind(
-      siginfo_t* siginfo, void* sigcontext, size_t num_ignore_frames) = 0;
+  static ThreadEntry* list_;
+  static pthread_mutex_t list_mutex_;
 };
 
 class BacktraceThread : public BacktraceCurrent {
 public:
-  // impl and thread_intf should point to the same object, this allows
-  // the compiler to catch if an implementation does not properly
-  // subclass both.
-  BacktraceThread(
-      BacktraceImpl* impl, BacktraceThreadInterface* thread_intf, pid_t tid,
-      BacktraceMap* map);
+  BacktraceThread(BacktraceImpl* impl, pid_t tid, BacktraceMap* map);
   virtual ~BacktraceThread();
 
-  virtual bool Unwind(size_t num_ignore_frames);
-
-  virtual void ThreadUnwind(
-      siginfo_t* siginfo, void* sigcontext, size_t num_ignore_frames) {
-    thread_intf_->ThreadUnwind(siginfo, sigcontext, num_ignore_frames);
-  }
-
-private:
-  virtual bool TriggerUnwindOnThread(ThreadEntry* entry);
-
-  virtual void FinishUnwind();
-
-  BacktraceThreadInterface* thread_intf_;
+  virtual bool Unwind(size_t num_ignore_frames, ucontext_t* ucontext);
 };
 
 #endif // _LIBBACKTRACE_BACKTRACE_THREAD_H
diff --git a/libbacktrace/UnwindCurrent.cpp b/libbacktrace/UnwindCurrent.cpp
index 67d372a..b176aaf 100755
--- a/libbacktrace/UnwindCurrent.cpp
+++ b/libbacktrace/UnwindCurrent.cpp
@@ -14,8 +14,8 @@
  * limitations under the License.
  */
 
-#include <sys/ucontext.h>
 #include <sys/types.h>
+#include <ucontext.h>
 
 #include <backtrace/Backtrace.h>
 #include <backtrace/BacktraceMap.h>
@@ -24,6 +24,7 @@
 #include <libunwind.h>
 
 #include "BacktraceLog.h"
+#include "BacktraceThread.h"
 #include "UnwindCurrent.h"
 #include "UnwindMap.h"
 
@@ -36,15 +37,45 @@
 UnwindCurrent::~UnwindCurrent() {
 }
 
-bool UnwindCurrent::Unwind(size_t num_ignore_frames) {
-  int ret = unw_getcontext(&context_);
-  if (ret < 0) {
-    BACK_LOGW("unw_getcontext failed %d", ret);
-    return false;
+bool UnwindCurrent::Unwind(size_t num_ignore_frames, ucontext_t* ucontext) {
+  if (!ucontext) {
+    int ret = unw_getcontext(&context_);
+    if (ret < 0) {
+      BACK_LOGW("unw_getcontext failed %d", ret);
+      return false;
+    }
+  }
+  else {
+    GetUnwContextFromUcontext(ucontext);
   }
   return UnwindFromContext(num_ignore_frames, false);
 }
 
+void UnwindCurrent::GetUnwContextFromUcontext(const ucontext_t* ucontext) {
+  unw_tdep_context_t* unw_context = reinterpret_cast<unw_tdep_context_t*>(&context_);
+
+#if defined(__arm__)
+  unw_context->regs[0] = ucontext->uc_mcontext.arm_r0;
+  unw_context->regs[1] = ucontext->uc_mcontext.arm_r1;
+  unw_context->regs[2] = ucontext->uc_mcontext.arm_r2;
+  unw_context->regs[3] = ucontext->uc_mcontext.arm_r3;
+  unw_context->regs[4] = ucontext->uc_mcontext.arm_r4;
+  unw_context->regs[5] = ucontext->uc_mcontext.arm_r5;
+  unw_context->regs[6] = ucontext->uc_mcontext.arm_r6;
+  unw_context->regs[7] = ucontext->uc_mcontext.arm_r7;
+  unw_context->regs[8] = ucontext->uc_mcontext.arm_r8;
+  unw_context->regs[9] = ucontext->uc_mcontext.arm_r9;
+  unw_context->regs[10] = ucontext->uc_mcontext.arm_r10;
+  unw_context->regs[11] = ucontext->uc_mcontext.arm_fp;
+  unw_context->regs[12] = ucontext->uc_mcontext.arm_ip;
+  unw_context->regs[13] = ucontext->uc_mcontext.arm_sp;
+  unw_context->regs[14] = ucontext->uc_mcontext.arm_lr;
+  unw_context->regs[15] = ucontext->uc_mcontext.arm_pc;
+#else
+  unw_context->uc_mcontext = ucontext->uc_mcontext;
+#endif
+}
+
 std::string UnwindCurrent::GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset) {
   *offset = 0;
   char buf[512];
@@ -122,47 +153,6 @@
   return true;
 }
 
-void UnwindCurrent::ExtractContext(void* sigcontext) {
-  unw_tdep_context_t* context = reinterpret_cast<unw_tdep_context_t*>(&context_);
-  const ucontext_t* uc = reinterpret_cast<const ucontext_t*>(sigcontext);
-
-#if defined(__arm__)
-  context->regs[0] = uc->uc_mcontext.arm_r0;
-  context->regs[1] = uc->uc_mcontext.arm_r1;
-  context->regs[2] = uc->uc_mcontext.arm_r2;
-  context->regs[3] = uc->uc_mcontext.arm_r3;
-  context->regs[4] = uc->uc_mcontext.arm_r4;
-  context->regs[5] = uc->uc_mcontext.arm_r5;
-  context->regs[6] = uc->uc_mcontext.arm_r6;
-  context->regs[7] = uc->uc_mcontext.arm_r7;
-  context->regs[8] = uc->uc_mcontext.arm_r8;
-  context->regs[9] = uc->uc_mcontext.arm_r9;
-  context->regs[10] = uc->uc_mcontext.arm_r10;
-  context->regs[11] = uc->uc_mcontext.arm_fp;
-  context->regs[12] = uc->uc_mcontext.arm_ip;
-  context->regs[13] = uc->uc_mcontext.arm_sp;
-  context->regs[14] = uc->uc_mcontext.arm_lr;
-  context->regs[15] = uc->uc_mcontext.arm_pc;
-#else
-  context->uc_mcontext = uc->uc_mcontext;
-#endif
-}
-
-//-------------------------------------------------------------------------
-// UnwindThread functions.
-//-------------------------------------------------------------------------
-UnwindThread::UnwindThread() {
-}
-
-UnwindThread::~UnwindThread() {
-}
-
-void UnwindThread::ThreadUnwind(
-    siginfo_t* /*siginfo*/, void* sigcontext, size_t num_ignore_frames) {
-  ExtractContext(sigcontext);
-  UnwindFromContext(num_ignore_frames, true);
-}
-
 //-------------------------------------------------------------------------
 // C++ object creation function.
 //-------------------------------------------------------------------------
@@ -171,6 +161,5 @@
 }
 
 Backtrace* CreateThreadObj(pid_t tid, BacktraceMap* map) {
-  UnwindThread* thread_obj = new UnwindThread();
-  return new BacktraceThread(thread_obj, thread_obj, tid, map);
+  return new BacktraceThread(new UnwindCurrent(), tid, map);
 }
diff --git a/libbacktrace/UnwindCurrent.h b/libbacktrace/UnwindCurrent.h
index 41080c7..2375e6e 100644
--- a/libbacktrace/UnwindCurrent.h
+++ b/libbacktrace/UnwindCurrent.h
@@ -20,7 +20,6 @@
 #include <string>
 
 #include "BacktraceImpl.h"
-#include "BacktraceThread.h"
 
 #define UNW_LOCAL_ONLY
 #include <libunwind.h>
@@ -30,25 +29,16 @@
   UnwindCurrent();
   virtual ~UnwindCurrent();
 
-  virtual bool Unwind(size_t num_ignore_frames);
+  virtual bool Unwind(size_t num_ignore_frames, ucontext_t* ucontext);
 
   virtual std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset);
 
   bool UnwindFromContext(size_t num_ignore_frames, bool within_handler);
 
-  void ExtractContext(void* sigcontext);
+  void GetUnwContextFromUcontext(const ucontext_t* context);
 
 protected:
   unw_context_t context_;
 };
 
-class UnwindThread : public UnwindCurrent, public BacktraceThreadInterface {
-public:
-  UnwindThread();
-  virtual ~UnwindThread();
-
-  virtual void ThreadUnwind(
-      siginfo_t* siginfo, void* sigcontext, size_t num_ignore_frames);
-};
-
 #endif // _LIBBACKTRACE_UNWIND_CURRENT_H
diff --git a/libbacktrace/UnwindPtrace.cpp b/libbacktrace/UnwindPtrace.cpp
index 5ca7e60..7ba8775 100644
--- a/libbacktrace/UnwindPtrace.cpp
+++ b/libbacktrace/UnwindPtrace.cpp
@@ -19,6 +19,7 @@
 
 #include <sys/types.h>
 #include <string.h>
+#include <ucontext.h>
 
 #include <libunwind.h>
 #include <libunwind-ptrace.h>
@@ -45,7 +46,12 @@
   }
 }
 
-bool UnwindPtrace::Unwind(size_t num_ignore_frames) {
+bool UnwindPtrace::Unwind(size_t num_ignore_frames, ucontext_t* ucontext) {
+  if (ucontext) {
+    BACK_LOGW("Unwinding from a specified context not supported yet.");
+    return false;
+  }
+
   addr_space_ = unw_create_addr_space(&_UPT_accessors, 0);
   if (!addr_space_) {
     BACK_LOGW("unw_create_addr_space failed.");
diff --git a/libbacktrace/UnwindPtrace.h b/libbacktrace/UnwindPtrace.h
index 1e82117..2fb7967 100644
--- a/libbacktrace/UnwindPtrace.h
+++ b/libbacktrace/UnwindPtrace.h
@@ -28,7 +28,7 @@
   UnwindPtrace();
   virtual ~UnwindPtrace();
 
-  virtual bool Unwind(size_t num_ignore_frames);
+  virtual bool Unwind(size_t num_ignore_frames, ucontext_t* ucontext);
 
   virtual std::string GetFunctionNameRaw(uintptr_t pc, uintptr_t* offset);
 
diff --git a/libbacktrace/backtrace_test.cpp b/libbacktrace/backtrace_test.cpp
index 9744922..ed6b211 100644
--- a/libbacktrace/backtrace_test.cpp
+++ b/libbacktrace/backtrace_test.cpp
@@ -615,6 +615,49 @@
   }
 }
 
+TEST(libbacktrace, thread_multiple_dump_same_thread) {
+  pthread_attr_t attr;
+  pthread_attr_init(&attr);
+  pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
+  thread_t runner;
+  runner.tid = 0;
+  runner.state = 0;
+  ASSERT_TRUE(pthread_create(&runner.threadId, &attr, ThreadMaxRun, &runner) == 0);
+
+  // Wait for tids to be set.
+  ASSERT_TRUE(WaitForNonZero(&runner.state, 10));
+
+  // Start all of the dumpers at once, they will spin until they are signalled
+  // to begin their dump run.
+  int32_t dump_now = 0;
+  // Dump the same thread NUM_THREADS simultaneously.
+  std::vector<dump_thread_t> dumpers(NUM_THREADS);
+  for (size_t i = 0; i < NUM_THREADS; i++) {
+    dumpers[i].thread.tid = runner.tid;
+    dumpers[i].thread.state = 0;
+    dumpers[i].done = 0;
+    dumpers[i].now = &dump_now;
+
+    ASSERT_TRUE(pthread_create(&dumpers[i].thread.threadId, &attr, ThreadDump, &dumpers[i]) == 0);
+  }
+
+  // Start all of the dumpers going at once.
+  android_atomic_acquire_store(1, &dump_now);
+
+  for (size_t i = 0; i < NUM_THREADS; i++) {
+    ASSERT_TRUE(WaitForNonZero(&dumpers[i].done, 100));
+
+    ASSERT_TRUE(dumpers[i].backtrace != NULL);
+    VerifyMaxDump(dumpers[i].backtrace);
+
+    delete dumpers[i].backtrace;
+    dumpers[i].backtrace = NULL;
+  }
+
+  // Tell the runner thread to exit its infinite loop.
+  android_atomic_acquire_store(0, &runner.state);
+}
+
 // This test is for UnwindMaps that should share the same map cursor when
 // multiple maps are created for the current process at the same time.
 TEST(libbacktrace, simultaneous_maps) {
diff --git a/libcutils/Android.mk b/libcutils/Android.mk
index 2dcc965..945ebdd 100644
--- a/libcutils/Android.mk
+++ b/libcutils/Android.mk
@@ -75,7 +75,6 @@
 # ========================================================
 LOCAL_MODULE := libcutils
 LOCAL_SRC_FILES := $(commonSources) $(commonHostSources) dlmalloc_stubs.c
-LOCAL_LDLIBS := -lpthread
 LOCAL_STATIC_LIBRARIES := liblog
 LOCAL_CFLAGS += $(hostSmpFlag)
 ifneq ($(HOST_OS),windows)
@@ -89,7 +88,6 @@
 include $(CLEAR_VARS)
 LOCAL_MODULE := lib64cutils
 LOCAL_SRC_FILES := $(commonSources) $(commonHostSources) dlmalloc_stubs.c
-LOCAL_LDLIBS := -lpthread
 LOCAL_STATIC_LIBRARIES := lib64log
 LOCAL_CFLAGS += $(hostSmpFlag) -m64
 ifneq ($(HOST_OS),windows)
diff --git a/liblog/Android.mk b/liblog/Android.mk
index 5e01903..69ca416 100644
--- a/liblog/Android.mk
+++ b/liblog/Android.mk
@@ -57,11 +57,7 @@
 # ========================================================
 LOCAL_MODULE := liblog
 LOCAL_SRC_FILES := $(liblog_host_sources)
-LOCAL_LDLIBS := -lpthread
-ifeq ($(strip $(HOST_OS)),linux)
-LOCAL_LDLIBS += -lrt
-endif
-LOCAL_CFLAGS := -DFAKE_LOG_DEVICE=1
+LOCAL_CFLAGS := -DFAKE_LOG_DEVICE=1 -Werror
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
@@ -78,11 +74,7 @@
 include $(CLEAR_VARS)
 LOCAL_MODULE := lib64log
 LOCAL_SRC_FILES := $(liblog_host_sources)
-LOCAL_LDLIBS := -lpthread
-ifeq ($(strip $(HOST_OS)),linux)
-LOCAL_LDLIBS += -lrt
-endif
-LOCAL_CFLAGS := -DFAKE_LOG_DEVICE=1 -m64
+LOCAL_CFLAGS := -DFAKE_LOG_DEVICE=1 -m64 -Werror
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 # Shared and static library for target
@@ -90,13 +82,13 @@
 include $(CLEAR_VARS)
 LOCAL_MODULE := liblog
 LOCAL_SRC_FILES := $(liblog_target_sources)
-LOCAL_CFLAGS := $(liblog_cflags)
+LOCAL_CFLAGS := -Werror
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
 LOCAL_MODULE := liblog
 LOCAL_WHOLE_STATIC_LIBRARIES := liblog
-LOCAL_CFLAGS := $(liblog_cflags)
+LOCAL_CFLAGS := -Werror
 include $(BUILD_SHARED_LIBRARY)
 
 include $(call first-makefiles-under,$(LOCAL_PATH))
diff --git a/liblog/event_tag_map.c b/liblog/event_tag_map.c
index f3d1e2f..bea99aa 100644
--- a/liblog/event_tag_map.c
+++ b/liblog/event_tag_map.c
@@ -13,15 +13,16 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-#include <log/event_tag_map.h>
-#include <log/log.h>
 
+#include <assert.h>
+#include <errno.h>
+#include <fcntl.h>
 #include <stdlib.h>
 #include <string.h>
-#include <fcntl.h>
 #include <sys/mman.h>
-#include <errno.h>
-#include <assert.h>
+
+#include <log/event_tag_map.h>
+#include <log/log.h>
 
 #define OUT_TAG "EventTagMap"
 
@@ -52,7 +53,6 @@
 static int parseMapLines(EventTagMap* map);
 static int scanTagLine(char** pData, EventTag* tag, int lineNum);
 static int sortTags(EventTagMap* map);
-static void dumpTags(const EventTagMap* map);
 
 
 /*
@@ -185,8 +185,6 @@
  */
 static int processFile(EventTagMap* map)
 {
-    EventTag* tagArray = NULL;
-
     /* get a tag count */
     map->numTags = countMapLines(map);
     if (map->numTags < 0)
@@ -422,17 +420,3 @@
 
     return 0;
 }
-
-/*
- * Dump the tag array for debugging.
- */
-static void dumpTags(const EventTagMap* map)
-{
-    int i;
-
-    for (i = 0; i < map->numTags; i++) {
-        const EventTag* tag = &map->tagArray[i];
-        printf("  %3d: %6d '%s'\n", i, tag->tagIndex, tag->tagStr);
-    }
-}
-
diff --git a/liblog/fake_log_device.c b/liblog/fake_log_device.c
index da83a85..136792d 100644
--- a/liblog/fake_log_device.c
+++ b/liblog/fake_log_device.c
@@ -21,18 +21,22 @@
  */
 #include "fake_log_device.h"
 
-#include <log/logd.h>
-
-#include <stdlib.h>
-#include <string.h>
 #include <ctype.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <log/logd.h>
 
 #ifdef HAVE_PTHREADS
 #include <pthread.h>
 #endif
 
+#ifndef __unused
+#define __unused __attribute__((__unused__))
+#endif
+
 #define kMaxTagLen  16      /* from the long-dead utils/Log.cpp */
 
 #define kTagSetSize 16      /* arbitrary */
@@ -613,7 +617,7 @@
 /*
  * Open a log output device and return a fake fd.
  */
-static int logOpen(const char* pathName, int flags)
+static int logOpen(const char* pathName, int flags __unused)
 {
     LogState *logState;
     int fd = -1;
diff --git a/liblog/log_read.c b/liblog/log_read.c
index 11fe848..ca5a1a7 100644
--- a/liblog/log_read.c
+++ b/liblog/log_read.c
@@ -23,6 +23,7 @@
 #define NOMINMAX /* for windows to suppress definition of min in stdlib.h */
 #include <stdlib.h>
 #include <string.h>
+#include <sys/cdefs.h>
 #include <unistd.h>
 
 #include <cutils/list.h>
@@ -34,7 +35,9 @@
 #define min(x,y) ((y) ^ (((x) ^ (y)) & -((x) < (y))))
 
 #define WEAK __attribute__((weak))
-#define UNUSED __attribute__((unused))
+#ifndef __unused
+#define __unused __attribute__((unused))
+#endif
 
 /* Private copy of ../libcutils/socket_local_client.c prevent library loops */
 
@@ -142,11 +145,10 @@
  * Used by AndroidSocketImpl
  */
 int WEAK socket_local_client_connect(int fd, const char *name, int namespaceId,
-                                     int type UNUSED)
+                                     int type __unused)
 {
     struct sockaddr_un addr;
     socklen_t alen;
-    size_t namelen;
     int err;
 
     err = socket_make_sockaddr_un(name, namespaceId, &addr, &alen);
@@ -409,7 +411,7 @@
 /*
  * returns the logger version
  */
-int android_logger_get_log_version(struct logger *logger UNUSED)
+int android_logger_get_log_version(struct logger *logger __unused)
 {
     return 3;
 }
@@ -420,7 +422,6 @@
 ssize_t android_logger_get_statistics(struct logger_list *logger_list,
                                       char *buf, size_t len)
 {
-    struct listnode *node;
     struct logger *logger;
     char *cp = buf;
     size_t remaining = len;
@@ -440,13 +441,13 @@
     return send_log_msg(NULL, NULL, buf, len);
 }
 
-ssize_t android_logger_get_prune_list(struct logger_list *logger_list UNUSED,
+ssize_t android_logger_get_prune_list(struct logger_list *logger_list __unused,
                                       char *buf, size_t len)
 {
     return send_log_msg(NULL, "getPruneList", buf, len);
 }
 
-int android_logger_set_prune_list(struct logger_list *logger_list UNUSED,
+int android_logger_set_prune_list(struct logger_list *logger_list __unused,
                                   char *buf, size_t len)
 {
     const char cmd[] = "setPruneList ";
@@ -512,9 +513,7 @@
 struct logger *android_logger_open(struct logger_list *logger_list,
                                    log_id_t id)
 {
-    struct listnode *node;
     struct logger *logger;
-    char *n;
 
     if (!logger_list || (id >= LOG_ID_MAX)) {
         goto err;
@@ -561,7 +560,7 @@
     return logger_list;
 }
 
-static void caught_signal(int signum UNUSED)
+static void caught_signal(int signum __unused)
 {
 }
 
diff --git a/liblog/log_read_kern.c b/liblog/log_read_kern.c
index 021fe47..41b8a51 100644
--- a/liblog/log_read_kern.c
+++ b/liblog/log_read_kern.c
@@ -21,12 +21,13 @@
 #include <string.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <sys/cdefs.h>
+#include <sys/ioctl.h>
+
 #include <cutils/list.h>
 #include <log/log.h>
 #include <log/logger.h>
 
-#include <sys/ioctl.h>
-
 #define __LOGGERIO     0xAE
 
 #define LOGGER_GET_LOG_BUF_SIZE    _IO(__LOGGERIO, 1) /* size of log */
@@ -51,7 +52,9 @@
          logger != node_to_item(&(logger_list)->node, struct logger, node); \
          logger = node_to_item((logger)->node.next, struct logger, node))
 
-#define UNUSED __attribute__((unused))
+#ifndef __unused
+#define __unused __attribute__((unused))
+#endif
 
 /* In the future, we would like to make this list extensible */
 static const char *LOG_NAME[LOG_ID_MAX] = {
@@ -233,8 +236,8 @@
     return logger_ioctl(logger, LOGGER_GET_LOG_BUF_SIZE, O_RDWR);
 }
 
-int android_logger_set_log_size(struct logger *logger UNUSED,
-                                unsigned long size UNUSED)
+int android_logger_set_log_size(struct logger *logger __unused,
+                                unsigned long size __unused)
 {
     return -ENOTSUP;
 }
@@ -262,21 +265,21 @@
  */
 static const char unsupported[] = "18\nNot Supported\n\f";
 
-ssize_t android_logger_get_statistics(struct logger_list *logger_list UNUSED,
+ssize_t android_logger_get_statistics(struct logger_list *logger_list __unused,
                                       char *buf, size_t len)
 {
     strncpy(buf, unsupported, len);
     return -ENOTSUP;
 }
 
-ssize_t android_logger_get_prune_list(struct logger_list *logger_list UNUSED,
+ssize_t android_logger_get_prune_list(struct logger_list *logger_list __unused,
                                       char *buf, size_t len)
 {
     strncpy(buf, unsupported, len);
     return -ENOTSUP;
 }
 
-int android_logger_set_prune_list(struct logger_list *logger_list UNUSED,
+int android_logger_set_prune_list(struct logger_list *logger_list __unused,
                                   char *buf, size_t len)
 {
     static const char unsupported_error[] = "Unsupported";
@@ -302,7 +305,7 @@
 }
 
 struct logger_list *android_logger_list_alloc_time(int mode,
-                                                   log_time start UNUSED,
+                                                   log_time start __unused,
                                                    pid_t pid)
 {
     return android_logger_list_alloc(mode, 0, pid);
diff --git a/liblog/logd_write.c b/liblog/logd_write.c
index 4c47382..121d84d 100644
--- a/liblog/logd_write.c
+++ b/liblog/logd_write.c
@@ -49,12 +49,15 @@
 static pthread_mutex_t log_init_lock = PTHREAD_MUTEX_INITIALIZER;
 #endif
 
-#define UNUSED  __attribute__((__unused__))
+#ifndef __unused
+#define __unused  __attribute__((__unused__))
+#endif
 
-static int logd_fd = -1;
 #if FAKE_LOG_DEVICE
 #define WEAK __attribute__((weak))
 static int log_fds[(int)LOG_ID_MAX] = { -1, -1, -1, -1, -1 };
+#else
+static int logd_fd = -1;
 #endif
 
 /*
@@ -77,12 +80,14 @@
     return (g_log_status == kLogAvailable);
 }
 
+#if !FAKE_LOG_DEVICE
 /* give up, resources too limited */
-static int __write_to_log_null(log_id_t log_fd UNUSED, struct iovec *vec UNUSED,
-                               size_t nr UNUSED)
+static int __write_to_log_null(log_id_t log_fd __unused, struct iovec *vec __unused,
+                               size_t nr __unused)
 {
     return -1;
 }
+#endif
 
 /* log_init_lock assumed */
 static int __write_to_log_initialize()
diff --git a/liblog/logd_write_kern.c b/liblog/logd_write_kern.c
index 982beaa..1d10748 100644
--- a/liblog/logd_write_kern.c
+++ b/liblog/logd_write_kern.c
@@ -57,7 +57,9 @@
 static pthread_mutex_t log_init_lock = PTHREAD_MUTEX_INITIALIZER;
 #endif
 
-#define UNUSED  __attribute__((__unused__))
+#ifndef __unused
+#define __unused  __attribute__((__unused__))
+#endif
 
 static int log_fds[(int)LOG_ID_MAX] = { -1, -1, -1, -1 };
 
@@ -81,8 +83,8 @@
     return (g_log_status == kLogAvailable);
 }
 
-static int __write_to_log_null(log_id_t log_fd UNUSED, struct iovec *vec UNUSED,
-                               size_t nr UNUSED)
+static int __write_to_log_null(log_id_t log_fd __unused, struct iovec *vec __unused,
+                               size_t nr __unused)
 {
     return -1;
 }
diff --git a/liblog/logprint.c b/liblog/logprint.c
index 3bc9f5a..08e830a 100644
--- a/liblog/logprint.c
+++ b/liblog/logprint.c
@@ -17,14 +17,14 @@
 
 #define _GNU_SOURCE /* for asprintf */
 
-#include <ctype.h>
-#include <stdio.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <stdint.h>
-#include <string.h>
-#include <assert.h>
 #include <arpa/inet.h>
+#include <assert.h>
+#include <ctype.h>
+#include <errno.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 
 #include <log/logd.h>
 #include <log/logprint.h>
@@ -52,15 +52,7 @@
     return p_ret;
 }
 
-static void filterinfo_free(FilterInfo *p_info)
-{
-    if (p_info == NULL) {
-        return;
-    }
-
-    free(p_info->mTag);
-    p_info->mTag = NULL;
-}
+/* balance to above, filterinfo_free left unimplemented */
 
 /*
  * Note: also accepts 0-9 priorities
@@ -139,23 +131,6 @@
     return p_format->global_pri;
 }
 
-/** for debugging */
-static void dumpFilters(AndroidLogFormat *p_format)
-{
-    FilterInfo *p_fi;
-
-    for (p_fi = p_format->filters ; p_fi != NULL ; p_fi = p_fi->p_next) {
-        char cPri = filterPriToChar(p_fi->mPri);
-        if (p_fi->mPri == ANDROID_LOG_DEFAULT) {
-            cPri = filterPriToChar(p_format->global_pri);
-        }
-        fprintf(stderr,"%s:%c\n", p_fi->mTag, cPri);
-    }
-
-    fprintf(stderr,"*:%c\n", filterPriToChar(p_format->global_pri));
-
-}
-
 /**
  * returns 1 if this log line should be printed based on its priority
  * and tag, and 0 if it should not
@@ -234,7 +209,6 @@
 int android_log_addFilterRule(AndroidLogFormat *p_format,
         const char *filterExpression)
 {
-    size_t i=0;
     size_t tagNameLength;
     android_LogPriority pri = ANDROID_LOG_DEFAULT;
 
@@ -718,7 +692,6 @@
 #endif
     struct tm* ptm;
     char timeBuf[32];
-    char headerBuf[128];
     char prefixBuf[128], suffixBuf[128];
     char priChar;
     int prefixSuffixIsHeaderFooter = 0;
@@ -817,7 +790,6 @@
     /* the following code is tragically unreadable */
 
     size_t numLines;
-    size_t i;
     char *p;
     size_t bufferSize;
     const char *pm;
diff --git a/liblog/tests/Android.mk b/liblog/tests/Android.mk
index d1d9115..255dc2e 100644
--- a/liblog/tests/Android.mk
+++ b/liblog/tests/Android.mk
@@ -83,7 +83,6 @@
 LOCAL_MODULE_TAGS := $(test_tags)
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_CFLAGS += $(test_c_flags)
-LOCAL_LDLIBS := -lpthread
 LOCAL_SHARED_LIBRARIES := liblog
 LOCAL_SRC_FILES := $(test_src_files)
 include $(BUILD_NATIVE_TEST)
diff --git a/liblog/tests/liblog_benchmark.cpp b/liblog/tests/liblog_benchmark.cpp
index 39fe2ad..549d79e 100644
--- a/liblog/tests/liblog_benchmark.cpp
+++ b/liblog/tests/liblog_benchmark.cpp
@@ -99,7 +99,7 @@
 }
 BENCHMARK(BM_log_overhead);
 
-static void caught_latency(int signum)
+static void caught_latency(int /*signum*/)
 {
     unsigned long long v = 0xDEADBEEFA55A5AA5ULL;
 
@@ -193,7 +193,7 @@
 }
 BENCHMARK(BM_log_latency);
 
-static void caught_delay(int signum)
+static void caught_delay(int /*signum*/)
 {
     unsigned long long v = 0xDEADBEEFA55A5AA6ULL;
 
diff --git a/liblog/tests/liblog_test.cpp b/liblog/tests/liblog_test.cpp
index c6f981f..ec35e45 100644
--- a/liblog/tests/liblog_test.cpp
+++ b/liblog/tests/liblog_test.cpp
@@ -164,7 +164,7 @@
 static unsigned signaled;
 log_time signal_time;
 
-static void caught_blocking(int signum)
+static void caught_blocking(int /*signum*/)
 {
     unsigned long long v = 0xDEADBEEFA55A0000ULL;
 
diff --git a/libmincrypt/dsa_sig.c b/libmincrypt/dsa_sig.c
index 8df6cf7..101314b 100644
--- a/libmincrypt/dsa_sig.c
+++ b/libmincrypt/dsa_sig.c
@@ -26,6 +26,7 @@
 
 #include <string.h>
 
+#include "mincrypt/dsa_sig.h"
 #include "mincrypt/p256.h"
 
 /**
diff --git a/libmincrypt/test/ecdsa_test.c b/libmincrypt/test/ecdsa_test.c
index b5a7b3a..24ec013 100644
--- a/libmincrypt/test/ecdsa_test.c
+++ b/libmincrypt/test/ecdsa_test.c
@@ -24,15 +24,21 @@
  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include <stdio.h>
 #include <ctype.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/cdefs.h>
 
+#include "mincrypt/dsa_sig.h"
 #include "mincrypt/p256.h"
 #include "mincrypt/p256_ecdsa.h"
 #include "mincrypt/sha256.h"
 
+#ifndef __unused
+#define __unused __attribute__((__unused__))
+#endif
+
 /**
  * Messages signed using:
  *
@@ -209,7 +215,7 @@
     return result;
 }
 
-int main(int arg, char** argv) {
+int main(int arg __unused, char** argv __unused) {
 
     unsigned char hash_buf[SHA256_DIGEST_SIZE];
 
diff --git a/libmincrypt/test/rsa_test.c b/libmincrypt/test/rsa_test.c
index 17862dc..055138f 100644
--- a/libmincrypt/test/rsa_test.c
+++ b/libmincrypt/test/rsa_test.c
@@ -1,5 +1,4 @@
-/* rsa_test.c
-**
+/*
 ** Copyright 2013, The Android Open Source Project
 **
 ** Redistribution and use in source and binary forms, with or without
@@ -25,14 +24,19 @@
 ** ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
 
-#include <stdio.h>
 #include <ctype.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/cdefs.h>
 
 #include "mincrypt/rsa.h"
 #include "mincrypt/sha.h"
 
+#ifndef __unused
+#define __unused __attribute__((unused))
+#endif
+
 // RSA test data taken from:
 //
 //   ftp://ftp.rsa.com/pub/rsalabs/tmp/pkcs1v15sign-vectors.txt
@@ -791,7 +795,7 @@
 }
 
 
-int main(int arg, char** argv) {
+int main(int arg __unused, char** argv __unused) {
 
     unsigned char hash[SHA_DIGEST_SIZE];
 
diff --git a/libsparse/Android.mk b/libsparse/Android.mk
index 4aba168..0abe33d 100644
--- a/libsparse/Android.mk
+++ b/libsparse/Android.mk
@@ -17,6 +17,7 @@
 LOCAL_MODULE := libsparse_host
 LOCAL_STATIC_LIBRARIES := libz
 LOCAL_C_INCLUDES += $(LOCAL_PATH)/include external/zlib
+LOCAL_CFLAGS := -Werror
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 
@@ -27,6 +28,7 @@
 LOCAL_C_INCLUDES += $(LOCAL_PATH)/include external/zlib
 LOCAL_SHARED_LIBRARIES := \
     libz
+LOCAL_CFLAGS := -Werror
 include $(BUILD_SHARED_LIBRARY)
 
 
@@ -36,6 +38,7 @@
 LOCAL_MODULE := libsparse_static
 LOCAL_C_INCLUDES += $(LOCAL_PATH)/include external/zlib
 LOCAL_STATIC_LIBRARIES := libz
+LOCAL_CFLAGS := -Werror
 include $(BUILD_STATIC_LIBRARY)
 
 
@@ -48,6 +51,7 @@
 LOCAL_STATIC_LIBRARIES := \
     libsparse_host \
     libz
+LOCAL_CFLAGS := -Werror
 include $(BUILD_HOST_EXECUTABLE)
 
 
@@ -58,6 +62,7 @@
 LOCAL_STATIC_LIBRARIES := \
     libsparse_static \
     libz
+LOCAL_CFLAGS := -Werror
 include $(BUILD_EXECUTABLE)
 
 
@@ -69,6 +74,7 @@
 LOCAL_STATIC_LIBRARIES := \
     libsparse_host \
     libz
+LOCAL_CFLAGS := -Werror
 include $(BUILD_HOST_EXECUTABLE)
 
 
@@ -78,6 +84,7 @@
 LOCAL_STATIC_LIBRARIES := \
     libsparse_static \
     libz
+LOCAL_CFLAGS := -Werror
 include $(BUILD_EXECUTABLE)
 
 
@@ -89,6 +96,7 @@
 LOCAL_STATIC_LIBRARIES := \
     libsparse_host \
     libz
+LOCAL_CFLAGS := -Werror
 include $(BUILD_HOST_EXECUTABLE)
 
 endif
@@ -98,5 +106,5 @@
 LOCAL_SRC_FILES := simg_dump.py
 LOCAL_MODULE_CLASS := EXECUTABLES
 LOCAL_IS_HOST_MODULE := true
+LOCAL_CFLAGS := -Werror
 include $(BUILD_PREBUILT)
-
diff --git a/libsparse/img2simg.c b/libsparse/img2simg.c
index 6b1caa5..a0db36f 100644
--- a/libsparse/img2simg.c
+++ b/libsparse/img2simg.c
@@ -47,7 +47,6 @@
 {
 	int in;
 	int out;
-	unsigned int i;
 	int ret;
 	struct sparse_file *s;
 	unsigned int block_size = 4096;
diff --git a/libsparse/output_file.c b/libsparse/output_file.c
index 1cf8d8d..cd30800 100644
--- a/libsparse/output_file.c
+++ b/libsparse/output_file.c
@@ -31,8 +31,8 @@
 
 #include "defs.h"
 #include "output_file.h"
-#include "sparse_format.h"
 #include "sparse_crc32.h"
+#include "sparse_format.h"
 
 #ifndef USE_MINGW
 #include <sys/mman.h>
@@ -295,7 +295,6 @@
 
 static int callback_file_write(struct output_file *out, void *data, int len)
 {
-	int ret;
 	struct output_file_callback *outc = to_output_file_callback(out);
 
 	return outc->write(outc->priv, data, len);
@@ -341,7 +340,7 @@
 static int write_sparse_skip_chunk(struct output_file *out, int64_t skip_len)
 {
 	chunk_header_t chunk_header;
-	int ret, chunk;
+	int ret;
 
 	if (skip_len % out->block_size) {
 		error("don't care size %"PRIi64" is not a multiple of the block size %u",
@@ -368,9 +367,8 @@
 		uint32_t fill_val)
 {
 	chunk_header_t chunk_header;
-	int rnd_up_len, zero_len, count;
+	int rnd_up_len, count;
 	int ret;
-	unsigned int i;
 
 	/* Round up the fill length to a multiple of the block size */
 	rnd_up_len = ALIGN(len, out->block_size);
@@ -536,8 +534,6 @@
 
 void output_file_close(struct output_file *out)
 {
-	int ret;
-
 	out->sparse_ops->write_end_chunk(out);
 	out->ops->close(out);
 }
diff --git a/libsparse/sparse.c b/libsparse/sparse.c
index 0f107b0..baa30cd 100644
--- a/libsparse/sparse.c
+++ b/libsparse/sparse.c
@@ -279,7 +279,6 @@
 		struct sparse_file **out_s, int out_s_count)
 {
 	struct backed_block *bb;
-	unsigned int overhead;
 	struct sparse_file *s;
 	struct sparse_file *tmp;
 	int c = 0;
diff --git a/libsparse/sparse_read.c b/libsparse/sparse_read.c
index 873c87c..8e188e9 100644
--- a/libsparse/sparse_read.c
+++ b/libsparse/sparse_read.c
@@ -180,22 +180,16 @@
 		int fd __unused, unsigned int blocks,
 		unsigned int block __unused, uint32_t *crc32)
 {
-	int ret;
-	int chunk;
-	int64_t len = (int64_t)blocks * s->block_size;
-	uint32_t fill_val;
-	uint32_t *fillbuf;
-	unsigned int i;
-
 	if (chunk_size != 0) {
 		return -EINVAL;
 	}
 
 	if (crc32) {
+	        int64_t len = (int64_t)blocks * s->block_size;
 		memset(copybuf, 0, COPY_BUF_SIZE);
 
 		while (len) {
-			chunk = min(len, COPY_BUF_SIZE);
+			int chunk = min(len, COPY_BUF_SIZE);
 			*crc32 = sparse_crc32(*crc32, copybuf, chunk);
 			len -= chunk;
 		}
@@ -367,7 +361,6 @@
 	int64_t remain = s->len;
 	int64_t offset = 0;
 	unsigned int to_read;
-	char *ptr;
 	unsigned int i;
 	bool sparse_block;
 
diff --git a/libutils/Android.mk b/libutils/Android.mk
index 8e9dfd3..1fef049 100644
--- a/libutils/Android.mk
+++ b/libutils/Android.mk
@@ -70,7 +70,6 @@
 LOCAL_MODULE:= libutils
 LOCAL_STATIC_LIBRARIES := liblog
 LOCAL_CFLAGS += $(host_commonCflags)
-LOCAL_LDLIBS += $(host_commonLdlibs)
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 
@@ -84,7 +83,6 @@
 LOCAL_MODULE:= lib64utils
 LOCAL_STATIC_LIBRARIES := liblog
 LOCAL_CFLAGS += $(host_commonCflags) -m64
-LOCAL_LDLIBS += $(host_commonLdlibs)
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 
@@ -99,10 +97,6 @@
 	Looper.cpp \
 	Trace.cpp
 
-ifeq ($(TARGET_OS),linux)
-LOCAL_LDLIBS += -lrt -ldl
-endif
-
 ifeq ($(TARGET_ARCH),mips)
 LOCAL_CFLAGS += -DALIGN_DOUBLE
 endif
@@ -111,8 +105,6 @@
 		bionic/libc/private \
 		external/zlib
 
-LOCAL_LDLIBS += -lpthread
-
 LOCAL_STATIC_LIBRARIES := \
 	libcutils
 
diff --git a/libziparchive/Android.mk b/libziparchive/Android.mk
index e754c3b..1d48fea 100644
--- a/libziparchive/Android.mk
+++ b/libziparchive/Android.mk
@@ -30,6 +30,7 @@
 LOCAL_MODULE:= libziparchive
 
 LOCAL_C_INCLUDES += ${includes}
+LOCAL_CFLAGS := -Werror
 include $(BUILD_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
@@ -40,6 +41,7 @@
 
 LOCAL_STATIC_LIBRARIES := libz libutils
 LOCAL_MODULE:= libziparchive-host
+LOCAL_CFLAGS := -Werror
 include $(BUILD_HOST_STATIC_LIBRARY)
 
 include $(CLEAR_VARS)
@@ -47,7 +49,8 @@
 LOCAL_CPP_EXTENSION := .cc
 LOCAL_CFLAGS += \
     -DGTEST_OS_LINUX_ANDROID \
-    -DGTEST_HAS_STD_STRING
+    -DGTEST_HAS_STD_STRING \
+    -Werror
 LOCAL_SRC_FILES := zip_archive_test.cc
 LOCAL_SHARED_LIBRARIES := liblog
 LOCAL_STATIC_LIBRARIES := libziparchive libz libgtest libgtest_main libutils
@@ -58,7 +61,8 @@
 LOCAL_CPP_EXTENSION := .cc
 LOCAL_CFLAGS += \
     -DGTEST_OS_LINUX \
-    -DGTEST_HAS_STD_STRING
+    -DGTEST_HAS_STD_STRING \
+    -Werror
 LOCAL_SRC_FILES := zip_archive_test.cc
 LOCAL_STATIC_LIBRARIES := libziparchive-host \
 	libz \
diff --git a/libziparchive/zip_archive.cc b/libziparchive/zip_archive.cc
index aebddc8..6781ebe 100644
--- a/libziparchive/zip_archive.cc
+++ b/libziparchive/zip_archive.cc
@@ -27,6 +27,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+#include <utils/Compat.h>
 #include <utils/FileMap.h>
 #include <zlib.h>
 
@@ -218,7 +219,7 @@
     ssize_t actual = TEMP_FAILURE_RETRY(read(fd, buf, get_size));
 
     if (actual != get_size) {
-      ALOGW("CopyFileToFile: copy read failed (%zd vs %zd)", actual, get_size);
+      ALOGW("CopyFileToFile: copy read failed (" ZD " vs " ZD ")", actual, get_size);
       return kIoError;
     }
 
@@ -337,12 +338,12 @@
   const off64_t search_start = file_length - read_amount;
 
   if (lseek64(fd, search_start, SEEK_SET) != search_start) {
-    ALOGW("Zip: seek %" PRId64 " failed: %s", search_start, strerror(errno));
+    ALOGW("Zip: seek %" PRId64 " failed: %s", (int64_t)search_start, strerror(errno));
     return kIoError;
   }
   ssize_t actual = TEMP_FAILURE_RETRY(read(fd, scan_buffer, read_amount));
   if (actual != (ssize_t) read_amount) {
-    ALOGW("Zip: read %u failed: %s", read_amount, strerror(errno));
+    ALOGW("Zip: read %" PRIu32 " failed: %s", read_amount, strerror(errno));
     return kIoError;
   }
 
@@ -380,7 +381,7 @@
 
   if (dir_offset + dir_size > eocd_offset) {
     ALOGW("Zip: bad offsets (dir %" PRId64 ", size %" PRId64 ", eocd %" PRId64 ")",
-        dir_offset, dir_size, eocd_offset);
+        (int64_t)dir_offset, (int64_t)dir_size, (int64_t)eocd_offset);
     return kInvalidOffset;
   }
   if (num_entries == 0) {
@@ -389,7 +390,7 @@
   }
 
   ALOGV("+++ num_entries=%d dir_size=%" PRId64 " dir_offset=%" PRId64,
-        num_entries, dir_size, dir_offset);
+        num_entries, (int64_t)dir_size, (int64_t)dir_offset);
 
   /*
    * It all looks good.  Create a mapping for the CD, and set the fields
@@ -430,12 +431,12 @@
   }
 
   if (file_length > (off64_t) 0xffffffff) {
-    ALOGV("Zip: zip file too long %" PRId64, file_length);
+    ALOGV("Zip: zip file too long %" PRId64, (int64_t)file_length);
     return kInvalidFile;
   }
 
   if (file_length < (int64_t) kEOCDLen) {
-    ALOGV("Zip: length %" PRId64 " is too small to be zip", file_length);
+    ALOGV("Zip: length %" PRId64 " is too small to be zip", (int64_t)file_length);
     return kInvalidFile;
   }
 
@@ -492,18 +493,18 @@
   const uint8_t* ptr = cd_ptr;
   for (uint16_t i = 0; i < num_entries; i++) {
     if (get4LE(ptr) != kCDESignature) {
-      ALOGW("Zip: missed a central dir sig (at %d)", i);
+      ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
       goto bail;
     }
 
     if (ptr + kCDELen > cd_ptr + cd_length) {
-      ALOGW("Zip: ran off the end (at %d)", i);
+      ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
       goto bail;
     }
 
     const off64_t local_header_offset = get4LE(ptr + kCDELocalOffset);
     if (local_header_offset >= archive->directory_offset) {
-      ALOGW("Zip: bad LFH offset %" PRId64 " at entry %d", local_header_offset, i);
+      ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16, (int64_t)local_header_offset, i);
       goto bail;
     }
 
@@ -522,12 +523,12 @@
 
     ptr += kCDELen + file_name_length + extra_length + comment_length;
     if ((size_t)(ptr - cd_ptr) > cd_length) {
-      ALOGW("Zip: bad CD advance (%zu vs %zu) at entry %d",
-        (size_t) (ptr - cd_ptr), cd_length, i);
+      ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16,
+          ptr - cd_ptr, cd_length, i);
       goto bail;
     }
   }
-  ALOGV("+++ zip good scan %d entries", num_entries);
+  ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
 
   result = 0;
 
@@ -686,13 +687,13 @@
   ssize_t actual = ReadAtOffset(archive->fd, lfh_buf, sizeof(lfh_buf),
                                  local_header_offset);
   if (actual != sizeof(lfh_buf)) {
-    ALOGW("Zip: failed reading lfh name from offset %" PRId64, local_header_offset);
+    ALOGW("Zip: failed reading lfh name from offset %" PRId64, (int64_t)local_header_offset);
     return kIoError;
   }
 
   if (get4LE(lfh_buf) != kLFHSignature) {
     ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
-        local_header_offset);
+        (int64_t)local_header_offset);
     return kInvalidOffset;
   }
 
@@ -710,7 +711,8 @@
     data->has_data_descriptor = 0;
     if (data->compressed_length != lfhCompLen || data->uncompressed_length != lfhUncompLen
         || data->crc32 != lfhCrc) {
-      ALOGW("Zip: size/crc32 mismatch. expected {%d, %d, %x}, was {%d, %d, %x}",
+      ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32
+        ", %" PRIx32 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
         data->compressed_length, data->uncompressed_length, data->crc32,
         lfhCompLen, lfhUncompLen, lfhCrc);
       return kInconsistentInformation;
@@ -733,7 +735,7 @@
                                   name_offset);
 
     if (actual != nameLen) {
-      ALOGW("Zip: failed reading lfh name from offset %" PRId64, name_offset);
+      ALOGW("Zip: failed reading lfh name from offset %" PRId64, (int64_t)name_offset);
       free(name_buf);
       return kIoError;
     }
@@ -751,20 +753,20 @@
 
   const off64_t data_offset = local_header_offset + kLFHLen + lfhNameLen + lfhExtraLen;
   if (data_offset > cd_offset) {
-    ALOGW("Zip: bad data offset %" PRId64 " in zip", data_offset);
+    ALOGW("Zip: bad data offset %" PRId64 " in zip", (int64_t)data_offset);
     return kInvalidOffset;
   }
 
   if ((off64_t)(data_offset + data->compressed_length) > cd_offset) {
-    ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %zd > %" PRId64 ")",
-      data_offset, data->compressed_length, cd_offset);
+    ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
+      (int64_t)data_offset, data->compressed_length, (int64_t)cd_offset);
     return kInvalidOffset;
   }
 
   if (data->method == kCompressStored &&
     (off64_t)(data_offset + data->uncompressed_length) > cd_offset) {
-     ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %d > %" PRId64 ")",
-       data_offset, data->uncompressed_length, cd_offset);
+     ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
+       (int64_t)data_offset, data->uncompressed_length, (int64_t)cd_offset);
      return kInvalidOffset;
   }
 
@@ -900,10 +902,10 @@
   do {
     /* read as much as we can */
     if (zstream.avail_in == 0) {
-      const ssize_t getSize = (compressed_length > kBufSize) ? kBufSize : compressed_length;
-      const ssize_t actual = TEMP_FAILURE_RETRY(read(fd, read_buf, getSize));
+      const ZD_TYPE getSize = (compressed_length > kBufSize) ? kBufSize : compressed_length;
+      const ZD_TYPE actual = TEMP_FAILURE_RETRY(read(fd, read_buf, getSize));
       if (actual != getSize) {
-        ALOGW("Zip: inflate read failed (%zd vs %zd)", actual, getSize);
+        ALOGW("Zip: inflate read failed (" ZD " vs " ZD ")", actual, getSize);
         result = kIoError;
         goto z_bail;
       }
@@ -946,7 +948,7 @@
   *crc_out = zstream.adler;
 
   if (zstream.total_out != uncompressed_length || compressed_length != 0) {
-    ALOGW("Zip: size mismatch on inflated file (%ld vs %u)",
+    ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")",
         zstream.total_out, uncompressed_length);
     result = kInconsistentInformation;
     goto z_bail;
@@ -967,7 +969,7 @@
   off64_t data_offset = entry->offset;
 
   if (lseek64(archive->fd, data_offset, SEEK_SET) != data_offset) {
-    ALOGW("Zip: lseek to data at %" PRId64 " failed", data_offset);
+    ALOGW("Zip: lseek to data at %" PRId64 " failed", (int64_t)data_offset);
     return kIoError;
   }
 
@@ -990,7 +992,7 @@
   // TODO: Fix this check by passing the right flags to inflate2 so that
   // it calculates the CRC for us.
   if (entry->crc32 != crc && false) {
-    ALOGW("Zip: crc mismatch: expected %u, was %" PRIu64, entry->crc32, crc);
+    ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
     return kInconsistentInformation;
   }
 
@@ -1011,7 +1013,7 @@
   int result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
   if (result == -1) {
     ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
-          declared_length + current_offset, strerror(errno));
+          (int64_t)(declared_length + current_offset), strerror(errno));
     return kIoError;
   }
 
diff --git a/logcat/tests/Android.mk b/logcat/tests/Android.mk
index d42b3d0..5d4d29e 100644
--- a/logcat/tests/Android.mk
+++ b/logcat/tests/Android.mk
@@ -40,7 +40,6 @@
 LOCAL_MODULE_TAGS := $(test_tags)
 LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
 LOCAL_CFLAGS += $(test_c_flags)
-LOCAL_LDLIBS := -lpthread
 LOCAL_SHARED_LIBRARIES := liblog
 LOCAL_SRC_FILES := $(test_src_files)
 include $(BUILD_NATIVE_TEST)
diff --git a/mkbootimg/Android.mk b/mkbootimg/Android.mk
index 2a97c26..0c9b0c6 100644
--- a/mkbootimg/Android.mk
+++ b/mkbootimg/Android.mk
@@ -4,6 +4,7 @@
 
 LOCAL_SRC_FILES := mkbootimg.c
 LOCAL_STATIC_LIBRARIES := libmincrypt
+LOCAL_CFLAGS := -Werror
 
 LOCAL_MODULE := mkbootimg
 
diff --git a/mkbootimg/mkbootimg.c b/mkbootimg/mkbootimg.c
index a7daccc..fc92b4d 100644
--- a/mkbootimg/mkbootimg.c
+++ b/mkbootimg/mkbootimg.c
@@ -77,7 +77,7 @@
 int write_padding(int fd, unsigned pagesize, unsigned itemsize)
 {
     unsigned pagemask = pagesize - 1;
-    unsigned count;
+    ssize_t count;
 
     if((itemsize & pagemask) == 0) {
         return 0;
@@ -108,7 +108,7 @@
     unsigned pagesize = 2048;
     int fd;
     SHA_CTX ctx;
-    uint8_t* sha;
+    const uint8_t* sha;
     unsigned base           = 0x10000000;
     unsigned kernel_offset  = 0x00008000;
     unsigned ramdisk_offset = 0x01000000;
@@ -189,7 +189,7 @@
         return usage();
     }
 
-    strcpy(hdr.name, board);
+    strcpy((char *) hdr.name, board);
 
     memcpy(hdr.magic, BOOT_MAGIC, BOOT_MAGIC_SIZE);
 
@@ -255,14 +255,14 @@
     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) != hdr.kernel_size) 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) != hdr.ramdisk_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) != hdr.second_size) goto fail;
+        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;
     }
 
diff --git a/netcfg/Android.mk b/netcfg/Android.mk
index 949f417..fc01a54 100644
--- a/netcfg/Android.mk
+++ b/netcfg/Android.mk
@@ -11,6 +11,7 @@
 #LOCAL_STATIC_LIBRARIES := libcutils libc
 
 LOCAL_SHARED_LIBRARIES := libc libnetutils
+LOCAL_CFLAGS := -Werror
 
 include $(BUILD_EXECUTABLE)
 endif
diff --git a/netcfg/netcfg.c b/netcfg/netcfg.c
index 3738f24..2308f37 100644
--- a/netcfg/netcfg.c
+++ b/netcfg/netcfg.c
@@ -1,5 +1,4 @@
-/* system/bin/netcfg/netcfg.c
-**
+/*
 ** Copyright 2006, The Android Open Source Project
 **
 ** Licensed under the Apache License, Version 2.0 (the "License"); 
@@ -15,18 +14,14 @@
 ** limitations under the License.
 */
 
-#include <stdio.h>
-#include <stdlib.h>
 #include <errno.h>
 #include <dirent.h>
 #include <netinet/ether.h>
 #include <netinet/if_ether.h>
-
-#include <netutils/ifc.h>
 #include <netutils/dhcp.h>
-
-static int verbose = 0;
-
+#include <netutils/ifc.h>
+#include <stdio.h>
+#include <stdlib.h>
 
 void die(const char *reason)
 {
diff --git a/run-as/Android.mk b/run-as/Android.mk
index a8f2885..3774acc 100644
--- a/run-as/Android.mk
+++ b/run-as/Android.mk
@@ -1,10 +1,12 @@
 LOCAL_PATH:= $(call my-dir)
 include $(CLEAR_VARS)
 
-LOCAL_SRC_FILES:= run-as.c package.c
+LOCAL_SRC_FILES := run-as.c package.c
 
 LOCAL_SHARED_LIBRARIES := libselinux
 
-LOCAL_MODULE:= run-as
+LOCAL_MODULE := run-as
+
+LOCAL_CFLAGS := -Werror
 
 include $(BUILD_EXECUTABLE)
diff --git a/run-as/package.c b/run-as/package.c
index 901e9e3..4f8f3a7 100644
--- a/run-as/package.c
+++ b/run-as/package.c
@@ -128,7 +128,9 @@
     }
 
     /* Memory-map the file now */
-    address = TEMP_FAILURE_RETRY(mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0));
+    do {
+        address = mmap(NULL, length, PROT_READ, MAP_PRIVATE, fd, 0);
+    } while (address == MAP_FAILED && errno == EINTR);
     if (address == MAP_FAILED) {
         address = NULL;
         goto EXIT;
@@ -408,10 +410,6 @@
         value = -1;
     }
     return value;
-
-BAD:
-    *pp = p;
-    return -1;
 }
 
 /* Read the system's package database and extract information about
diff --git a/sdcard/fuse.h b/sdcard/fuse.h
deleted file mode 100644
index 3138da9..0000000
--- a/sdcard/fuse.h
+++ /dev/null
@@ -1,578 +0,0 @@
-/*
-    FUSE: Filesystem in Userspace
-    Copyright (C) 2001-2008  Miklos Szeredi <miklos@szeredi.hu>
-
-    This program can be distributed under the terms of the GNU GPL.
-    See the file COPYING.
-*/
-
-/*
- * from the libfuse FAQ (and consistent with the Linux Kernel license):
- *
- * Under what conditions may I distribute a filesystem that uses the
- * raw kernel interface of FUSE?
- *
- * There are no restrictions whatsoever for using the raw kernel interface. 
- *
- */
-
-/*
- * This file defines the kernel interface of FUSE
- *
- * Protocol changelog:
- *
- * 7.9:
- *  - new fuse_getattr_in input argument of GETATTR
- *  - add lk_flags in fuse_lk_in
- *  - add lock_owner field to fuse_setattr_in, fuse_read_in and fuse_write_in
- *  - add blksize field to fuse_attr
- *  - add file flags field to fuse_read_in and fuse_write_in
- *
- * 7.10
- *  - add nonseekable open flag
- *
- * 7.11
- *  - add IOCTL message
- *  - add unsolicited notification support
- *  - add POLL message and NOTIFY_POLL notification
- *
- * 7.12
- *  - add umask flag to input argument of open, mknod and mkdir
- *  - add notification messages for invalidation of inodes and
- *    directory entries
- *
- * 7.13
- *  - make max number of background requests and congestion threshold
- *    tunables
- */
-
-#ifndef _LINUX_FUSE_H
-#define _LINUX_FUSE_H
-
-#include <linux/types.h>
-
-/*
- * Version negotiation:
- *
- * Both the kernel and userspace send the version they support in the
- * INIT request and reply respectively.
- *
- * If the major versions match then both shall use the smallest
- * of the two minor versions for communication.
- *
- * If the kernel supports a larger major version, then userspace shall
- * reply with the major version it supports, ignore the rest of the
- * INIT message and expect a new INIT message from the kernel with a
- * matching major version.
- *
- * If the library supports a larger major version, then it shall fall
- * back to the major protocol version sent by the kernel for
- * communication and reply with that major version (and an arbitrary
- * supported minor version).
- */
-
-/** Version number of this interface */
-#define FUSE_KERNEL_VERSION 7
-
-/** Minor version number of this interface */
-#define FUSE_KERNEL_MINOR_VERSION 13
-
-/** The node ID of the root inode */
-#define FUSE_ROOT_ID 1
-
-/* Make sure all structures are padded to 64bit boundary, so 32bit
-   userspace works under 64bit kernels */
-
-struct fuse_attr {
-	__u64	ino;
-	__u64	size;
-	__u64	blocks;
-	__u64	atime;
-	__u64	mtime;
-	__u64	ctime;
-	__u32	atimensec;
-	__u32	mtimensec;
-	__u32	ctimensec;
-	__u32	mode;
-	__u32	nlink;
-	__u32	uid;
-	__u32	gid;
-	__u32	rdev;
-	__u32	blksize;
-	__u32	padding;
-};
-
-struct fuse_kstatfs {
-	__u64	blocks;
-	__u64	bfree;
-	__u64	bavail;
-	__u64	files;
-	__u64	ffree;
-	__u32	bsize;
-	__u32	namelen;
-	__u32	frsize;
-	__u32	padding;
-	__u32	spare[6];
-};
-
-struct fuse_file_lock {
-	__u64	start;
-	__u64	end;
-	__u32	type;
-	__u32	pid; /* tgid */
-};
-
-/**
- * Bitmasks for fuse_setattr_in.valid
- */
-#define FATTR_MODE	(1 << 0)
-#define FATTR_UID	(1 << 1)
-#define FATTR_GID	(1 << 2)
-#define FATTR_SIZE	(1 << 3)
-#define FATTR_ATIME	(1 << 4)
-#define FATTR_MTIME	(1 << 5)
-#define FATTR_FH	(1 << 6)
-#define FATTR_ATIME_NOW	(1 << 7)
-#define FATTR_MTIME_NOW	(1 << 8)
-#define FATTR_LOCKOWNER	(1 << 9)
-
-/**
- * Flags returned by the OPEN request
- *
- * FOPEN_DIRECT_IO: bypass page cache for this open file
- * FOPEN_KEEP_CACHE: don't invalidate the data cache on open
- * FOPEN_NONSEEKABLE: the file is not seekable
- */
-#define FOPEN_DIRECT_IO		(1 << 0)
-#define FOPEN_KEEP_CACHE	(1 << 1)
-#define FOPEN_NONSEEKABLE	(1 << 2)
-
-/**
- * INIT request/reply flags
- *
- * FUSE_EXPORT_SUPPORT: filesystem handles lookups of "." and ".."
- * FUSE_DONT_MASK: don't apply umask to file mode on create operations
- */
-#define FUSE_ASYNC_READ		(1 << 0)
-#define FUSE_POSIX_LOCKS	(1 << 1)
-#define FUSE_FILE_OPS		(1 << 2)
-#define FUSE_ATOMIC_O_TRUNC	(1 << 3)
-#define FUSE_EXPORT_SUPPORT	(1 << 4)
-#define FUSE_BIG_WRITES		(1 << 5)
-#define FUSE_DONT_MASK		(1 << 6)
-
-/**
- * CUSE INIT request/reply flags
- *
- * CUSE_UNRESTRICTED_IOCTL:  use unrestricted ioctl
- */
-#define CUSE_UNRESTRICTED_IOCTL	(1 << 0)
-
-/**
- * Release flags
- */
-#define FUSE_RELEASE_FLUSH	(1 << 0)
-
-/**
- * Getattr flags
- */
-#define FUSE_GETATTR_FH		(1 << 0)
-
-/**
- * Lock flags
- */
-#define FUSE_LK_FLOCK		(1 << 0)
-
-/**
- * WRITE flags
- *
- * FUSE_WRITE_CACHE: delayed write from page cache, file handle is guessed
- * FUSE_WRITE_LOCKOWNER: lock_owner field is valid
- */
-#define FUSE_WRITE_CACHE	(1 << 0)
-#define FUSE_WRITE_LOCKOWNER	(1 << 1)
-
-/**
- * Read flags
- */
-#define FUSE_READ_LOCKOWNER	(1 << 1)
-
-/**
- * Ioctl flags
- *
- * FUSE_IOCTL_COMPAT: 32bit compat ioctl on 64bit machine
- * FUSE_IOCTL_UNRESTRICTED: not restricted to well-formed ioctls, retry allowed
- * FUSE_IOCTL_RETRY: retry with new iovecs
- *
- * FUSE_IOCTL_MAX_IOV: maximum of in_iovecs + out_iovecs
- */
-#define FUSE_IOCTL_COMPAT	(1 << 0)
-#define FUSE_IOCTL_UNRESTRICTED	(1 << 1)
-#define FUSE_IOCTL_RETRY	(1 << 2)
-
-#define FUSE_IOCTL_MAX_IOV	256
-
-/**
- * Poll flags
- *
- * FUSE_POLL_SCHEDULE_NOTIFY: request poll notify
- */
-#define FUSE_POLL_SCHEDULE_NOTIFY (1 << 0)
-
-enum fuse_opcode {
-	FUSE_LOOKUP	   = 1,
-	FUSE_FORGET	   = 2,  /* no reply */
-	FUSE_GETATTR	   = 3,
-	FUSE_SETATTR	   = 4,
-	FUSE_READLINK	   = 5,
-	FUSE_SYMLINK	   = 6,
-	FUSE_MKNOD	   = 8,
-	FUSE_MKDIR	   = 9,
-	FUSE_UNLINK	   = 10,
-	FUSE_RMDIR	   = 11,
-	FUSE_RENAME	   = 12,
-	FUSE_LINK	   = 13,
-	FUSE_OPEN	   = 14,
-	FUSE_READ	   = 15,
-	FUSE_WRITE	   = 16,
-	FUSE_STATFS	   = 17,
-	FUSE_RELEASE       = 18,
-	FUSE_FSYNC         = 20,
-	FUSE_SETXATTR      = 21,
-	FUSE_GETXATTR      = 22,
-	FUSE_LISTXATTR     = 23,
-	FUSE_REMOVEXATTR   = 24,
-	FUSE_FLUSH         = 25,
-	FUSE_INIT          = 26,
-	FUSE_OPENDIR       = 27,
-	FUSE_READDIR       = 28,
-	FUSE_RELEASEDIR    = 29,
-	FUSE_FSYNCDIR      = 30,
-	FUSE_GETLK         = 31,
-	FUSE_SETLK         = 32,
-	FUSE_SETLKW        = 33,
-	FUSE_ACCESS        = 34,
-	FUSE_CREATE        = 35,
-	FUSE_INTERRUPT     = 36,
-	FUSE_BMAP          = 37,
-	FUSE_DESTROY       = 38,
-	FUSE_IOCTL         = 39,
-	FUSE_POLL          = 40,
-
-	/* CUSE specific operations */
-	CUSE_INIT          = 4096,
-};
-
-enum fuse_notify_code {
-	FUSE_NOTIFY_POLL   = 1,
-	FUSE_NOTIFY_INVAL_INODE = 2,
-	FUSE_NOTIFY_INVAL_ENTRY = 3,
-	FUSE_NOTIFY_CODE_MAX,
-};
-
-/* The read buffer is required to be at least 8k, but may be much larger */
-#define FUSE_MIN_READ_BUFFER 8192
-
-#define FUSE_COMPAT_ENTRY_OUT_SIZE 120
-
-struct fuse_entry_out {
-	__u64	nodeid;		/* Inode ID */
-	__u64	generation;	/* Inode generation: nodeid:gen must
-				   be unique for the fs's lifetime */
-	__u64	entry_valid;	/* Cache timeout for the name */
-	__u64	attr_valid;	/* Cache timeout for the attributes */
-	__u32	entry_valid_nsec;
-	__u32	attr_valid_nsec;
-	struct fuse_attr attr;
-};
-
-struct fuse_forget_in {
-	__u64	nlookup;
-};
-
-struct fuse_getattr_in {
-	__u32	getattr_flags;
-	__u32	dummy;
-	__u64	fh;
-};
-
-#define FUSE_COMPAT_ATTR_OUT_SIZE 96
-
-struct fuse_attr_out {
-	__u64	attr_valid;	/* Cache timeout for the attributes */
-	__u32	attr_valid_nsec;
-	__u32	dummy;
-	struct fuse_attr attr;
-};
-
-#define FUSE_COMPAT_MKNOD_IN_SIZE 8
-
-struct fuse_mknod_in {
-	__u32	mode;
-	__u32	rdev;
-	__u32	umask;
-	__u32	padding;
-};
-
-struct fuse_mkdir_in {
-	__u32	mode;
-	__u32	umask;
-};
-
-struct fuse_rename_in {
-	__u64	newdir;
-};
-
-struct fuse_link_in {
-	__u64	oldnodeid;
-};
-
-struct fuse_setattr_in {
-	__u32	valid;
-	__u32	padding;
-	__u64	fh;
-	__u64	size;
-	__u64	lock_owner;
-	__u64	atime;
-	__u64	mtime;
-	__u64	unused2;
-	__u32	atimensec;
-	__u32	mtimensec;
-	__u32	unused3;
-	__u32	mode;
-	__u32	unused4;
-	__u32	uid;
-	__u32	gid;
-	__u32	unused5;
-};
-
-struct fuse_open_in {
-	__u32	flags;
-	__u32	unused;
-};
-
-struct fuse_create_in {
-	__u32	flags;
-	__u32	mode;
-	__u32	umask;
-	__u32	padding;
-};
-
-struct fuse_open_out {
-	__u64	fh;
-	__u32	open_flags;
-	__u32	padding;
-};
-
-struct fuse_release_in {
-	__u64	fh;
-	__u32	flags;
-	__u32	release_flags;
-	__u64	lock_owner;
-};
-
-struct fuse_flush_in {
-	__u64	fh;
-	__u32	unused;
-	__u32	padding;
-	__u64	lock_owner;
-};
-
-struct fuse_read_in {
-	__u64	fh;
-	__u64	offset;
-	__u32	size;
-	__u32	read_flags;
-	__u64	lock_owner;
-	__u32	flags;
-	__u32	padding;
-};
-
-#define FUSE_COMPAT_WRITE_IN_SIZE 24
-
-struct fuse_write_in {
-	__u64	fh;
-	__u64	offset;
-	__u32	size;
-	__u32	write_flags;
-	__u64	lock_owner;
-	__u32	flags;
-	__u32	padding;
-};
-
-struct fuse_write_out {
-	__u32	size;
-	__u32	padding;
-};
-
-#define FUSE_COMPAT_STATFS_SIZE 48
-
-struct fuse_statfs_out {
-	struct fuse_kstatfs st;
-};
-
-struct fuse_fsync_in {
-	__u64	fh;
-	__u32	fsync_flags;
-	__u32	padding;
-};
-
-struct fuse_setxattr_in {
-	__u32	size;
-	__u32	flags;
-};
-
-struct fuse_getxattr_in {
-	__u32	size;
-	__u32	padding;
-};
-
-struct fuse_getxattr_out {
-	__u32	size;
-	__u32	padding;
-};
-
-struct fuse_lk_in {
-	__u64	fh;
-	__u64	owner;
-	struct fuse_file_lock lk;
-	__u32	lk_flags;
-	__u32	padding;
-};
-
-struct fuse_lk_out {
-	struct fuse_file_lock lk;
-};
-
-struct fuse_access_in {
-	__u32	mask;
-	__u32	padding;
-};
-
-struct fuse_init_in {
-	__u32	major;
-	__u32	minor;
-	__u32	max_readahead;
-	__u32	flags;
-};
-
-struct fuse_init_out {
-	__u32	major;
-	__u32	minor;
-	__u32	max_readahead;
-	__u32	flags;
-	__u16   max_background;
-	__u16   congestion_threshold;
-	__u32	max_write;
-};
-
-#define CUSE_INIT_INFO_MAX 4096
-
-struct cuse_init_in {
-	__u32	major;
-	__u32	minor;
-	__u32	unused;
-	__u32	flags;
-};
-
-struct cuse_init_out {
-	__u32	major;
-	__u32	minor;
-	__u32	unused;
-	__u32	flags;
-	__u32	max_read;
-	__u32	max_write;
-	__u32	dev_major;		/* chardev major */
-	__u32	dev_minor;		/* chardev minor */
-	__u32	spare[10];
-};
-
-struct fuse_interrupt_in {
-	__u64	unique;
-};
-
-struct fuse_bmap_in {
-	__u64	block;
-	__u32	blocksize;
-	__u32	padding;
-};
-
-struct fuse_bmap_out {
-	__u64	block;
-};
-
-struct fuse_ioctl_in {
-	__u64	fh;
-	__u32	flags;
-	__u32	cmd;
-	__u64	arg;
-	__u32	in_size;
-	__u32	out_size;
-};
-
-struct fuse_ioctl_out {
-	__s32	result;
-	__u32	flags;
-	__u32	in_iovs;
-	__u32	out_iovs;
-};
-
-struct fuse_poll_in {
-	__u64	fh;
-	__u64	kh;
-	__u32	flags;
-	__u32   padding;
-};
-
-struct fuse_poll_out {
-	__u32	revents;
-	__u32	padding;
-};
-
-struct fuse_notify_poll_wakeup_out {
-	__u64	kh;
-};
-
-struct fuse_in_header {
-	__u32	len;
-	__u32	opcode;
-	__u64	unique;
-	__u64	nodeid;
-	__u32	uid;
-	__u32	gid;
-	__u32	pid;
-	__u32	padding;
-};
-
-struct fuse_out_header {
-	__u32	len;
-	__s32	error;
-	__u64	unique;
-};
-
-struct fuse_dirent {
-	__u64	ino;
-	__u64	off;
-	__u32	namelen;
-	__u32	type;
-	char name[0];
-};
-
-#define FUSE_NAME_OFFSET offsetof(struct fuse_dirent, name)
-#define FUSE_DIRENT_ALIGN(x) (((x) + sizeof(__u64) - 1) & ~(sizeof(__u64) - 1))
-#define FUSE_DIRENT_SIZE(d) \
-	FUSE_DIRENT_ALIGN(FUSE_NAME_OFFSET + (d)->namelen)
-
-struct fuse_notify_inval_inode_out {
-	__u64	ino;
-	__s64	off;
-	__s64	len;
-};
-
-struct fuse_notify_inval_entry_out {
-	__u64	parent;
-	__u32	namelen;
-	__u32	padding;
-};
-
-#endif /* _LINUX_FUSE_H */
diff --git a/sdcard/sdcard.c b/sdcard/sdcard.c
index 6a9c2eb..7baad63 100644
--- a/sdcard/sdcard.c
+++ b/sdcard/sdcard.c
@@ -14,23 +14,24 @@
  * limitations under the License.
  */
 
+#include <ctype.h>
+#include <dirent.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <limits.h>
+#include <linux/fuse.h>
+#include <pthread.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
-#include <unistd.h>
-#include <errno.h>
-#include <fcntl.h>
+#include <sys/inotify.h>
 #include <sys/mount.h>
+#include <sys/resource.h>
 #include <sys/stat.h>
 #include <sys/statfs.h>
-#include <sys/uio.h>
-#include <dirent.h>
-#include <limits.h>
-#include <ctype.h>
-#include <pthread.h>
 #include <sys/time.h>
-#include <sys/resource.h>
-#include <sys/inotify.h>
+#include <sys/uio.h>
+#include <unistd.h>
 
 #include <cutils/fs.h>
 #include <cutils/hashmap.h>
@@ -38,15 +39,13 @@
 
 #include <private/android_filesystem_config.h>
 
-#include "fuse.h"
-
 /* README
  *
  * What is this?
- * 
+ *
  * sdcard is a program that uses FUSE to emulate FAT-on-sdcard style
- * directory permissions (all files are given fixed owner, group, and 
- * permissions at creation, owner, group, and permissions are not 
+ * directory permissions (all files are given fixed owner, group, and
+ * permissions at creation, owner, group, and permissions are not
  * changeable, symlinks and hardlinks are not createable, etc.
  *
  * See usage() for command line options.
@@ -1245,7 +1244,7 @@
     struct handle *h = id_to_ptr(req->fh);
     int res;
     __u8 aligned_buffer[req->size] __attribute__((__aligned__(PAGESIZE)));
-    
+
     if (req->flags & O_DIRECT) {
         memcpy(aligned_buffer, buffer, req->size);
         buffer = (const __u8*) aligned_buffer;