Merge "Fix for linker allocator"
diff --git a/benchmarks/benchmark_main.cpp b/benchmarks/benchmark_main.cpp
index d8b8e58..f8e85bb 100644
--- a/benchmarks/benchmark_main.cpp
+++ b/benchmarks/benchmark_main.cpp
@@ -25,13 +25,13 @@
 
 #include <inttypes.h>
 
-static int64_t gBytesProcessed;
-static int64_t gBenchmarkTotalTimeNs;
-static int64_t gBenchmarkStartTimeNs;
+static int64_t g_bytes_processed;
+static int64_t g_benchmark_total_time_ns;
+static int64_t g_benchmark_start_time_ns;
 
 typedef std::map<std::string, ::testing::Benchmark*> BenchmarkMap;
 typedef BenchmarkMap::iterator BenchmarkMapIt;
-static BenchmarkMap gBenchmarks;
+static BenchmarkMap g_benchmarks;
 
 static int Round(int n) {
   int base = 1;
@@ -96,7 +96,7 @@
     exit(EXIT_FAILURE);
   }
 
-  gBenchmarks.insert(std::make_pair(name, this));
+  g_benchmarks.insert(std::make_pair(name, this));
 }
 
 void Benchmark::Run() {
@@ -114,16 +114,16 @@
 }
 
 void Benchmark::RunRepeatedlyWithArg(int iterations, int arg) {
-  gBytesProcessed = 0;
-  gBenchmarkTotalTimeNs = 0;
-  gBenchmarkStartTimeNs = NanoTime();
+  g_bytes_processed = 0;
+  g_benchmark_total_time_ns = 0;
+  g_benchmark_start_time_ns = NanoTime();
   if (fn_ != NULL) {
     fn_(iterations);
   } else {
     fn_range_(iterations, arg);
   }
-  if (gBenchmarkStartTimeNs != 0) {
-    gBenchmarkTotalTimeNs += NanoTime() - gBenchmarkStartTimeNs;
+  if (g_benchmark_start_time_ns != 0) {
+    g_benchmark_total_time_ns += NanoTime() - g_benchmark_start_time_ns;
   }
 }
 
@@ -131,12 +131,12 @@
   // run once in case it's expensive
   int iterations = 1;
   RunRepeatedlyWithArg(iterations, arg);
-  while (gBenchmarkTotalTimeNs < 1e9 && iterations < 1e9) {
+  while (g_benchmark_total_time_ns < 1e9 && iterations < 1e9) {
     int last = iterations;
-    if (gBenchmarkTotalTimeNs/iterations == 0) {
+    if (g_benchmark_total_time_ns/iterations == 0) {
       iterations = 1e9;
     } else {
-      iterations = 1e9 / (gBenchmarkTotalTimeNs/iterations);
+      iterations = 1e9 / (g_benchmark_total_time_ns/iterations);
     }
     iterations = std::max(last + 1, std::min(iterations + iterations/2, 100*last));
     iterations = Round(iterations);
@@ -145,9 +145,9 @@
 
   char throughput[100];
   throughput[0] = '\0';
-  if (gBenchmarkTotalTimeNs > 0 && gBytesProcessed > 0) {
-    double mib_processed = static_cast<double>(gBytesProcessed)/1e6;
-    double seconds = static_cast<double>(gBenchmarkTotalTimeNs)/1e9;
+  if (g_benchmark_total_time_ns > 0 && g_bytes_processed > 0) {
+    double mib_processed = static_cast<double>(g_bytes_processed)/1e6;
+    double seconds = static_cast<double>(g_benchmark_total_time_ns)/1e9;
     snprintf(throughput, sizeof(throughput), " %8.2f MiB/s", mib_processed/seconds);
   }
 
@@ -165,37 +165,37 @@
   }
 
   printf("%-20s %10d %10" PRId64 "%s\n", full_name,
-         iterations, gBenchmarkTotalTimeNs/iterations, throughput);
+         iterations, g_benchmark_total_time_ns/iterations, throughput);
   fflush(stdout);
 }
 
 }  // namespace testing
 
 void SetBenchmarkBytesProcessed(int64_t x) {
-  gBytesProcessed = x;
+  g_bytes_processed = x;
 }
 
 void StopBenchmarkTiming() {
-  if (gBenchmarkStartTimeNs != 0) {
-    gBenchmarkTotalTimeNs += NanoTime() - gBenchmarkStartTimeNs;
+  if (g_benchmark_start_time_ns != 0) {
+    g_benchmark_total_time_ns += NanoTime() - g_benchmark_start_time_ns;
   }
-  gBenchmarkStartTimeNs = 0;
+  g_benchmark_start_time_ns = 0;
 }
 
 void StartBenchmarkTiming() {
-  if (gBenchmarkStartTimeNs == 0) {
-    gBenchmarkStartTimeNs = NanoTime();
+  if (g_benchmark_start_time_ns == 0) {
+    g_benchmark_start_time_ns = NanoTime();
   }
 }
 
 int main(int argc, char* argv[]) {
-  if (gBenchmarks.empty()) {
+  if (g_benchmarks.empty()) {
     fprintf(stderr, "No benchmarks registered!\n");
     exit(EXIT_FAILURE);
   }
 
   bool need_header = true;
-  for (BenchmarkMapIt it = gBenchmarks.begin(); it != gBenchmarks.end(); ++it) {
+  for (BenchmarkMapIt it = g_benchmarks.begin(); it != g_benchmarks.end(); ++it) {
     ::testing::Benchmark* b = it->second;
     if (b->ShouldRun(argc, argv)) {
       if (need_header) {
@@ -210,7 +210,7 @@
   if (need_header) {
     fprintf(stderr, "No matching benchmarks!\n");
     fprintf(stderr, "Available benchmarks:\n");
-    for (BenchmarkMapIt it = gBenchmarks.begin(); it != gBenchmarks.end(); ++it) {
+    for (BenchmarkMapIt it = g_benchmarks.begin(); it != g_benchmarks.end(); ++it) {
       fprintf(stderr, "  %s\n", it->second->Name());
     }
     exit(EXIT_FAILURE);
diff --git a/libc/Android.mk b/libc/Android.mk
index cf3d48c..2d56af0 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -98,6 +98,7 @@
 
 libc_bionic_src_files := \
     bionic/abort.cpp \
+    bionic/accept.cpp \
     bionic/access.cpp \
     bionic/assert.cpp \
     bionic/atof.cpp \
@@ -267,6 +268,7 @@
     upstream-netbsd/lib/libc/gen/setjmperr.c \
     upstream-netbsd/lib/libc/gen/utime.c \
     upstream-netbsd/lib/libc/gen/utmp.c \
+    upstream-netbsd/lib/libc/inet/inet_ntop.c \
     upstream-netbsd/lib/libc/isc/ev_streams.c \
     upstream-netbsd/lib/libc/isc/ev_timers.c \
     upstream-netbsd/lib/libc/regex/regcomp.c \
@@ -363,7 +365,6 @@
     upstream-openbsd/lib/libc/net/inet_netof.c \
     upstream-openbsd/lib/libc/net/inet_network.c \
     upstream-openbsd/lib/libc/net/inet_ntoa.c \
-    upstream-openbsd/lib/libc/net/inet_ntop.c \
     upstream-openbsd/lib/libc/net/inet_pton.c \
     upstream-openbsd/lib/libc/net/ntohl.c \
     upstream-openbsd/lib/libc/net/ntohs.c \
@@ -747,10 +748,6 @@
 LOCAL_ADDITIONAL_DEPENDENCIES := $(libc_common_additional_dependencies)
 LOCAL_SYSTEM_SHARED_LIBRARIES :=
 
-# Set -DPTHREAD_DEBUG_ENABLED=true to enable support for pthread deadlock prediction.
-# Since this code is experimental it is disabled by default.
-LOCAL_CFLAGS += -DPTHREAD_DEBUG_ENABLED=false
-
 ifneq ($(TARGET_USES_LOGD),false)
 LOCAL_CFLAGS += -DTARGET_USES_LOGD
 endif
@@ -889,7 +886,6 @@
     bionic/malloc_debug_common.cpp \
     bionic/debug_mapinfo.cpp \
     bionic/debug_stacktrace.cpp \
-    bionic/pthread_debug.cpp \
     bionic/libc_init_dynamic.cpp \
     bionic/NetdClient.cpp \
 
diff --git a/libc/SYSCALLS.TXT b/libc/SYSCALLS.TXT
index e9fb575..83feb65 100644
--- a/libc/SYSCALLS.TXT
+++ b/libc/SYSCALLS.TXT
@@ -236,7 +236,7 @@
 int           bind(int, struct sockaddr*, int)  arm,arm64,mips,mips64,x86_64
 int           __connect:connect(int, struct sockaddr*, socklen_t)   arm,arm64,mips,mips64,x86_64
 int           listen(int, int)                   arm,arm64,mips,mips64,x86_64
-int           accept(int, struct sockaddr*, socklen_t*)  arm,arm64,mips,mips64,x86_64
+int           __accept:accept(int, struct sockaddr*, socklen_t*)  arm,arm64,mips,mips64,x86_64
 int           accept4(int, struct sockaddr*, socklen_t*, int)  arm,arm64,mips,mips64,x86_64
 int           getsockname(int, struct sockaddr*, socklen_t*)  arm,arm64,mips,mips64,x86_64
 int           getpeername(int, struct sockaddr*, socklen_t*)  arm,arm64,mips,mips64,x86_64
@@ -255,7 +255,7 @@
 int           bind:socketcall:2(int, struct sockaddr*, int)  x86
 int           __connect:socketcall:3(int, struct sockaddr*, socklen_t)   x86
 int           listen:socketcall:4(int, int)                   x86
-int           accept:socketcall:5(int, struct sockaddr*, socklen_t*)  x86
+int           __accept:socketcall:5(int, struct sockaddr*, socklen_t*)  x86
 int           getsockname:socketcall:6(int, struct sockaddr*, socklen_t*)  x86
 int           getpeername:socketcall:7(int, struct sockaddr*, socklen_t*)  x86
 int           socketpair:socketcall:8(int, int, int, int*)    x86
diff --git a/libc/arch-arm/syscalls/accept.S b/libc/arch-arm/syscalls/__accept.S
similarity index 89%
rename from libc/arch-arm/syscalls/accept.S
rename to libc/arch-arm/syscalls/__accept.S
index e2a51f5..bae11bc 100644
--- a/libc/arch-arm/syscalls/accept.S
+++ b/libc/arch-arm/syscalls/__accept.S
@@ -2,7 +2,7 @@
 
 #include <private/bionic_asm.h>
 
-ENTRY(accept)
+ENTRY(__accept)
     mov     ip, r7
     ldr     r7, =__NR_accept
     swi     #0
@@ -11,4 +11,4 @@
     bxls    lr
     neg     r0, r0
     b       __set_errno
-END(accept)
+END(__accept)
diff --git a/libc/arch-arm64/syscalls/accept.S b/libc/arch-arm64/syscalls/__accept.S
similarity index 88%
rename from libc/arch-arm64/syscalls/accept.S
rename to libc/arch-arm64/syscalls/__accept.S
index dae6121..21b68bc 100644
--- a/libc/arch-arm64/syscalls/accept.S
+++ b/libc/arch-arm64/syscalls/__accept.S
@@ -2,7 +2,7 @@
 
 #include <private/bionic_asm.h>
 
-ENTRY(accept)
+ENTRY(__accept)
     stp     x29, x30, [sp, #-16]!
     mov     x29,  sp
     str     x8,       [sp, #-16]!
@@ -18,4 +18,5 @@
     b.hi    __set_errno
 
     ret
-END(accept)
+END(__accept)
+.hidden __accept
diff --git a/libc/arch-mips/syscalls/accept.S b/libc/arch-mips/syscalls/__accept.S
similarity index 89%
rename from libc/arch-mips/syscalls/accept.S
rename to libc/arch-mips/syscalls/__accept.S
index 09496ab..d8141fe 100644
--- a/libc/arch-mips/syscalls/accept.S
+++ b/libc/arch-mips/syscalls/__accept.S
@@ -2,7 +2,7 @@
 
 #include <private/bionic_asm.h>
 
-ENTRY(accept)
+ENTRY(__accept)
     .set noreorder
     .cpload t9
     li v0, __NR_accept
@@ -16,4 +16,4 @@
     j t9
     nop
     .set reorder
-END(accept)
+END(__accept)
diff --git a/libc/arch-mips64/syscalls/accept.S b/libc/arch-mips64/syscalls/__accept.S
similarity index 87%
rename from libc/arch-mips64/syscalls/accept.S
rename to libc/arch-mips64/syscalls/__accept.S
index 6c38556..4404a68 100644
--- a/libc/arch-mips64/syscalls/accept.S
+++ b/libc/arch-mips64/syscalls/__accept.S
@@ -2,7 +2,7 @@
 
 #include <private/bionic_asm.h>
 
-ENTRY(accept)
+ENTRY(__accept)
     .set push
     .set noreorder
     li v0, __NR_accept
@@ -22,4 +22,5 @@
     j t9
     move ra, t0
     .set pop
-END(accept)
+END(__accept)
+.hidden __accept
diff --git a/libc/arch-x86/syscalls/accept.S b/libc/arch-x86/syscalls/__accept.S
similarity index 94%
rename from libc/arch-x86/syscalls/accept.S
rename to libc/arch-x86/syscalls/__accept.S
index f7e8a58..31cb350 100644
--- a/libc/arch-x86/syscalls/accept.S
+++ b/libc/arch-x86/syscalls/__accept.S
@@ -2,7 +2,7 @@
 
 #include <private/bionic_asm.h>
 
-ENTRY(accept)
+ENTRY(__accept)
     pushl   %ebx
     pushl   %ecx
     .cfi_def_cfa_offset 8
@@ -24,4 +24,4 @@
     popl    %ecx
     popl    %ebx
     ret
-END(accept)
+END(__accept)
diff --git a/libc/arch-x86_64/syscalls/accept.S b/libc/arch-x86_64/syscalls/__accept.S
similarity index 85%
rename from libc/arch-x86_64/syscalls/accept.S
rename to libc/arch-x86_64/syscalls/__accept.S
index 588fb82..ff0f5e7 100644
--- a/libc/arch-x86_64/syscalls/accept.S
+++ b/libc/arch-x86_64/syscalls/__accept.S
@@ -2,7 +2,7 @@
 
 #include <private/bionic_asm.h>
 
-ENTRY(accept)
+ENTRY(__accept)
     movl    $__NR_accept, %eax
     syscall
     cmpq    $-MAX_ERRNO, %rax
@@ -13,4 +13,5 @@
     orq     $-1, %rax
 1:
     ret
-END(accept)
+END(__accept)
+.hidden __accept
diff --git a/libc/bionic/NetdClient.cpp b/libc/bionic/NetdClient.cpp
index 6826ee8..72d90b7 100644
--- a/libc/bionic/NetdClient.cpp
+++ b/libc/bionic/NetdClient.cpp
@@ -40,6 +40,7 @@
         // default implementations of functions that it would've overridden.
         return;
     }
+    netdClientInitFunction(netdClientHandle, "netdClientInitAccept", &__netdClientDispatch.accept);
     netdClientInitFunction(netdClientHandle, "netdClientInitConnect",
                            &__netdClientDispatch.connect);
 }
diff --git a/libc/bionic/NetdClientDispatch.cpp b/libc/bionic/NetdClientDispatch.cpp
index 31728d2..adfe16d 100644
--- a/libc/bionic/NetdClientDispatch.cpp
+++ b/libc/bionic/NetdClientDispatch.cpp
@@ -22,8 +22,10 @@
 #define __socketcall
 #endif
 
+extern "C" __socketcall int __accept(int, sockaddr*, socklen_t*);
 extern "C" __socketcall int __connect(int, const sockaddr*, socklen_t);
 
 NetdClientDispatch __netdClientDispatch __attribute__((aligned(32))) = {
-    __connect
+    __accept,
+    __connect,
 };
diff --git a/libc/bionic/accept.cpp b/libc/bionic/accept.cpp
new file mode 100644
index 0000000..46b4efc
--- /dev/null
+++ b/libc/bionic/accept.cpp
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <private/NetdClient.h>
+#include <sys/socket.h>
+
+int accept(int sockfd, sockaddr* addr, socklen_t* addrlen) {
+    return __netdClientDispatch.accept(sockfd, addr, addrlen);
+}
diff --git a/libc/bionic/debug_stacktrace.cpp b/libc/bionic/debug_stacktrace.cpp
index 4207a3f..713e761 100644
--- a/libc/bionic/debug_stacktrace.cpp
+++ b/libc/bionic/debug_stacktrace.cpp
@@ -50,30 +50,30 @@
 typedef _Unwind_Context __unwind_context;
 #endif
 
-static mapinfo_t* gMapInfo = NULL;
-static void* gDemangler;
+static mapinfo_t* g_map_info = NULL;
+static void* g_demangler;
 typedef char* (*DemanglerFn)(const char*, char*, size_t*, int*);
-static DemanglerFn gDemanglerFn = NULL;
+static DemanglerFn g_demangler_fn = NULL;
 
 __LIBC_HIDDEN__ void backtrace_startup() {
-  gMapInfo = mapinfo_create(getpid());
-  gDemangler = dlopen("libgccdemangle.so", RTLD_NOW);
-  if (gDemangler != NULL) {
-    void* sym = dlsym(gDemangler, "__cxa_demangle");
-    gDemanglerFn = reinterpret_cast<DemanglerFn>(sym);
+  g_map_info = mapinfo_create(getpid());
+  g_demangler = dlopen("libgccdemangle.so", RTLD_NOW);
+  if (g_demangler != NULL) {
+    void* sym = dlsym(g_demangler, "__cxa_demangle");
+    g_demangler_fn = reinterpret_cast<DemanglerFn>(sym);
   }
 }
 
 __LIBC_HIDDEN__ void backtrace_shutdown() {
-  mapinfo_destroy(gMapInfo);
-  dlclose(gDemangler);
+  mapinfo_destroy(g_map_info);
+  dlclose(g_demangler);
 }
 
 static char* demangle(const char* symbol) {
-  if (gDemanglerFn == NULL) {
+  if (g_demangler_fn == NULL) {
     return NULL;
   }
-  return (*gDemanglerFn)(symbol, NULL, NULL, NULL);
+  return (*g_demangler_fn)(symbol, NULL, NULL, NULL);
 }
 
 struct stack_crawl_state_t {
@@ -147,7 +147,7 @@
     }
 
     uintptr_t rel_pc;
-    const mapinfo_t* mi = (gMapInfo != NULL) ? mapinfo_find(gMapInfo, frames[i], &rel_pc) : NULL;
+    const mapinfo_t* mi = (g_map_info != NULL) ? mapinfo_find(g_map_info, frames[i], &rel_pc) : NULL;
     const char* soname = (mi != NULL) ? mi->name : info.dli_fname;
     if (soname == NULL) {
       soname = "<unknown>";
diff --git a/libc/bionic/libc_init_common.cpp b/libc/bionic/libc_init_common.cpp
index 1cfaf50..abf2d36 100644
--- a/libc/bionic/libc_init_common.cpp
+++ b/libc/bionic/libc_init_common.cpp
@@ -77,7 +77,7 @@
  * apply to linker-private copies and will not be visible from libc later on.
  *
  * Note: this function creates a pthread_internal_t for the initial thread and
- * stores the pointer in TLS, but does not add it to pthread's gThreadList. This
+ * stores the pointer in TLS, but does not add it to pthread's thread list. This
  * has to be done later from libc itself (see __libc_init_common).
  *
  * This function also stores a pointer to the kernel argument block in a TLS slot to be
diff --git a/libc/bionic/libc_init_dynamic.cpp b/libc/bionic/libc_init_dynamic.cpp
index 3d98861..659cf39 100644
--- a/libc/bionic/libc_init_dynamic.cpp
+++ b/libc/bionic/libc_init_dynamic.cpp
@@ -55,7 +55,6 @@
 #include "private/KernelArgumentBlock.h"
 
 extern "C" {
-  extern void pthread_debug_init(void);
   extern void malloc_debug_init(void);
   extern void malloc_debug_fini(void);
   extern void netdClientInit(void);
@@ -77,11 +76,8 @@
 
   __libc_init_common(*args);
 
-  // Hooks for the debug malloc and pthread libraries to let them know that we're starting up.
-  pthread_debug_init();
+  // Hooks for various libraries to let them know that we're starting up.
   malloc_debug_init();
-
-  // Hook for the netd client library to let it know that we're starting up.
   netdClientInit();
 }
 
diff --git a/libc/bionic/libc_logging.cpp b/libc/bionic/libc_logging.cpp
index 79472b3..8966a5f 100644
--- a/libc/bionic/libc_logging.cpp
+++ b/libc/bionic/libc_logging.cpp
@@ -45,7 +45,7 @@
 #include <time.h>
 #include <unistd.h>
 
-static pthread_mutex_t gAbortMsgLock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t g_abort_msg_lock = PTHREAD_MUTEX_INITIALIZER;
 
 __LIBC_HIDDEN__ abort_msg_t** __abort_message_ptr; // Accessible to __libc_init_common.
 
@@ -643,7 +643,7 @@
 }
 
 void __android_set_abort_message(const char* msg) {
-  ScopedPthreadMutexLocker locker(&gAbortMsgLock);
+  ScopedPthreadMutexLocker locker(&g_abort_msg_lock);
 
   if (__abort_message_ptr == NULL) {
     // We must have crashed _very_ early.
diff --git a/libc/bionic/locale.cpp b/libc/bionic/locale.cpp
index 3752fa4..5a1da43 100644
--- a/libc/bionic/locale.cpp
+++ b/libc/bionic/locale.cpp
@@ -36,43 +36,43 @@
   // Because we only support one locale, these are just tokens with no data.
 };
 
-static pthread_once_t gLocaleOnce = PTHREAD_ONCE_INIT;
-static lconv gLocale;
+static pthread_once_t g_locale_once = PTHREAD_ONCE_INIT;
+static lconv g_locale;
 
 // We don't use pthread_once for this so that we know when the resource (a TLS slot) will be taken.
-static pthread_key_t gUselocaleKey;
+static pthread_key_t g_uselocale_key;
 __attribute__((constructor)) static void __bionic_tls_uselocale_key_init() {
-  pthread_key_create(&gUselocaleKey, NULL);
+  pthread_key_create(&g_uselocale_key, NULL);
 }
 
 static void __locale_init() {
-  gLocale.decimal_point = const_cast<char*>(".");
+  g_locale.decimal_point = const_cast<char*>(".");
 
   char* not_available = const_cast<char*>("");
-  gLocale.thousands_sep = not_available;
-  gLocale.grouping = not_available;
-  gLocale.int_curr_symbol = not_available;
-  gLocale.currency_symbol = not_available;
-  gLocale.mon_decimal_point = not_available;
-  gLocale.mon_thousands_sep = not_available;
-  gLocale.mon_grouping = not_available;
-  gLocale.positive_sign = not_available;
-  gLocale.negative_sign = not_available;
+  g_locale.thousands_sep = not_available;
+  g_locale.grouping = not_available;
+  g_locale.int_curr_symbol = not_available;
+  g_locale.currency_symbol = not_available;
+  g_locale.mon_decimal_point = not_available;
+  g_locale.mon_thousands_sep = not_available;
+  g_locale.mon_grouping = not_available;
+  g_locale.positive_sign = not_available;
+  g_locale.negative_sign = not_available;
 
-  gLocale.int_frac_digits = CHAR_MAX;
-  gLocale.frac_digits = CHAR_MAX;
-  gLocale.p_cs_precedes = CHAR_MAX;
-  gLocale.p_sep_by_space = CHAR_MAX;
-  gLocale.n_cs_precedes = CHAR_MAX;
-  gLocale.n_sep_by_space = CHAR_MAX;
-  gLocale.p_sign_posn = CHAR_MAX;
-  gLocale.n_sign_posn = CHAR_MAX;
-  gLocale.int_p_cs_precedes = CHAR_MAX;
-  gLocale.int_p_sep_by_space = CHAR_MAX;
-  gLocale.int_n_cs_precedes = CHAR_MAX;
-  gLocale.int_n_sep_by_space = CHAR_MAX;
-  gLocale.int_p_sign_posn = CHAR_MAX;
-  gLocale.int_n_sign_posn = CHAR_MAX;
+  g_locale.int_frac_digits = CHAR_MAX;
+  g_locale.frac_digits = CHAR_MAX;
+  g_locale.p_cs_precedes = CHAR_MAX;
+  g_locale.p_sep_by_space = CHAR_MAX;
+  g_locale.n_cs_precedes = CHAR_MAX;
+  g_locale.n_sep_by_space = CHAR_MAX;
+  g_locale.p_sign_posn = CHAR_MAX;
+  g_locale.n_sign_posn = CHAR_MAX;
+  g_locale.int_p_cs_precedes = CHAR_MAX;
+  g_locale.int_p_sep_by_space = CHAR_MAX;
+  g_locale.int_n_cs_precedes = CHAR_MAX;
+  g_locale.int_n_sep_by_space = CHAR_MAX;
+  g_locale.int_p_sign_posn = CHAR_MAX;
+  g_locale.int_n_sign_posn = CHAR_MAX;
 }
 
 static bool __bionic_current_locale_is_utf8 = false;
@@ -88,8 +88,8 @@
 }
 
 lconv* localeconv() {
-  pthread_once(&gLocaleOnce, __locale_init);
-  return &gLocale;
+  pthread_once(&g_locale_once, __locale_init);
+  return &g_locale;
 }
 
 locale_t duplocale(locale_t l) {
@@ -140,7 +140,7 @@
 }
 
 locale_t uselocale(locale_t new_locale) {
-  locale_t old_locale = static_cast<locale_t>(pthread_getspecific(gUselocaleKey));
+  locale_t old_locale = static_cast<locale_t>(pthread_getspecific(g_uselocale_key));
 
   // If this is the first call to uselocale(3) on this thread, we return LC_GLOBAL_LOCALE.
   if (old_locale == NULL) {
@@ -148,7 +148,7 @@
   }
 
   if (new_locale != NULL) {
-    pthread_setspecific(gUselocaleKey, new_locale);
+    pthread_setspecific(g_uselocale_key, new_locale);
   }
 
   return old_locale;
diff --git a/libc/bionic/malloc_debug_check.cpp b/libc/bionic/malloc_debug_check.cpp
index 7dd8e3c..11578a3 100644
--- a/libc/bionic/malloc_debug_check.cpp
+++ b/libc/bionic/malloc_debug_check.cpp
@@ -53,8 +53,8 @@
 #include "private/ScopedPthreadMutexLocker.h"
 
 /* libc.debug.malloc.backlog */
-extern unsigned int gMallocDebugBacklog;
-extern int gMallocDebugLevel;
+extern unsigned int g_malloc_debug_backlog;
+extern int g_malloc_debug_level;
 
 #define MAX_BACKTRACE_DEPTH 16
 #define ALLOCATION_TAG      0x1ee7d00d
@@ -108,8 +108,10 @@
     return reinterpret_cast<const hdr_t*>(user) - 1;
 }
 
-
-static unsigned gAllocatedBlockCount;
+// TODO: introduce a struct for this global state.
+// There are basically two lists here, the regular list and the backlog list.
+// We should be able to remove the duplication.
+static unsigned g_allocated_block_count;
 static hdr_t* tail;
 static hdr_t* head;
 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
@@ -188,7 +190,7 @@
     hdr->size = size;
     init_front_guard(hdr);
     init_rear_guard(hdr);
-    ++gAllocatedBlockCount;
+    ++g_allocated_block_count;
     add_locked(hdr, &tail, &head);
 }
 
@@ -199,7 +201,7 @@
 
     ScopedPthreadMutexLocker locker(&lock);
     del_locked(hdr, &tail, &head);
-    --gAllocatedBlockCount;
+    --g_allocated_block_count;
     return 0;
 }
 
@@ -306,7 +308,7 @@
 
 static inline int del_leak(hdr_t* hdr, int* safe) {
     ScopedPthreadMutexLocker locker(&lock);
-    return del_and_check_locked(hdr, &tail, &head, &gAllocatedBlockCount, safe);
+    return del_and_check_locked(hdr, &tail, &head, &g_allocated_block_count, safe);
 }
 
 static inline void add_to_backlog(hdr_t* hdr) {
@@ -316,7 +318,7 @@
     add_locked(hdr, &backlog_tail, &backlog_head);
     poison(hdr);
     /* If we've exceeded the maximum backlog, clear it up */
-    while (backlog_num > gMallocDebugBacklog) {
+    while (backlog_num > g_malloc_debug_backlog) {
         hdr_t* gone = backlog_tail;
         del_from_backlog_locked(gone);
         dlfree(gone->base);
@@ -508,7 +510,7 @@
 
 static void ReportMemoryLeaks() {
   // We only track leaks at level 10.
-  if (gMallocDebugLevel != 10) {
+  if (g_malloc_debug_level != 10) {
     return;
   }
 
@@ -522,13 +524,13 @@
     exe[count] = '\0';
   }
 
-  if (gAllocatedBlockCount == 0) {
+  if (g_allocated_block_count == 0) {
     log_message("+++ %s did not leak", exe);
     return;
   }
 
   size_t index = 1;
-  const size_t total = gAllocatedBlockCount;
+  const size_t total = g_allocated_block_count;
   while (head != NULL) {
     int safe;
     hdr_t* block = head;
diff --git a/libc/bionic/malloc_debug_common.cpp b/libc/bionic/malloc_debug_common.cpp
index 4fa4b6e..356ecb1 100644
--- a/libc/bionic/malloc_debug_common.cpp
+++ b/libc/bionic/malloc_debug_common.cpp
@@ -54,8 +54,8 @@
  */
 int gMallocLeakZygoteChild = 0;
 
-pthread_mutex_t gAllocationsMutex = PTHREAD_MUTEX_INITIALIZER;
-HashTable gHashTable;
+pthread_mutex_t g_allocations_mutex = PTHREAD_MUTEX_INITIALIZER;
+HashTable g_hash_table;
 
 // =============================================================================
 // output functions
@@ -122,9 +122,9 @@
     }
     *totalMemory = 0;
 
-    ScopedPthreadMutexLocker locker(&gAllocationsMutex);
+    ScopedPthreadMutexLocker locker(&g_allocations_mutex);
 
-    if (gHashTable.count == 0) {
+    if (g_hash_table.count == 0) {
         *info = NULL;
         *overallSize = 0;
         *infoSize = 0;
@@ -132,12 +132,12 @@
         return;
     }
 
-    HashEntry** list = static_cast<HashEntry**>(dlmalloc(sizeof(void*) * gHashTable.count));
+    HashEntry** list = static_cast<HashEntry**>(dlmalloc(sizeof(void*) * g_hash_table.count));
 
     // get the entries into an array to be sorted
     int index = 0;
     for (size_t i = 0 ; i < HASHTABLE_SIZE ; ++i) {
-        HashEntry* entry = gHashTable.slots[i];
+        HashEntry* entry = g_hash_table.slots[i];
         while (entry != NULL) {
             list[index] = entry;
             *totalMemory = *totalMemory +
@@ -149,7 +149,7 @@
 
     // XXX: the protocol doesn't allow variable size for the stack trace (yet)
     *infoSize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * BACKTRACE_SIZE);
-    *overallSize = *infoSize * gHashTable.count;
+    *overallSize = *infoSize * g_hash_table.count;
     *backtraceSize = BACKTRACE_SIZE;
 
     // now get a byte array big enough for this
@@ -161,10 +161,10 @@
         return;
     }
 
-    qsort(list, gHashTable.count, sizeof(void*), hash_entry_compare);
+    qsort(list, g_hash_table.count, sizeof(void*), hash_entry_compare);
 
     uint8_t* head = *info;
-    const int count = gHashTable.count;
+    const int count = g_hash_table.count;
     for (int i = 0 ; i < count ; ++i) {
         HashEntry* entry = list[i];
         size_t entrySize = (sizeof(size_t) * 2) + (sizeof(uintptr_t) * entry->numEntries);
@@ -253,7 +253,7 @@
 #include "private/libc_logging.h"
 
 /* Table for dispatching malloc calls, depending on environment. */
-static MallocDebug gMallocUse __attribute__((aligned(32))) = {
+static MallocDebug g_malloc_dispatch_table __attribute__((aligned(32))) = {
     dlmalloc, dlfree, dlcalloc, dlrealloc, dlmemalign, dlmalloc_usable_size
 };
 
@@ -286,11 +286,11 @@
  * backlog we use to detect multiple frees.  If the property is not set, the
  * backlog length defaults to BACKLOG_DEFAULT_LEN.
  */
-unsigned int gMallocDebugBacklog;
+unsigned int g_malloc_debug_backlog;
 #define BACKLOG_DEFAULT_LEN 100
 
 /* The value of libc.debug.malloc. */
-int gMallocDebugLevel;
+int g_malloc_debug_level;
 
 template<typename FunctionType>
 static void InitMallocFunction(void* malloc_impl_handler, FunctionType* func, const char* prefix, const char* suffix) {
@@ -304,7 +304,7 @@
 
 static void InitMalloc(void* malloc_impl_handler, MallocDebug* table, const char* prefix) {
     __libc_format_log(ANDROID_LOG_INFO, "libc", "%s: using libc.debug.malloc %d (%s)\n",
-                      __progname, gMallocDebugLevel, prefix);
+                      __progname, g_malloc_debug_level, prefix);
 
     InitMallocFunction<MallocDebugMalloc>(malloc_impl_handler, &table->malloc, prefix, "malloc");
     InitMallocFunction<MallocDebugFree>(malloc_impl_handler, &table->free, prefix, "free");
@@ -332,7 +332,7 @@
         if (__system_property_get("ro.kernel.memcheck", memcheck_tracing)) {
             if (memcheck_tracing[0] != '0') {
                 // Emulator has started with memory tracing enabled. Enforce it.
-                gMallocDebugLevel = 20;
+                g_malloc_debug_level = 20;
                 memcheck_enabled = 1;
             }
         }
@@ -340,13 +340,13 @@
 
     /* If debug level has not been set by memcheck option in the emulator,
      * lets grab it from libc.debug.malloc system property. */
-    if (gMallocDebugLevel == 0 && __system_property_get("libc.debug.malloc", env)) {
-        gMallocDebugLevel = atoi(env);
+    if (g_malloc_debug_level == 0 && __system_property_get("libc.debug.malloc", env)) {
+        g_malloc_debug_level = atoi(env);
     }
 
     /* Debug level 0 means that we should use dlxxx allocation
      * routines (default). */
-    if (gMallocDebugLevel == 0) {
+    if (g_malloc_debug_level == 0) {
         return;
     }
 
@@ -360,24 +360,24 @@
     }
 
     // mksh is way too leaky. http://b/7291287.
-    if (gMallocDebugLevel >= 10) {
+    if (g_malloc_debug_level >= 10) {
         if (strcmp(__progname, "sh") == 0 || strcmp(__progname, "/system/bin/sh") == 0) {
             return;
         }
     }
 
     // Choose the appropriate .so for the requested debug level.
-    switch (gMallocDebugLevel) {
+    switch (g_malloc_debug_level) {
         case 1:
         case 5:
         case 10: {
             char debug_backlog[PROP_VALUE_MAX];
             if (__system_property_get("libc.debug.malloc.backlog", debug_backlog)) {
-                gMallocDebugBacklog = atoi(debug_backlog);
-                info_log("%s: setting backlog length to %d\n", __progname, gMallocDebugBacklog);
+                g_malloc_debug_backlog = atoi(debug_backlog);
+                info_log("%s: setting backlog length to %d\n", __progname, g_malloc_debug_backlog);
             }
-            if (gMallocDebugBacklog == 0) {
-                gMallocDebugBacklog = BACKLOG_DEFAULT_LEN;
+            if (g_malloc_debug_backlog == 0) {
+                g_malloc_debug_backlog = BACKLOG_DEFAULT_LEN;
             }
             so_name = "libc_malloc_debug_leak.so";
             break;
@@ -386,7 +386,7 @@
             // Quick check: debug level 20 can only be handled in emulator.
             if (!qemu_running) {
                 error_log("%s: Debug level %d can only be set in emulator\n",
-                          __progname, gMallocDebugLevel);
+                          __progname, g_malloc_debug_level);
                 return;
             }
             // Make sure that memory checking has been enabled in emulator.
@@ -398,7 +398,7 @@
             so_name = "libc_malloc_debug_qemu.so";
             break;
         default:
-            error_log("%s: Debug level %d is unknown\n", __progname, gMallocDebugLevel);
+            error_log("%s: Debug level %d is unknown\n", __progname, g_malloc_debug_level);
             return;
     }
 
@@ -406,7 +406,7 @@
     void* malloc_impl_handle = dlopen(so_name, RTLD_LAZY);
     if (malloc_impl_handle == NULL) {
         error_log("%s: Missing module %s required for malloc debug level %d: %s",
-                  __progname, so_name, gMallocDebugLevel, dlerror());
+                  __progname, so_name, g_malloc_debug_level, dlerror());
         return;
     }
 
@@ -424,7 +424,7 @@
         return;
     }
 
-    if (gMallocDebugLevel == 20) {
+    if (g_malloc_debug_level == 20) {
         // For memory checker we need to do extra initialization.
         typedef int (*MemCheckInit)(int, const char*);
         MemCheckInit memcheck_initialize =
@@ -445,35 +445,35 @@
 
 
     // Initialize malloc dispatch table with appropriate routines.
-    switch (gMallocDebugLevel) {
+    switch (g_malloc_debug_level) {
         case 1:
-            InitMalloc(malloc_impl_handle, &gMallocUse, "leak");
+            InitMalloc(malloc_impl_handle, &g_malloc_dispatch_table, "leak");
             break;
         case 5:
-            InitMalloc(malloc_impl_handle, &gMallocUse, "fill");
+            InitMalloc(malloc_impl_handle, &g_malloc_dispatch_table, "fill");
             break;
         case 10:
-            InitMalloc(malloc_impl_handle, &gMallocUse, "chk");
+            InitMalloc(malloc_impl_handle, &g_malloc_dispatch_table, "chk");
             break;
         case 20:
-            InitMalloc(malloc_impl_handle, &gMallocUse, "qemu_instrumented");
+            InitMalloc(malloc_impl_handle, &g_malloc_dispatch_table, "qemu_instrumented");
             break;
         default:
             break;
     }
 
     // Make sure dispatch table is initialized
-    if ((gMallocUse.malloc == NULL) ||
-        (gMallocUse.free == NULL) ||
-        (gMallocUse.calloc == NULL) ||
-        (gMallocUse.realloc == NULL) ||
-        (gMallocUse.memalign == NULL) ||
-        (gMallocUse.malloc_usable_size == NULL)) {
+    if ((g_malloc_dispatch_table.malloc == NULL) ||
+        (g_malloc_dispatch_table.free == NULL) ||
+        (g_malloc_dispatch_table.calloc == NULL) ||
+        (g_malloc_dispatch_table.realloc == NULL) ||
+        (g_malloc_dispatch_table.memalign == NULL) ||
+        (g_malloc_dispatch_table.malloc_usable_size == NULL)) {
         error_log("%s: some symbols for libc.debug.malloc level %d were not found (see above)",
-                  __progname, gMallocDebugLevel);
+                  __progname, g_malloc_debug_level);
         dlclose(malloc_impl_handle);
     } else {
-        __libc_malloc_dispatch = &gMallocUse;
+        __libc_malloc_dispatch = &g_malloc_dispatch_table;
         libc_malloc_impl_handle = malloc_impl_handle;
     }
 }
diff --git a/libc/bionic/malloc_debug_leak.cpp b/libc/bionic/malloc_debug_leak.cpp
index 3397def..146cddc 100644
--- a/libc/bionic/malloc_debug_leak.cpp
+++ b/libc/bionic/malloc_debug_leak.cpp
@@ -61,8 +61,8 @@
 
 // Global variables defined in malloc_debug_common.c
 extern int gMallocLeakZygoteChild;
-extern pthread_mutex_t gAllocationsMutex;
-extern HashTable gHashTable;
+extern pthread_mutex_t g_allocations_mutex;
+extern HashTable g_hash_table;
 
 // =============================================================================
 // stack trace functions
@@ -138,7 +138,7 @@
         size |= SIZE_FLAG_ZYGOTE_CHILD;
     }
 
-    HashEntry* entry = find_entry(&gHashTable, slot, backtrace, numEntries, size);
+    HashEntry* entry = find_entry(&g_hash_table, slot, backtrace, numEntries, size);
 
     if (entry != NULL) {
         entry->allocations++;
@@ -151,20 +151,20 @@
         entry->allocations = 1;
         entry->slot = slot;
         entry->prev = NULL;
-        entry->next = gHashTable.slots[slot];
+        entry->next = g_hash_table.slots[slot];
         entry->numEntries = numEntries;
         entry->size = size;
 
         memcpy(entry->backtrace, backtrace, numEntries * sizeof(uintptr_t));
 
-        gHashTable.slots[slot] = entry;
+        g_hash_table.slots[slot] = entry;
 
         if (entry->next != NULL) {
             entry->next->prev = entry;
         }
 
         // we just added an entry, increase the size of the hashtable
-        gHashTable.count++;
+        g_hash_table.count++;
     }
 
     return entry;
@@ -174,7 +174,7 @@
     if (entry != NULL) {
         int i;
         for (i = 0 ; i < HASHTABLE_SIZE ; i++) {
-            HashEntry* e1 = gHashTable.slots[i];
+            HashEntry* e1 = g_hash_table.slots[i];
 
             while (e1 != NULL) {
                 if (e1 == entry) {
@@ -198,11 +198,11 @@
 
     if (prev == NULL) {
         // we are the head of the list. set the head to be next
-        gHashTable.slots[entry->slot] = entry->next;
+        g_hash_table.slots[entry->slot] = entry->next;
     }
 
     // we just removed and entry, decrease the size of the hashtable
-    gHashTable.count--;
+    g_hash_table.count--;
 }
 
 // =============================================================================
@@ -277,7 +277,7 @@
 
     void* base = dlmalloc(size);
     if (base != NULL) {
-        ScopedPthreadMutexLocker locker(&gAllocationsMutex);
+        ScopedPthreadMutexLocker locker(&g_allocations_mutex);
 
         uintptr_t backtrace[BACKTRACE_SIZE];
         size_t numEntries = get_backtrace(backtrace, BACKTRACE_SIZE);
@@ -296,7 +296,7 @@
 
 extern "C" void leak_free(void* mem) {
     if (mem != NULL) {
-        ScopedPthreadMutexLocker locker(&gAllocationsMutex);
+        ScopedPthreadMutexLocker locker(&g_allocations_mutex);
 
         // check the guard to make sure it is valid
         AllocationEntry* header = to_header(mem);
diff --git a/libc/bionic/pthread_accessor.h b/libc/bionic/pthread_accessor.h
index ccb71bb..df4a5a2 100644
--- a/libc/bionic/pthread_accessor.h
+++ b/libc/bionic/pthread_accessor.h
@@ -26,7 +26,7 @@
  public:
   explicit pthread_accessor(pthread_t desired_thread) {
     Lock();
-    for (thread_ = gThreadList; thread_ != NULL; thread_ = thread_->next) {
+    for (thread_ = g_thread_list; thread_ != NULL; thread_ = thread_->next) {
       if (thread_ == reinterpret_cast<pthread_internal_t*>(desired_thread)) {
         break;
       }
@@ -41,7 +41,7 @@
     if (is_locked_) {
       is_locked_ = false;
       thread_ = NULL;
-      pthread_mutex_unlock(&gThreadListLock);
+      pthread_mutex_unlock(&g_thread_list_lock);
     }
   }
 
@@ -54,7 +54,7 @@
   bool is_locked_;
 
   void Lock() {
-    pthread_mutex_lock(&gThreadListLock);
+    pthread_mutex_lock(&g_thread_list_lock);
     is_locked_ = true;
   }
 
diff --git a/libc/bionic/pthread_atfork.cpp b/libc/bionic/pthread_atfork.cpp
index c0664a9..b845f7d 100644
--- a/libc/bionic/pthread_atfork.cpp
+++ b/libc/bionic/pthread_atfork.cpp
@@ -29,8 +29,6 @@
 #include <errno.h>
 #include <pthread.h>
 
-static pthread_mutex_t gAtForkListMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
-
 struct atfork_t {
   atfork_t* next;
   atfork_t* prev;
@@ -45,7 +43,8 @@
   atfork_t* last;
 };
 
-static atfork_list_t gAtForkList = { NULL, NULL };
+static pthread_mutex_t g_atfork_list_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
+static atfork_list_t g_atfork_list = { NULL, NULL };
 
 void __bionic_atfork_run_prepare() {
   // We lock the atfork list here, unlock it in the parent, and reset it in the child.
@@ -54,12 +53,12 @@
   //
   // TODO: If a handler tries to mutate the list, they'll block. We should probably copy
   // the list before forking, and have prepare, parent, and child all work on the consistent copy.
-  pthread_mutex_lock(&gAtForkListMutex);
+  pthread_mutex_lock(&g_atfork_list_mutex);
 
   // Call pthread_atfork() prepare handlers. POSIX states that the prepare
   // handlers should be called in the reverse order of the parent/child
   // handlers, so we iterate backwards.
-  for (atfork_t* it = gAtForkList.last; it != NULL; it = it->prev) {
+  for (atfork_t* it = g_atfork_list.last; it != NULL; it = it->prev) {
     if (it->prepare != NULL) {
       it->prepare();
     }
@@ -67,23 +66,23 @@
 }
 
 void __bionic_atfork_run_child() {
-  for (atfork_t* it = gAtForkList.first; it != NULL; it = it->next) {
+  for (atfork_t* it = g_atfork_list.first; it != NULL; it = it->next) {
     if (it->child != NULL) {
       it->child();
     }
   }
 
-  gAtForkListMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
+  g_atfork_list_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
 }
 
 void __bionic_atfork_run_parent() {
-  for (atfork_t* it = gAtForkList.first; it != NULL; it = it->next) {
+  for (atfork_t* it = g_atfork_list.first; it != NULL; it = it->next) {
     if (it->parent != NULL) {
       it->parent();
     }
   }
 
-  pthread_mutex_unlock(&gAtForkListMutex);
+  pthread_mutex_unlock(&g_atfork_list_mutex);
 }
 
 int pthread_atfork(void (*prepare)(void), void (*parent)(void), void(*child)(void)) {
@@ -96,20 +95,20 @@
   entry->parent = parent;
   entry->child = child;
 
-  pthread_mutex_lock(&gAtForkListMutex);
+  pthread_mutex_lock(&g_atfork_list_mutex);
 
   // Append 'entry' to the list.
   entry->next = NULL;
-  entry->prev = gAtForkList.last;
+  entry->prev = g_atfork_list.last;
   if (entry->prev != NULL) {
     entry->prev->next = entry;
   }
-  if (gAtForkList.first == NULL) {
-    gAtForkList.first = entry;
+  if (g_atfork_list.first == NULL) {
+    g_atfork_list.first = entry;
   }
-  gAtForkList.last = entry;
+  g_atfork_list.last = entry;
 
-  pthread_mutex_unlock(&gAtForkListMutex);
+  pthread_mutex_unlock(&g_atfork_list_mutex);
 
   return 0;
 }
diff --git a/libc/bionic/pthread_create.cpp b/libc/bionic/pthread_create.cpp
index f62dc15..303af81 100644
--- a/libc/bionic/pthread_create.cpp
+++ b/libc/bionic/pthread_create.cpp
@@ -52,9 +52,9 @@
 extern "C" __LIBC_HIDDEN__ void __init_user_desc(struct user_desc*, int, void*);
 #endif
 
-static pthread_mutex_t gPthreadStackCreationLock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t g_pthread_stack_creation_lock = PTHREAD_MUTEX_INITIALIZER;
 
-static pthread_mutex_t gDebuggerNotificationLock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t g_debugger_notification_lock = PTHREAD_MUTEX_INITIALIZER;
 
 extern "C" int __isthreaded;
 
@@ -111,7 +111,7 @@
 }
 
 static void* __create_thread_stack(pthread_internal_t* thread) {
-  ScopedPthreadMutexLocker lock(&gPthreadStackCreationLock);
+  ScopedPthreadMutexLocker lock(&g_pthread_stack_creation_lock);
 
   // Create a new private anonymous map.
   int prot = PROT_READ | PROT_WRITE;
@@ -258,7 +258,7 @@
 
   // Notify any debuggers about the new thread.
   {
-    ScopedPthreadMutexLocker debugger_locker(&gDebuggerNotificationLock);
+    ScopedPthreadMutexLocker debugger_locker(&g_debugger_notification_lock);
     _thread_created_hook(thread->tid);
   }
 
diff --git a/libc/bionic/pthread_debug.cpp b/libc/bionic/pthread_debug.cpp
deleted file mode 100644
index f01f040..0000000
--- a/libc/bionic/pthread_debug.cpp
+++ /dev/null
@@ -1,717 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#include <sys/types.h>
-#include <sys/atomics.h>
-#include <sys/system_properties.h>
-#include <sys/mman.h>
-
-#include <stdint.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <errno.h>
-#include <pthread.h>
-#include <unwind.h>
-#include <unistd.h>
-
-#include "private/bionic_tls.h"
-#include "debug_mapinfo.h"
-#include "debug_stacktrace.h"
-#include "private/libc_logging.h"
-
-/*
- * ===========================================================================
- *      Deadlock prediction
- * ===========================================================================
- */
-/*
-The idea is to predict the possibility of deadlock by recording the order
-in which locks are acquired.  If we see an attempt to acquire a lock
-out of order, we can identify the locks and offending code.
-
-To make this work, we need to keep track of the locks held by each thread,
-and create history trees for each lock.  When a thread tries to acquire
-a new lock, we walk through the "history children" of the lock, looking
-for a match with locks the thread already holds.  If we find a match,
-it means the thread has made a request that could result in a deadlock.
-
-To support recursive locks, we always allow re-locking a currently-held
-lock, and maintain a recursion depth count.
-
-An ASCII-art example, where letters represent locks:
-
-        A
-       /|\
-      / | \
-     B  |  D
-      \ |
-       \|
-        C
-
-The above is the tree we'd have after handling lock synchronization
-sequences "ABC", "AC", "AD".  A has three children, {B, C, D}.  C is also
-a child of B.  (The lines represent pointers between parent and child.
-Every node can have multiple parents and multiple children.)
-
-If we hold AC, and want to lock B, we recursively search through B's
-children to see if A or C appears.  It does, so we reject the attempt.
-(A straightforward way to implement it: add a link from C to B, then
-determine whether the graph starting at B contains a cycle.)
-
-If we hold AC and want to lock D, we would succeed, creating a new link
-from C to D.
-
-Updates to MutexInfo structs are only allowed for the thread that holds
-the lock, so we actually do most of our deadlock prediction work after
-the lock has been acquired.
-*/
-
-#if PTHREAD_DEBUG_ENABLED
-
-// =============================================================================
-// log functions
-// =============================================================================
-
-#define LOGD(format, ...)  \
-    __libc_format_log(ANDROID_LOG_DEBUG, "pthread_debug", (format), ##__VA_ARGS__ )
-
-#define LOGW(format, ...)  \
-    __libc_format_log(ANDROID_LOG_WARN, "pthread_debug", (format), ##__VA_ARGS__ )
-
-#define LOGE(format, ...)  \
-    __libc_format_log(ANDROID_LOG_ERROR, "pthread_debug", (format), ##__VA_ARGS__ )
-
-#define LOGI(format, ...)  \
-    __libc_format_log(ANDROID_LOG_INFO, "pthread_debug", (format), ##__VA_ARGS__ )
-
-static const char* const kStartBanner =
-        "===============================================================";
-
-static const char* const kEndBanner =
-        "===============================================================";
-
-extern const char* __progname;
-
-#define STACK_TRACE_DEPTH 16
-
-/****************************************************************************/
-
-/*
- * level <= 0 : deadlock prediction disabled
- * level    1 : deadlock prediction enabled, w/o call stacks
- * level    2 : deadlock prediction enabled w/ call stacks
- */
-#define CAPTURE_CALLSTACK 2
-static int sPthreadDebugLevel = 0;
-static pid_t sPthreadDebugDisabledThread = -1;
-static pthread_mutex_t sDbgLock = PTHREAD_MUTEX_INITIALIZER;
-
-/****************************************************************************/
-
-/* some simple/lame malloc replacement
- * NOT thread-safe and leaks everything
- */
-
-#define DBG_ALLOC_BLOCK_SIZE PAGESIZE
-static size_t sDbgAllocOffset = DBG_ALLOC_BLOCK_SIZE;
-static char* sDbgAllocPtr = NULL;
-
-template <typename T>
-static T* DbgAllocLocked(size_t count = 1) {
-    size_t size = sizeof(T) * count;
-    if ((sDbgAllocOffset + size) > DBG_ALLOC_BLOCK_SIZE) {
-        sDbgAllocOffset = 0;
-        sDbgAllocPtr = reinterpret_cast<char*>(mmap(NULL, DBG_ALLOC_BLOCK_SIZE,
-                                                    PROT_READ|PROT_WRITE,
-                                                    MAP_ANON | MAP_PRIVATE, 0, 0));
-        if (sDbgAllocPtr == MAP_FAILED) {
-            return NULL;
-        }
-    }
-    void* addr = sDbgAllocPtr + sDbgAllocOffset;
-    sDbgAllocOffset += size;
-    return reinterpret_cast<T*>(addr);
-}
-
-static void* debug_realloc(void *ptr, size_t size, size_t old_size) {
-    void* addr = mmap(NULL, size, PROT_READ|PROT_WRITE,
-            MAP_ANON | MAP_PRIVATE, 0, 0);
-    if (addr != MAP_FAILED) {
-        if (ptr) {
-            memcpy(addr, ptr, old_size);
-            munmap(ptr, old_size);
-        }
-    } else {
-        addr = NULL;
-    }
-    return addr;
-}
-
-/*****************************************************************************/
-
-struct MutexInfo;
-
-typedef struct CallStack {
-    uintptr_t    depth;
-    uintptr_t*   addrs;
-} CallStack;
-
-typedef struct MutexInfo* MutexInfoListEntry;
-typedef struct CallStack  CallStackListEntry;
-
-typedef struct GrowingList {
-    int alloc;
-    int count;
-    union {
-        void*               data;
-        MutexInfoListEntry* list;
-        CallStackListEntry* stack;
-    };
-} GrowingList;
-
-typedef GrowingList MutexInfoList;
-typedef GrowingList CallStackList;
-
-typedef struct MutexInfo {
-    // thread currently holding the lock or 0
-    pid_t               owner;
-
-    // most-recently-locked doubly-linked list
-    struct MutexInfo*   prev;
-    struct MutexInfo*   next;
-
-    // for reentrant locks
-    int                 lockCount;
-    // when looking for loops in the graph, marks visited nodes
-    int                 historyMark;
-    // the actual mutex
-    pthread_mutex_t*    mutex;
-    // list of locks directly acquired AFTER this one in the same thread
-    MutexInfoList       children;
-    // list of locks directly acquired BEFORE this one in the same thread
-    MutexInfoList       parents;
-    // list of call stacks when a new link is established to this lock form its parent
-    CallStackList       stacks;
-    // call stack when this lock was acquired last
-    int                 stackDepth;
-    uintptr_t           stackTrace[STACK_TRACE_DEPTH];
-} MutexInfo;
-
-static void growingListInit(GrowingList* list) {
-    list->alloc = 0;
-    list->count = 0;
-    list->data = NULL;
-}
-
-static void growingListAdd(GrowingList* pList, size_t objSize) {
-    if (pList->count == pList->alloc) {
-        size_t oldsize = pList->alloc * objSize;
-        pList->alloc += PAGESIZE / objSize;
-        size_t size = pList->alloc * objSize;
-        pList->data = debug_realloc(pList->data, size, oldsize);
-    }
-    pList->count++;
-}
-
-static void initMutexInfo(MutexInfo* object, pthread_mutex_t* mutex) {
-    object->owner = 0;
-    object->prev = 0;
-    object->next = 0;
-    object->lockCount = 0;
-    object->historyMark = 0;
-    object->mutex = mutex;
-    growingListInit(&object->children);
-    growingListInit(&object->parents);
-    growingListInit(&object->stacks);
-    object->stackDepth = 0;
-}
-
-typedef struct ThreadInfo {
-    pid_t       pid;
-    MutexInfo*  mrl;
-} ThreadInfo;
-
-static void initThreadInfo(ThreadInfo* object, pid_t pid) {
-    object->pid = pid;
-    object->mrl = NULL;
-}
-
-/****************************************************************************/
-
-static MutexInfo* get_mutex_info(pthread_mutex_t *mutex);
-static void mutex_lock_checked(MutexInfo* mrl, MutexInfo* object);
-static void mutex_unlock_checked(MutexInfo* object);
-
-/****************************************************************************/
-
-extern "C" int pthread_mutex_lock_impl(pthread_mutex_t *mutex);
-extern "C" int pthread_mutex_unlock_impl(pthread_mutex_t *mutex);
-
-static int pthread_mutex_lock_unchecked(pthread_mutex_t *mutex) {
-    return pthread_mutex_lock_impl(mutex);
-}
-
-static int pthread_mutex_unlock_unchecked(pthread_mutex_t *mutex) {
-    return pthread_mutex_unlock_impl(mutex);
-}
-
-/****************************************************************************/
-
-static void dup_backtrace(CallStack* stack, size_t count, uintptr_t const* addrs) {
-    stack->depth = count;
-    stack->addrs = DbgAllocLocked<uintptr_t>(count);
-    memcpy(stack->addrs, addrs, count * sizeof(uintptr_t));
-}
-
-/****************************************************************************/
-
-static int historyListHas(
-        const MutexInfoList* list, MutexInfo const * obj) {
-    int i;
-    for (i=0; i<list->count; i++) {
-        if (list->list[i] == obj) {
-            return i;
-        }
-    }
-    return -1;
-}
-
-static void historyListAdd(MutexInfoList* pList, MutexInfo* obj) {
-    growingListAdd(pList, sizeof(MutexInfoListEntry));
-    pList->list[pList->count - 1] = obj;
-}
-
-static int historyListRemove(MutexInfoList* pList, MutexInfo* obj) {
-    int i;
-    for (i = pList->count-1; i >= 0; i--) {
-        if (pList->list[i] == obj) {
-            break;
-        }
-    }
-    if (i < 0) {
-        // not found!
-        return 0;
-    }
-
-    if (i != pList->count-1) {
-        // copy the last entry to the new free slot
-        pList->list[i] = pList->list[pList->count-1];
-    }
-    pList->count--;
-    memset(&pList->list[pList->count], 0, sizeof(MutexInfoListEntry));
-    return 1;
-}
-
-static void linkParentToChild(MutexInfo* parent, MutexInfo* child) {
-    historyListAdd(&parent->children, child);
-    historyListAdd(&child->parents, parent);
-}
-
-static void unlinkParentFromChild(MutexInfo* parent, MutexInfo* child) {
-    historyListRemove(&parent->children, child);
-    historyListRemove(&child->parents, parent);
-}
-
-/****************************************************************************/
-
-static void callstackListAdd(CallStackList* pList,
-        int count, uintptr_t const* addrs) {
-    growingListAdd(pList, sizeof(CallStackListEntry));
-    dup_backtrace(&pList->stack[pList->count - 1], count, addrs);
-}
-
-/****************************************************************************/
-
-/*
- * Recursively traverse the object hierarchy starting at "obj".  We mark
- * ourselves on entry and clear the mark on exit.  If we ever encounter
- * a marked object, we have a cycle.
- *
- * Returns "true" if all is well, "false" if we found a cycle.
- */
-
-static int traverseTree(MutexInfo* obj, MutexInfo const* objParent)
-{
-    /*
-     * Have we been here before?
-     */
-    if (obj->historyMark) {
-        int stackDepth;
-        uintptr_t addrs[STACK_TRACE_DEPTH];
-
-        /* Turn off prediction temporarily in this thread while logging */
-        sPthreadDebugDisabledThread = gettid();
-
-        backtrace_startup();
-
-        LOGW("%s\n", kStartBanner);
-        LOGW("pid: %d, tid: %d >>> %s <<<", getpid(), gettid(), __progname);
-        LOGW("Illegal lock attempt:\n");
-        LOGW("--- pthread_mutex_t at %p\n", obj->mutex);
-        stackDepth = get_backtrace(addrs, STACK_TRACE_DEPTH);
-        log_backtrace(addrs, stackDepth);
-
-        LOGW("+++ Currently held locks in this thread (in reverse order):");
-        MutexInfo* cur = obj;
-        pid_t ourtid = gettid();
-        int i;
-        for (i=0 ; i<cur->parents.count ; i++) {
-            MutexInfo* parent = cur->parents.list[i];
-            if (parent->owner == ourtid) {
-                LOGW("--- pthread_mutex_t at %p\n", parent->mutex);
-                if (sPthreadDebugLevel >= CAPTURE_CALLSTACK) {
-                    log_backtrace(parent->stackTrace, parent->stackDepth);
-                }
-                cur = parent;
-                break;
-            }
-        }
-
-        LOGW("+++ Earlier, the following lock order (from last to first) was established\n");
-        return 0;
-    }
-
-    obj->historyMark = 1;
-
-    MutexInfoList* pList = &obj->children;
-    int result = 1;
-    int i;
-    for (i = pList->count-1; i >= 0; i--) {
-        MutexInfo* child = pList->list[i];
-        if (!traverseTree(child,  obj)) {
-            LOGW("--- pthread_mutex_t at %p\n", obj->mutex);
-            if (sPthreadDebugLevel >= CAPTURE_CALLSTACK) {
-                int index = historyListHas(&obj->parents, objParent);
-                if ((size_t)index < (size_t)obj->stacks.count) {
-                    log_backtrace(obj->stacks.stack[index].addrs, obj->stacks.stack[index].depth);
-                } else {
-                    log_backtrace(obj->stackTrace, obj->stackDepth);
-                }
-            }
-            result = 0;
-            break;
-        }
-    }
-
-    obj->historyMark = 0;
-    return result;
-}
-
-/****************************************************************************/
-
-static void mutex_lock_checked(MutexInfo* mrl, MutexInfo* object)
-{
-    pid_t tid = gettid();
-    if (object->owner == tid) {
-        object->lockCount++;
-        return;
-    }
-
-    object->owner = tid;
-    object->lockCount = 0;
-
-    if (sPthreadDebugLevel >= CAPTURE_CALLSTACK) {
-        // always record the call stack when acquiring a lock.
-        // it's not efficient, but is useful during diagnostics
-        object->stackDepth = get_backtrace(object->stackTrace, STACK_TRACE_DEPTH);
-    }
-
-    // no other locks held in this thread -- no deadlock possible!
-    if (mrl == NULL)
-        return;
-
-    // check if the lock we're trying to acquire is a direct descendant of
-    // the most recently locked mutex in this thread, in which case we're
-    // in a good situation -- no deadlock possible
-    if (historyListHas(&mrl->children, object) >= 0)
-        return;
-
-    pthread_mutex_lock_unchecked(&sDbgLock);
-
-    linkParentToChild(mrl, object);
-    if (!traverseTree(object, mrl)) {
-        backtrace_shutdown();
-        LOGW("%s\n", kEndBanner);
-        unlinkParentFromChild(mrl, object);
-        // reenable pthread debugging for this thread
-        sPthreadDebugDisabledThread = -1;
-    } else {
-        // record the call stack for this link
-        // NOTE: the call stack is added at the same index
-        // as mrl in object->parents[]
-        // ie: object->parents.count == object->stacks.count, which is
-        // also the index.
-        if (sPthreadDebugLevel >= CAPTURE_CALLSTACK) {
-            callstackListAdd(&object->stacks,
-                    object->stackDepth, object->stackTrace);
-        }
-    }
-
-    pthread_mutex_unlock_unchecked(&sDbgLock);
-}
-
-static void mutex_unlock_checked(MutexInfo* object)
-{
-    pid_t tid = gettid();
-    if (object->owner == tid) {
-        if (object->lockCount == 0) {
-            object->owner = 0;
-        } else {
-            object->lockCount--;
-        }
-    }
-}
-
-
-// =============================================================================
-// Hash Table functions
-// =============================================================================
-
-/****************************************************************************/
-
-#define HASHTABLE_SIZE      256
-
-typedef struct HashEntry HashEntry;
-struct HashEntry {
-    size_t slot;
-    HashEntry* prev;
-    HashEntry* next;
-    void* data;
-};
-
-typedef struct HashTable HashTable;
-struct HashTable {
-    HashEntry* slots[HASHTABLE_SIZE];
-};
-
-static HashTable sMutexMap;
-static HashTable sThreadMap;
-
-/****************************************************************************/
-
-static uint32_t get_hashcode(void const * key, size_t keySize)
-{
-    uint32_t h = keySize;
-    char const* data = (char const*)key;
-    size_t i;
-    for (i = 0; i < keySize; i++) {
-        h = h * 31 + *data;
-        data++;
-    }
-    return (uint32_t)h;
-}
-
-static size_t get_index(uint32_t h)
-{
-    // We apply this secondary hashing discovered by Doug Lea to defend
-    // against bad hashes.
-    h += ~(h << 9);
-    h ^= (((unsigned int) h) >> 14);
-    h += (h << 4);
-    h ^= (((unsigned int) h) >> 10);
-    return (size_t)h & (HASHTABLE_SIZE - 1);
-}
-
-/****************************************************************************/
-
-static void hashmap_init(HashTable* table) {
-    memset(table, 0, sizeof(HashTable));
-}
-
-static void hashmap_removeEntry(HashTable* table, HashEntry* entry)
-{
-    HashEntry* prev = entry->prev;
-    HashEntry* next = entry->next;
-    if (prev != NULL) entry->prev->next = next;
-    if (next != NULL) entry->next->prev = prev;
-    if (prev == NULL) {
-        // we are the head of the list. set the head to be next
-        table->slots[entry->slot] = entry->next;
-    }
-}
-
-static HashEntry* hashmap_lookup(HashTable* table,
-        void const* key, size_t ksize,
-        int (*equals)(void const* data, void const* key))
-{
-    const uint32_t hash = get_hashcode(key, ksize);
-    const size_t slot = get_index(hash);
-
-    HashEntry* entry = table->slots[slot];
-    while (entry) {
-        if (equals(entry->data, key)) {
-            break;
-        }
-        entry = entry->next;
-    }
-
-    if (entry == NULL) {
-        // create a new entry
-        entry = DbgAllocLocked<HashEntry>();
-        entry->data = NULL;
-        entry->slot = slot;
-        entry->prev = NULL;
-        entry->next = table->slots[slot];
-        if (entry->next != NULL) {
-            entry->next->prev = entry;
-        }
-        table->slots[slot] = entry;
-    }
-    return entry;
-}
-
-/****************************************************************************/
-
-static int MutexInfo_equals(void const* data, void const* key) {
-    return ((MutexInfo const *)data)->mutex == *(pthread_mutex_t **)key;
-}
-
-static MutexInfo* get_mutex_info(pthread_mutex_t *mutex)
-{
-    pthread_mutex_lock_unchecked(&sDbgLock);
-
-    HashEntry* entry = hashmap_lookup(&sMutexMap,
-            &mutex, sizeof(mutex),
-            &MutexInfo_equals);
-    if (entry->data == NULL) {
-        MutexInfo* mutex_info = DbgAllocLocked<MutexInfo>();
-        entry->data = mutex_info;
-        initMutexInfo(mutex_info, mutex);
-    }
-
-    pthread_mutex_unlock_unchecked(&sDbgLock);
-
-    return (MutexInfo *)entry->data;
-}
-
-/****************************************************************************/
-
-static int ThreadInfo_equals(void const* data, void const* key) {
-    return ((ThreadInfo const *)data)->pid == *(pid_t *)key;
-}
-
-static ThreadInfo* get_thread_info(pid_t pid)
-{
-    pthread_mutex_lock_unchecked(&sDbgLock);
-
-    HashEntry* entry = hashmap_lookup(&sThreadMap,
-            &pid, sizeof(pid),
-            &ThreadInfo_equals);
-    if (entry->data == NULL) {
-        ThreadInfo* thread_info = DbgAllocLocked<ThreadInfo>();
-        entry->data = thread_info;
-        initThreadInfo(thread_info, pid);
-    }
-
-    pthread_mutex_unlock_unchecked(&sDbgLock);
-
-    return (ThreadInfo *)entry->data;
-}
-
-static void push_most_recently_locked(MutexInfo* mrl) {
-    ThreadInfo* tinfo = get_thread_info(gettid());
-    mrl->next = NULL;
-    mrl->prev = tinfo->mrl;
-    tinfo->mrl = mrl;
-}
-
-static void remove_most_recently_locked(MutexInfo* mrl) {
-    ThreadInfo* tinfo = get_thread_info(gettid());
-    if (mrl->next) {
-        (mrl->next)->prev = mrl->prev;
-    }
-    if (mrl->prev) {
-        (mrl->prev)->next = mrl->next;
-    }
-    if (tinfo->mrl == mrl) {
-        tinfo->mrl = mrl->next;
-    }
-}
-
-static MutexInfo* get_most_recently_locked() {
-    ThreadInfo* tinfo = get_thread_info(gettid());
-    return tinfo->mrl;
-}
-
-/****************************************************************************/
-
-/*
- * See if we were allowed to grab the lock at this time.  We do it
- * *after* acquiring the lock, rather than before, so that we can
- * freely update the MutexInfo struct.  This seems counter-intuitive,
- * but our goal is deadlock *prediction* not deadlock *prevention*.
- * (If we actually deadlock, the situation is easy to diagnose from
- * a thread dump, so there's no point making a special effort to do
- * the checks before the lock is held.)
- */
-
-extern "C" __LIBC_HIDDEN__ void pthread_debug_mutex_lock_check(pthread_mutex_t *mutex)
-{
-    if (sPthreadDebugLevel == 0) return;
-    // prediction disabled for this thread
-    if (sPthreadDebugDisabledThread == gettid())
-        return;
-    MutexInfo* object = get_mutex_info(mutex);
-    MutexInfo* mrl = get_most_recently_locked();
-    mutex_lock_checked(mrl, object);
-    push_most_recently_locked(object);
-}
-
-/*
- * pthread_debug_mutex_unlock_check() must be called with the mutex
- * still held (ie: before calling the real unlock)
- */
-
-extern "C" __LIBC_HIDDEN__ void pthread_debug_mutex_unlock_check(pthread_mutex_t *mutex)
-{
-    if (sPthreadDebugLevel == 0) return;
-    // prediction disabled for this thread
-    if (sPthreadDebugDisabledThread == gettid())
-        return;
-    MutexInfo* object = get_mutex_info(mutex);
-    remove_most_recently_locked(object);
-    mutex_unlock_checked(object);
-}
-
-#endif // PTHREAD_DEBUG_ENABLED
-
-// Called from libc_init_dynamic() just after system properties have been initialized.
-extern "C" __LIBC_HIDDEN__ void pthread_debug_init() {
-#if PTHREAD_DEBUG_ENABLED
-    char env[PROP_VALUE_MAX];
-    if (__system_property_get("debug.libc.pthread", env)) {
-        int level = atoi(env);
-        if (level) {
-            LOGI("pthread deadlock detection level %d enabled for pid %d (%s)",
-                    level, getpid(), __progname);
-            hashmap_init(&sMutexMap);
-            sPthreadDebugLevel = level;
-        }
-    }
-#endif
-}
diff --git a/libc/bionic/pthread_exit.cpp b/libc/bionic/pthread_exit.cpp
index 2692762..de818cd 100644
--- a/libc/bionic/pthread_exit.cpp
+++ b/libc/bionic/pthread_exit.cpp
@@ -92,7 +92,7 @@
   size_t stack_size = thread->attr.stack_size;
   bool user_allocated_stack = ((thread->attr.flags & PTHREAD_ATTR_FLAG_USER_ALLOCATED_STACK) != 0);
 
-  pthread_mutex_lock(&gThreadListLock);
+  pthread_mutex_lock(&g_thread_list_lock);
   if ((thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) != 0) {
     // The thread is detached, so we can free the pthread_internal_t.
     // First make sure that the kernel does not try to clear the tid field
@@ -110,7 +110,7 @@
     // pthread_join is responsible for destroying the pthread_internal_t for non-detached threads.
     // The kernel will futex_wake on the pthread_internal_t::tid field to wake pthread_join.
   }
-  pthread_mutex_unlock(&gThreadListLock);
+  pthread_mutex_unlock(&g_thread_list_lock);
 
   if (user_allocated_stack) {
     // Cleaning up this thread's stack is the creator's responsibility, not ours.
diff --git a/libc/bionic/pthread_internal.h b/libc/bionic/pthread_internal.h
index 41f4636..295d9d6 100644
--- a/libc/bionic/pthread_internal.h
+++ b/libc/bionic/pthread_internal.h
@@ -86,8 +86,8 @@
  */
 #define PTHREAD_STACK_SIZE_DEFAULT ((1 * 1024 * 1024) - SIGSTKSZ)
 
-__LIBC_HIDDEN__ extern pthread_internal_t* gThreadList;
-__LIBC_HIDDEN__ extern pthread_mutex_t gThreadListLock;
+__LIBC_HIDDEN__ extern pthread_internal_t* g_thread_list;
+__LIBC_HIDDEN__ extern pthread_mutex_t g_thread_list_lock;
 
 __LIBC_HIDDEN__ int __timespec_from_absolute(timespec*, const timespec*, clockid_t);
 
diff --git a/libc/bionic/pthread_internals.cpp b/libc/bionic/pthread_internals.cpp
index d4d6099..baa95d9 100644
--- a/libc/bionic/pthread_internals.cpp
+++ b/libc/bionic/pthread_internals.cpp
@@ -33,8 +33,8 @@
 #include "private/bionic_tls.h"
 #include "private/ScopedPthreadMutexLocker.h"
 
-pthread_internal_t* gThreadList = NULL;
-pthread_mutex_t gThreadListLock = PTHREAD_MUTEX_INITIALIZER;
+pthread_internal_t* g_thread_list = NULL;
+pthread_mutex_t g_thread_list_lock = PTHREAD_MUTEX_INITIALIZER;
 
 void _pthread_internal_remove_locked(pthread_internal_t* thread) {
   if (thread->next != NULL) {
@@ -43,7 +43,7 @@
   if (thread->prev != NULL) {
     thread->prev->next = thread->next;
   } else {
-    gThreadList = thread->next;
+    g_thread_list = thread->next;
   }
 
   // The main thread is not heap-allocated. See __libc_init_tls for the declaration,
@@ -54,15 +54,15 @@
 }
 
 void _pthread_internal_add(pthread_internal_t* thread) {
-  ScopedPthreadMutexLocker locker(&gThreadListLock);
+  ScopedPthreadMutexLocker locker(&g_thread_list_lock);
 
   // We insert at the head.
-  thread->next = gThreadList;
+  thread->next = g_thread_list;
   thread->prev = NULL;
   if (thread->next != NULL) {
     thread->next->prev = thread;
   }
-  gThreadList = thread;
+  g_thread_list = thread;
 }
 
 pthread_internal_t* __get_thread(void) {
diff --git a/libc/bionic/pthread_key.cpp b/libc/bionic/pthread_key.cpp
index 6cc68af..27eab27 100644
--- a/libc/bionic/pthread_key.cpp
+++ b/libc/bionic/pthread_key.cpp
@@ -210,8 +210,8 @@
   }
 
   // Clear value in all threads.
-  pthread_mutex_lock(&gThreadListLock);
-  for (pthread_internal_t*  t = gThreadList; t != NULL; t = t->next) {
+  pthread_mutex_lock(&g_thread_list_lock);
+  for (pthread_internal_t*  t = g_thread_list; t != NULL; t = t->next) {
     // Skip zombie threads. They don't have a valid TLS area any more.
     // Similarly, it is possible to have t->tls == NULL for threads that
     // were just recently created through pthread_create() but whose
@@ -226,7 +226,7 @@
   }
   tls_map.DeleteKey(key);
 
-  pthread_mutex_unlock(&gThreadListLock);
+  pthread_mutex_unlock(&g_thread_list_lock);
   return 0;
 }
 
diff --git a/libc/bionic/pthread_mutex.cpp b/libc/bionic/pthread_mutex.cpp
index c4cd9e0..9fd5d32 100644
--- a/libc/bionic/pthread_mutex.cpp
+++ b/libc/bionic/pthread_mutex.cpp
@@ -445,9 +445,7 @@
     }
 }
 
-__LIBC_HIDDEN__
-int pthread_mutex_lock_impl(pthread_mutex_t *mutex)
-{
+int pthread_mutex_lock(pthread_mutex_t* mutex) {
     int mvalue, mtype, tid, shared;
 
     mvalue = mutex->value;
@@ -523,20 +521,7 @@
     /* NOTREACHED */
 }
 
-int pthread_mutex_lock(pthread_mutex_t *mutex)
-{
-    int err = pthread_mutex_lock_impl(mutex);
-    if (PTHREAD_DEBUG_ENABLED) {
-        if (!err) {
-            pthread_debug_mutex_lock_check(mutex);
-        }
-    }
-    return err;
-}
-
-__LIBC_HIDDEN__
-int pthread_mutex_unlock_impl(pthread_mutex_t *mutex)
-{
+int pthread_mutex_unlock(pthread_mutex_t* mutex) {
     int mvalue, mtype, tid, shared;
 
     mvalue = mutex->value;
@@ -588,17 +573,7 @@
     return 0;
 }
 
-int pthread_mutex_unlock(pthread_mutex_t *mutex)
-{
-    if (PTHREAD_DEBUG_ENABLED) {
-        pthread_debug_mutex_unlock_check(mutex);
-    }
-    return pthread_mutex_unlock_impl(mutex);
-}
-
-__LIBC_HIDDEN__
-int pthread_mutex_trylock_impl(pthread_mutex_t *mutex)
-{
+int pthread_mutex_trylock(pthread_mutex_t* mutex) {
     int mvalue, mtype, tid, shared;
 
     mvalue = mutex->value;
@@ -638,17 +613,6 @@
     return EBUSY;
 }
 
-int pthread_mutex_trylock(pthread_mutex_t *mutex)
-{
-    int err = pthread_mutex_trylock_impl(mutex);
-    if (PTHREAD_DEBUG_ENABLED) {
-        if (!err) {
-            pthread_debug_mutex_lock_check(mutex);
-        }
-    }
-    return err;
-}
-
 static int __pthread_mutex_timedlock(pthread_mutex_t* mutex, const timespec* abs_timeout, clockid_t clock) {
   timespec ts;
 
@@ -761,16 +725,11 @@
     abs_timeout.tv_nsec -= 1000000000;
   }
 
-  int err = __pthread_mutex_timedlock(mutex, &abs_timeout, CLOCK_MONOTONIC);
-  if (err == ETIMEDOUT) {
-    err = EBUSY;
+  int error = __pthread_mutex_timedlock(mutex, &abs_timeout, CLOCK_MONOTONIC);
+  if (error == ETIMEDOUT) {
+    error = EBUSY;
   }
-  if (PTHREAD_DEBUG_ENABLED) {
-    if (!err) {
-      pthread_debug_mutex_lock_check(mutex);
-    }
-  }
-  return err;
+  return error;
 }
 #endif
 
@@ -778,16 +737,12 @@
   return __pthread_mutex_timedlock(mutex, abs_timeout, CLOCK_REALTIME);
 }
 
-int pthread_mutex_destroy(pthread_mutex_t *mutex)
-{
-    int ret;
-
-    /* use trylock to ensure that the mutex value is
-     * valid and is not already locked. */
-    ret = pthread_mutex_trylock_impl(mutex);
-    if (ret != 0)
-        return ret;
-
-    mutex->value = 0xdead10cc;
-    return 0;
+int pthread_mutex_destroy(pthread_mutex_t* mutex) {
+  // Use trylock to ensure that the mutex is valid and not already locked.
+  int error = pthread_mutex_trylock(mutex);
+  if (error != 0) {
+    return error;
+  }
+  mutex->value = 0xdead10cc;
+  return 0;
 }
diff --git a/libc/bionic/thread_atexit.cpp b/libc/bionic/thread_atexit.cpp
index cad65d3..68c119d 100644
--- a/libc/bionic/thread_atexit.cpp
+++ b/libc/bionic/thread_atexit.cpp
@@ -30,7 +30,7 @@
 
 #include <pthread.h>
 
-static pthread_mutex_t gAtExitLock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_mutex_t g_atexit_lock = PTHREAD_MUTEX_INITIALIZER;
 
 __BEGIN_DECLS
 __LIBC_HIDDEN__ void _thread_atexit_lock();
@@ -38,9 +38,9 @@
 __END_DECLS
 
 void _thread_atexit_lock() {
-  pthread_mutex_lock(&gAtExitLock);
+  pthread_mutex_lock(&g_atexit_lock);
 }
 
 void _thread_atexit_unlock() {
-  pthread_mutex_unlock(&gAtExitLock);
+  pthread_mutex_unlock(&g_atexit_lock);
 }
diff --git a/libc/include/sys/user.h b/libc/include/sys/user.h
index 21803d8..18684f1 100644
--- a/libc/include/sys/user.h
+++ b/libc/include/sys/user.h
@@ -103,7 +103,7 @@
 struct user_fpregs_struct {
   unsigned short cwd;
   unsigned short swd;
-  unsigned short twd;
+  unsigned short ftw;
   unsigned short fop;
   __u64 rip;
   __u64 rdp;
diff --git a/libc/include/wchar.h b/libc/include/wchar.h
index 4ac468d..af7593f 100644
--- a/libc/include/wchar.h
+++ b/libc/include/wchar.h
@@ -47,7 +47,7 @@
 #endif
 } mbstate_t;
 
-typedef enum {
+enum {
     WC_TYPE_INVALID = 0,
     WC_TYPE_ALNUM,
     WC_TYPE_ALPHA,
@@ -62,7 +62,9 @@
     WC_TYPE_UPPER,
     WC_TYPE_XDIGIT,
     WC_TYPE_MAX
-} wctype_t;
+};
+
+typedef long wctype_t;
 
 #define  WEOF        ((wint_t)(-1))
 
diff --git a/libc/private/NetdClient.h b/libc/private/NetdClient.h
index 48c05cb..b2ce7a6 100644
--- a/libc/private/NetdClient.h
+++ b/libc/private/NetdClient.h
@@ -20,6 +20,7 @@
 #include <sys/socket.h>
 
 struct NetdClientDispatch {
+    int (*accept)(int, sockaddr*, socklen_t*);
     int (*connect)(int, const sockaddr*, socklen_t);
 };
 
diff --git a/libc/tzcode/localtime.c b/libc/tzcode/localtime.c
index 3efa5dd..9f67dc6 100644
--- a/libc/tzcode/localtime.c
+++ b/libc/tzcode/localtime.c
@@ -2255,12 +2255,12 @@
   _tzLock();
 
   // Our single-item cache.
-  static char* gCachedTimeZoneName;
-  static struct state gCachedTimeZone;
+  static char* g_cached_time_zone_name;
+  static struct state g_cached_time_zone;
 
   // Do we already have this timezone cached?
-  if (gCachedTimeZoneName != NULL && strcmp(name, gCachedTimeZoneName) == 0) {
-    *sp = gCachedTimeZone;
+  if (g_cached_time_zone_name != NULL && strcmp(name, g_cached_time_zone_name) == 0) {
+    *sp = g_cached_time_zone;
     _tzUnlock();
     return 0;
   }
@@ -2269,9 +2269,9 @@
   int rc = tzload(name, sp, doextend);
   if (rc == 0) {
     // Update the cache.
-    free(gCachedTimeZoneName);
-    gCachedTimeZoneName = strdup(name);
-    gCachedTimeZone = *sp;
+    free(g_cached_time_zone_name);
+    g_cached_time_zone_name = strdup(name);
+    g_cached_time_zone = *sp;
   }
 
   _tzUnlock();
diff --git a/libc/upstream-netbsd/lib/libc/inet/inet_ntop.c b/libc/upstream-netbsd/lib/libc/inet/inet_ntop.c
new file mode 100644
index 0000000..d27a5b1
--- /dev/null
+++ b/libc/upstream-netbsd/lib/libc/inet/inet_ntop.c
@@ -0,0 +1,231 @@
+/*	$NetBSD: inet_ntop.c,v 1.11 2014/02/10 16:30:54 christos Exp $	*/
+
+/*
+ * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
+ * Copyright (c) 1996-1999 by Internet Software Consortium.
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
+ * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <sys/cdefs.h>
+#if defined(LIBC_SCCS) && !defined(lint)
+#if 0
+static const char rcsid[] = "Id: inet_ntop.c,v 1.5 2005/11/03 22:59:52 marka Exp";
+#else
+__RCSID("$NetBSD: inet_ntop.c,v 1.11 2014/02/10 16:30:54 christos Exp $");
+#endif
+#endif /* LIBC_SCCS and not lint */
+
+#include "port_before.h"
+
+#include "namespace.h"
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <arpa/nameser.h>
+
+#include <assert.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "port_after.h"
+
+#ifdef __weak_alias
+__weak_alias(inet_ntop,_inet_ntop)
+#endif
+
+/*%
+ * WARNING: Don't even consider trying to compile this on a system where
+ * sizeof(int) < 4.  sizeof(int) > 4 is fine; all the world's not a VAX.
+ */
+
+static const char *inet_ntop4(const u_char *src, char *dst, socklen_t size);
+static const char *inet_ntop6(const u_char *src, char *dst, socklen_t size);
+
+/* char *
+ * inet_ntop(af, src, dst, size)
+ *	convert a network format address to presentation format.
+ * return:
+ *	pointer to presentation format address (`dst'), or NULL (see errno).
+ * author:
+ *	Paul Vixie, 1996.
+ */
+const char *
+inet_ntop(int af, const void *src, char *dst, socklen_t size)
+{
+
+	_DIAGASSERT(src != NULL);
+	_DIAGASSERT(dst != NULL);
+
+	switch (af) {
+	case AF_INET:
+		return inet_ntop4(src, dst, size);
+	case AF_INET6:
+		return inet_ntop6(src, dst, size);
+	default:
+		errno = EAFNOSUPPORT;
+		return NULL;
+	}
+	/* NOTREACHED */
+}
+
+/* const char *
+ * inet_ntop4(src, dst, size)
+ *	format an IPv4 address, more or less like inet_ntoa()
+ * return:
+ *	`dst' (as a const)
+ * notes:
+ *	(1) uses no statics
+ *	(2) takes a u_char* not an in_addr as input
+ * author:
+ *	Paul Vixie, 1996.
+ */
+static const char *
+inet_ntop4(const u_char *src, char *dst, socklen_t size)
+{
+	char tmp[sizeof "255.255.255.255"];
+	int l;
+
+	_DIAGASSERT(src != NULL);
+	_DIAGASSERT(dst != NULL);
+
+	l = snprintf(tmp, sizeof(tmp), "%u.%u.%u.%u",
+	    src[0], src[1], src[2], src[3]);
+	if (l <= 0 || (socklen_t) l >= size)
+		return NULL;
+	strlcpy(dst, tmp, size);
+	return dst;
+}
+
+/* const char *
+ * inet_ntop6(src, dst, size)
+ *	convert IPv6 binary address into presentation (printable) format
+ * author:
+ *	Paul Vixie, 1996.
+ */
+static const char *
+inet_ntop6(const u_char *src, char *dst, socklen_t size)
+{
+	/*
+	 * Note that int32_t and int16_t need only be "at least" large enough
+	 * to contain a value of the specified size.  On some systems, like
+	 * Crays, there is no such thing as an integer variable with 16 bits.
+	 * Keep this in mind if you think this function should have been coded
+	 * to use pointer overlays.  All the world's not a VAX.
+	 */
+	char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"];
+	char *tp, *ep;
+	struct { int base, len; } best, cur;
+	u_int words[NS_IN6ADDRSZ / NS_INT16SZ];
+	int i;
+	int advance;
+
+	_DIAGASSERT(src != NULL);
+	_DIAGASSERT(dst != NULL);
+
+	/*
+	 * Preprocess:
+	 *	Copy the input (bytewise) array into a wordwise array.
+	 *	Find the longest run of 0x00's in src[] for :: shorthanding.
+	 */
+	memset(words, '\0', sizeof words);
+	for (i = 0; i < NS_IN6ADDRSZ; i++)
+		words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
+	best.base = -1;
+	best.len = 0;
+	cur.base = -1;
+	cur.len = 0;
+	for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
+		if (words[i] == 0) {
+			if (cur.base == -1)
+				cur.base = i, cur.len = 1;
+			else
+				cur.len++;
+		} else {
+			if (cur.base != -1) {
+				if (best.base == -1 || cur.len > best.len)
+					best = cur;
+				cur.base = -1;
+			}
+		}
+	}
+	if (cur.base != -1) {
+		if (best.base == -1 || cur.len > best.len)
+			best = cur;
+	}
+	if (best.base != -1 && best.len < 2)
+		best.base = -1;
+
+	/*
+	 * Format the result.
+	 */
+	tp = tmp;
+	ep = tmp + sizeof(tmp);
+	for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
+		/* Are we inside the best run of 0x00's? */
+		if (best.base != -1 && i >= best.base &&
+		    i < (best.base + best.len)) {
+			if (i == best.base)
+				*tp++ = ':';
+			continue;
+		}
+		/* Are we following an initial run of 0x00s or any real hex? */
+		if (i != 0) {
+			if (tp + 1 >= ep)
+				goto out;
+			*tp++ = ':';
+		}
+		/* Is this address an encapsulated IPv4? */
+		if (i == 6 && best.base == 0 &&
+		    (best.len == 6 ||
+		    (best.len == 7 && words[7] != 0x0001) ||
+		    (best.len == 5 && words[5] == 0xffff))) {
+			if (!inet_ntop4(src + 12, tp, (socklen_t)(ep - tp)))
+				goto out;
+			tp += strlen(tp);
+			break;
+		}
+		advance = snprintf(tp, (size_t)(ep - tp), "%x", words[i]);
+		if (advance <= 0 || advance >= ep - tp)
+			goto out;
+		tp += advance;
+	}
+	/* Was it a trailing run of 0x00's? */
+	if (best.base != -1 && (best.base + best.len) == 
+	    (NS_IN6ADDRSZ / NS_INT16SZ)) {
+		if (tp + 1 >= ep)
+			goto out;
+		*tp++ = ':';
+	}
+	if (tp + 1 >= ep)
+		goto out;
+	*tp++ = '\0';
+
+	/*
+	 * Check for overflow, copy, and we're done.
+	 */
+	if ((size_t)(tp - tmp) > size)
+		goto out;
+	strlcpy(dst, tmp, size);
+	return dst;
+out:
+	errno = ENOSPC;
+	return NULL;
+}
+
+/*! \file */
diff --git a/linker/debugger.cpp b/linker/debugger.cpp
index 272c16a..521a599 100644
--- a/linker/debugger.cpp
+++ b/linker/debugger.cpp
@@ -217,7 +217,7 @@
   debugger_msg_t msg;
   msg.action = DEBUGGER_ACTION_CRASH;
   msg.tid = gettid();
-  msg.abort_msg_address = reinterpret_cast<uintptr_t>(gAbortMessage);
+  msg.abort_msg_address = reinterpret_cast<uintptr_t>(g_abort_message);
   msg.original_si_code = (info != NULL) ? info->si_code : 0;
   int ret = TEMP_FAILURE_RETRY(write(s, &msg, sizeof(msg)));
   if (ret == sizeof(msg)) {
diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp
index 0292bdf..a3cad11 100644
--- a/linker/dlfcn.cpp
+++ b/linker/dlfcn.cpp
@@ -29,7 +29,7 @@
 
 /* This file hijacks the symbols stubbed out in libdl.so. */
 
-static pthread_mutex_t gDlMutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
+static pthread_mutex_t g_dl_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER;
 
 static const char* __bionic_set_dlerror(char* new_value) {
   char** dlerror_slot = &reinterpret_cast<char**>(__get_tls())[TLS_SLOT_DLERROR];
@@ -56,18 +56,18 @@
 }
 
 void android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
-  ScopedPthreadMutexLocker locker(&gDlMutex);
+  ScopedPthreadMutexLocker locker(&g_dl_mutex);
   do_android_get_LD_LIBRARY_PATH(buffer, buffer_size);
 }
 
 void android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
-  ScopedPthreadMutexLocker locker(&gDlMutex);
+  ScopedPthreadMutexLocker locker(&g_dl_mutex);
   do_android_update_LD_LIBRARY_PATH(ld_library_path);
 }
 
 void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* extinfo)
 {
-  ScopedPthreadMutexLocker locker(&gDlMutex);
+  ScopedPthreadMutexLocker locker(&g_dl_mutex);
   soinfo* result = do_dlopen(filename, flags, extinfo);
   if (result == NULL) {
     __bionic_format_dlerror("dlopen failed", linker_get_error_buffer());
@@ -81,7 +81,7 @@
 }
 
 void* dlsym(void* handle, const char* symbol) {
-  ScopedPthreadMutexLocker locker(&gDlMutex);
+  ScopedPthreadMutexLocker locker(&g_dl_mutex);
 
   if (handle == NULL) {
     __bionic_format_dlerror("dlsym library handle is null", NULL);
@@ -125,7 +125,7 @@
 }
 
 int dladdr(const void* addr, Dl_info* info) {
-  ScopedPthreadMutexLocker locker(&gDlMutex);
+  ScopedPthreadMutexLocker locker(&g_dl_mutex);
 
   // Determine if this address can be found in any library currently mapped.
   soinfo* si = find_containing_library(addr);
@@ -150,7 +150,7 @@
 }
 
 int dlclose(void* handle) {
-  ScopedPthreadMutexLocker locker(&gDlMutex);
+  ScopedPthreadMutexLocker locker(&g_dl_mutex);
   return do_dlclose(reinterpret_cast<soinfo*>(handle));
 }
 
@@ -187,7 +187,7 @@
 #  error Unsupported architecture. Only arm, arm64, mips, mips64, x86 and x86_64 are presently supported.
 #endif
 
-static ElfW(Sym) gLibDlSymtab[] = {
+static ElfW(Sym) g_libdl_symtab[] = {
   // Total length of libdl_info.strtab, including trailing 0.
   // This is actually the STH_UNDEF entry. Technically, it's
   // supposed to have st_name == 0, but instead, it points to an index
@@ -209,20 +209,20 @@
 
 // Fake out a hash table with a single bucket.
 //
-// A search of the hash table will look through gLibDlSymtab starting with index 1, then
-// use gLibDlChains to find the next index to look at. gLibDlChains should be set up to
-// walk through every element in gLibDlSymtab, and then end with 0 (sentinel value).
+// A search of the hash table will look through g_libdl_symtab starting with index 1, then
+// use g_libdl_chains to find the next index to look at. g_libdl_chains should be set up to
+// walk through every element in g_libdl_symtab, and then end with 0 (sentinel value).
 //
-// That is, gLibDlChains should look like { 0, 2, 3, ... N, 0 } where N is the number
-// of actual symbols, or nelems(gLibDlSymtab)-1 (since the first element of gLibDlSymtab is not
+// That is, g_libdl_chains should look like { 0, 2, 3, ... N, 0 } where N is the number
+// of actual symbols, or nelems(g_libdl_symtab)-1 (since the first element of g_libdl_symtab is not
 // a real symbol). (See soinfo_elf_lookup().)
 //
 // Note that adding any new symbols here requires stubbing them out in libdl.
-static unsigned gLibDlBuckets[1] = { 1 };
+static unsigned g_libdl_buckets[1] = { 1 };
 #if defined(__arm__)
-static unsigned gLibDlChains[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0 };
+static unsigned g_libdl_chains[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0 };
 #else
-static unsigned gLibDlChains[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
+static unsigned g_libdl_chains[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
 #endif
 
 // This is used by the dynamic linker. Every process gets these symbols for free.
@@ -250,12 +250,12 @@
     .flags = FLAG_LINKED,
 
     .strtab = ANDROID_LIBDL_STRTAB,
-    .symtab = gLibDlSymtab,
+    .symtab = g_libdl_symtab,
 
-    .nbucket = sizeof(gLibDlBuckets)/sizeof(unsigned),
-    .nchain = sizeof(gLibDlChains)/sizeof(unsigned),
-    .bucket = gLibDlBuckets,
-    .chain = gLibDlChains,
+    .nbucket = sizeof(g_libdl_buckets)/sizeof(unsigned),
+    .nchain = sizeof(g_libdl_chains)/sizeof(unsigned),
+    .bucket = g_libdl_buckets,
+    .chain = g_libdl_chains,
 
 #if defined(USE_RELA)
     .plt_rela = 0,
diff --git a/linker/linker.cpp b/linker/linker.cpp
index df53a84..86204de 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -71,13 +71,13 @@
 // We can't use malloc(3) in the dynamic linker. We use a linked list of anonymous
 // maps, each a single page in size. The pages are broken up into as many struct soinfo
 // objects as will fit.
-static LinkerAllocator<soinfo> gSoInfoAllocator;
+static LinkerAllocator<soinfo> g_soinfo_allocator;
 
 static soinfo* solist = &libdl_info;
 static soinfo* sonext = &libdl_info;
 static soinfo* somain; /* main process, always the one after libdl_info */
 
-static const char* const gDefaultLdPaths[] = {
+static const char* const kDefaultLdPaths[] = {
 #if defined(__LP64__)
   "/vendor/lib64",
   "/system/lib64",
@@ -94,17 +94,17 @@
 #define LDPRELOAD_BUFSIZE (LDPRELOAD_MAX*64)
 #define LDPRELOAD_MAX 8
 
-static char gLdPathsBuffer[LDPATH_BUFSIZE];
-static const char* gLdPaths[LDPATH_MAX + 1];
+static char g_ld_library_paths_buffer[LDPATH_BUFSIZE];
+static const char* g_ld_library_paths[LDPATH_MAX + 1];
 
-static char gLdPreloadsBuffer[LDPRELOAD_BUFSIZE];
-static const char* gLdPreloadNames[LDPRELOAD_MAX + 1];
+static char g_ld_preloads_buffer[LDPRELOAD_BUFSIZE];
+static const char* g_ld_preload_names[LDPRELOAD_MAX + 1];
 
-static soinfo* gLdPreloads[LDPRELOAD_MAX + 1];
+static soinfo* g_ld_preloads[LDPRELOAD_MAX + 1];
 
-__LIBC_HIDDEN__ int gLdDebugVerbosity;
+__LIBC_HIDDEN__ int g_ld_debug_verbosity;
 
-__LIBC_HIDDEN__ abort_msg_t* gAbortMessage = NULL; // For debuggerd.
+__LIBC_HIDDEN__ abort_msg_t* g_abort_message = NULL; // For debuggerd.
 
 enum RelocationKind {
     kRelocAbsolute = 0,
@@ -179,11 +179,10 @@
  */
 extern "C" void __attribute__((noinline)) __attribute__((visibility("default"))) rtld_db_dlactivity();
 
+static pthread_mutex_t g__r_debug_mutex = PTHREAD_MUTEX_INITIALIZER;
 static r_debug _r_debug = {1, NULL, reinterpret_cast<uintptr_t>(&rtld_db_dlactivity), r_debug::RT_CONSISTENT, 0};
 static link_map* r_debug_tail = 0;
 
-static pthread_mutex_t gDebugMutex = PTHREAD_MUTEX_INITIALIZER;
-
 static void insert_soinfo_into_debug_map(soinfo* info) {
     // Copy the necessary fields into the debug structure.
     link_map* map = &(info->link_map_head);
@@ -229,7 +228,7 @@
         return;
     }
 
-    ScopedPthreadMutexLocker locker(&gDebugMutex);
+    ScopedPthreadMutexLocker locker(&g__r_debug_mutex);
 
     _r_debug.r_state = r_debug::RT_ADD;
     rtld_db_dlactivity();
@@ -246,7 +245,7 @@
         return;
     }
 
-    ScopedPthreadMutexLocker locker(&gDebugMutex);
+    ScopedPthreadMutexLocker locker(&g__r_debug_mutex);
 
     _r_debug.r_state = r_debug::RT_DELETE;
     rtld_db_dlactivity();
@@ -270,7 +269,7 @@
     return NULL;
   }
 
-  soinfo* si = gSoInfoAllocator.alloc();
+  soinfo* si = g_soinfo_allocator.alloc();
 
   // Initialize the new element.
   memset(si, 0, sizeof(soinfo));
@@ -310,7 +309,7 @@
         sonext = prev;
     }
 
-    gSoInfoAllocator.free(si);
+    g_soinfo_allocator.free(si);
 }
 
 
@@ -340,14 +339,14 @@
 }
 
 static void parse_LD_LIBRARY_PATH(const char* path) {
-  parse_path(path, ":", gLdPaths,
-             gLdPathsBuffer, sizeof(gLdPathsBuffer), LDPATH_MAX);
+  parse_path(path, ":", g_ld_library_paths,
+             g_ld_library_paths_buffer, sizeof(g_ld_library_paths_buffer), LDPATH_MAX);
 }
 
 static void parse_LD_PRELOAD(const char* path) {
   // We have historically supported ':' as well as ' ' in LD_PRELOAD.
-  parse_path(path, " :", gLdPreloadNames,
-             gLdPreloadsBuffer, sizeof(gLdPreloadsBuffer), LDPRELOAD_MAX);
+  parse_path(path, " :", g_ld_preload_names,
+             g_ld_preloads_buffer, sizeof(g_ld_preloads_buffer), LDPRELOAD_MAX);
 }
 
 #if defined(__arm__)
@@ -505,10 +504,10 @@
     }
 
     /* Next, look for it in the preloads list */
-    for (int i = 0; gLdPreloads[i] != NULL; i++) {
-        s = soinfo_elf_lookup(gLdPreloads[i], elf_hash, name);
+    for (int i = 0; g_ld_preloads[i] != NULL; i++) {
+        s = soinfo_elf_lookup(g_ld_preloads[i], elf_hash, name);
         if (s != NULL) {
-            *lsi = gLdPreloads[i];
+            *lsi = g_ld_preloads[i];
             goto done;
         }
     }
@@ -637,9 +636,9 @@
   }
 
   // Otherwise we try LD_LIBRARY_PATH first, and fall back to the built-in well known paths.
-  int fd = open_library_on_path(name, gLdPaths);
+  int fd = open_library_on_path(name, g_ld_library_paths);
   if (fd == -1) {
-    fd = open_library_on_path(name, gDefaultLdPaths);
+    fd = open_library_on_path(name, kDefaultLdPaths);
   }
   return fd;
 }
@@ -756,7 +755,7 @@
 }
 
 void do_android_get_LD_LIBRARY_PATH(char* buffer, size_t buffer_size) {
-  snprintf(buffer, buffer_size, "%s:%s", gDefaultLdPaths[0], gDefaultLdPaths[1]);
+  snprintf(buffer, buffer_size, "%s:%s", kDefaultLdPaths[0], kDefaultLdPaths[1]);
 }
 
 void do_android_update_LD_LIBRARY_PATH(const char* ld_library_path) {
@@ -774,19 +773,19 @@
     DL_ERR("invalid extended flags to android_dlopen_ext: %x", extinfo->flags);
     return NULL;
   }
-  gSoInfoAllocator.protect_all(PROT_READ | PROT_WRITE);
+  g_soinfo_allocator.protect_all(PROT_READ | PROT_WRITE);
   soinfo* si = find_library(name, extinfo);
   if (si != NULL) {
     si->CallConstructors();
   }
-  gSoInfoAllocator.protect_all(PROT_READ);
+  g_soinfo_allocator.protect_all(PROT_READ);
   return si;
 }
 
 int do_dlclose(soinfo* si) {
-  gSoInfoAllocator.protect_all(PROT_READ | PROT_WRITE);
+  g_soinfo_allocator.protect_all(PROT_READ | PROT_WRITE);
   int result = soinfo_unload(si);
-  gSoInfoAllocator.protect_all(PROT_READ);
+  g_soinfo_allocator.protect_all(PROT_READ);
   return result;
 }
 
@@ -1334,7 +1333,7 @@
 
   // The function may have called dlopen(3) or dlclose(3), so we need to ensure our data structures
   // are still writable. This happens with our debug malloc (see http://b/7941716).
-  gSoInfoAllocator.protect_all(PROT_READ | PROT_WRITE);
+  g_soinfo_allocator.protect_all(PROT_READ | PROT_WRITE);
 }
 
 void soinfo::CallPreInitConstructors() {
@@ -1688,16 +1687,16 @@
 
     // If this is the main executable, then load all of the libraries from LD_PRELOAD now.
     if (si->flags & FLAG_EXE) {
-        memset(gLdPreloads, 0, sizeof(gLdPreloads));
+        memset(g_ld_preloads, 0, sizeof(g_ld_preloads));
         size_t preload_count = 0;
-        for (size_t i = 0; gLdPreloadNames[i] != NULL; i++) {
-            soinfo* lsi = find_library(gLdPreloadNames[i], NULL);
+        for (size_t i = 0; g_ld_preload_names[i] != NULL; i++) {
+            soinfo* lsi = find_library(g_ld_preload_names[i], NULL);
             if (lsi != NULL) {
-                gLdPreloads[preload_count++] = lsi;
+                g_ld_preloads[preload_count++] = lsi;
             } else {
                 // As with glibc, failure to load an LD_PRELOAD library is just a warning.
                 DL_WARN("could not load library \"%s\" from LD_PRELOAD for \"%s\"; caused by %s",
-                        gLdPreloadNames[i], si->name, linker_get_error_buffer());
+                        g_ld_preload_names[i], si->name, linker_get_error_buffer());
             }
         }
     }
@@ -1873,7 +1872,7 @@
     // Get a few environment variables.
     const char* LD_DEBUG = linker_env_get("LD_DEBUG");
     if (LD_DEBUG != NULL) {
-      gLdDebugVerbosity = atoi(LD_DEBUG);
+      g_ld_debug_verbosity = atoi(LD_DEBUG);
     }
 
     // Normally, these are cleaned by linker_env_init, but the test
@@ -1888,7 +1887,7 @@
     // Linker does not call constructors for its own
     // global variables so we need to initialize
     // the allocator explicitly.
-    gSoInfoAllocator.init();
+    g_soinfo_allocator.init();
 
     INFO("[ android linker & debugger ]");
 
@@ -1982,8 +1981,8 @@
 
     si->CallPreInitConstructors();
 
-    for (size_t i = 0; gLdPreloads[i] != NULL; ++i) {
-        gLdPreloads[i]->CallConstructors();
+    for (size_t i = 0; g_ld_preloads[i] != NULL; ++i) {
+        g_ld_preloads[i]->CallConstructors();
     }
 
     /* After the link_image, the si->load_bias is initialized.
@@ -2104,10 +2103,10 @@
 
   // We have successfully fixed our own relocations. It's safe to run
   // the main part of the linker now.
-  args.abort_message_ptr = &gAbortMessage;
+  args.abort_message_ptr = &g_abort_message;
   ElfW(Addr) start_address = __linker_init_post_relocation(args, linker_addr);
 
-  gSoInfoAllocator.protect_all(PROT_READ);
+  g_soinfo_allocator.protect_all(PROT_READ);
 
   // Return the address that the calling assembly stub should jump to.
   return start_address;
diff --git a/linker/linker.h b/linker/linker.h
index 93ab51d..645498a 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -203,7 +203,7 @@
 ElfW(Sym)* dlsym_handle_lookup(soinfo* si, const char* name);
 
 void debuggerd_init();
-extern "C" abort_msg_t* gAbortMessage;
+extern "C" abort_msg_t* g_abort_message;
 extern "C" void notify_gdb_of_libraries();
 
 char* linker_get_error_buffer();
diff --git a/linker/linker_debug.h b/linker/linker_debug.h
index 7a5821a..3faa38e 100644
--- a/linker/linker_debug.h
+++ b/linker/linker_debug.h
@@ -55,17 +55,17 @@
 
 #include "private/libc_logging.h"
 
-__LIBC_HIDDEN__ extern int gLdDebugVerbosity;
+__LIBC_HIDDEN__ extern int g_ld_debug_verbosity;
 
 #if LINKER_DEBUG_TO_LOG
 #define _PRINTVF(v, x...) \
     do { \
-      if (gLdDebugVerbosity > (v)) __libc_format_log(5-(v), "linker", x); \
+      if (g_ld_debug_verbosity > (v)) __libc_format_log(5-(v), "linker", x); \
     } while (0)
 #else /* !LINKER_DEBUG_TO_LOG */
 #define _PRINTVF(v, x...) \
     do { \
-      if (gLdDebugVerbosity > (v)) { __libc_format_fd(1, x); write(1, "\n", 1); } \
+      if (g_ld_debug_verbosity > (v)) { __libc_format_fd(1, x); write(1, "\n", 1); } \
     } while (0)
 #endif /* !LINKER_DEBUG_TO_LOG */
 
diff --git a/tests/arpa_inet_test.cpp b/tests/arpa_inet_test.cpp
index cee9f36..5e53337 100644
--- a/tests/arpa_inet_test.cpp
+++ b/tests/arpa_inet_test.cpp
@@ -59,3 +59,23 @@
   char s[INET_ADDRSTRLEN];
   ASSERT_STREQ("127.0.0.1", inet_ntop(AF_INET, &ss, s, INET_ADDRSTRLEN));
 }
+
+TEST(arpa_inet, inet_ntop_overflow) {
+  // OpenBSD's inet_ntop had a bug where passing a 'size' larger than INET_ADDRSTRLEN
+  // for AF_INET or INET6_ADDRSTRLEN for AF_INET6 would cause inet_ntop to overflow an
+  // internal buffer.
+
+  sockaddr_storage ss4;
+  ASSERT_EQ(1, inet_pton(AF_INET, "127.0.0.1", &ss4));
+
+  sockaddr_storage ss6;
+  ASSERT_EQ(1, inet_pton(AF_INET6, "::1", &ss6));
+
+  char s4[INET_ADDRSTRLEN];
+  char s6[INET6_ADDRSTRLEN];
+  ASSERT_STREQ("127.0.0.1", inet_ntop(AF_INET, &ss4, s4, INET_ADDRSTRLEN));
+  ASSERT_STREQ("127.0.0.1", inet_ntop(AF_INET, &ss4, s4, 2*INET_ADDRSTRLEN));
+  ASSERT_STREQ("::1", inet_ntop(AF_INET6, &ss6, s6, INET_ADDRSTRLEN));
+  ASSERT_STREQ("::1", inet_ntop(AF_INET6, &ss6, s6, INET6_ADDRSTRLEN));
+  ASSERT_STREQ("::1", inet_ntop(AF_INET6, &ss6, s6, 2*INET6_ADDRSTRLEN));
+}
diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp
index b31d7e4..3b3c0f6 100644
--- a/tests/dlfcn_test.cpp
+++ b/tests/dlfcn_test.cpp
@@ -27,9 +27,9 @@
 #define ASSERT_SUBSTR(needle, haystack) \
     ASSERT_PRED_FORMAT2(::testing::IsSubstring, needle, haystack)
 
-static bool gCalled = false;
+static bool g_called = false;
 extern "C" void DlSymTestFunction() {
-  gCalled = true;
+  g_called = true;
 }
 
 TEST(dlfcn, dlsym_in_self) {
@@ -43,9 +43,9 @@
 
   void (*function)() = reinterpret_cast<void(*)()>(sym);
 
-  gCalled = false;
+  g_called = false;
   function();
-  ASSERT_TRUE(gCalled);
+  ASSERT_TRUE(g_called);
 
   ASSERT_EQ(0, dlclose(self));
 }
diff --git a/tests/pthread_test.cpp b/tests/pthread_test.cpp
index 6a5e4a6..fa66d21 100644
--- a/tests/pthread_test.cpp
+++ b/tests/pthread_test.cpp
@@ -560,27 +560,47 @@
   ASSERT_EQ(0, pthread_rwlock_destroy(&l));
 }
 
-static int gOnceFnCallCount = 0;
+static int g_once_fn_call_count = 0;
 static void OnceFn() {
-  ++gOnceFnCallCount;
+  ++g_once_fn_call_count;
 }
 
 TEST(pthread, pthread_once_smoke) {
   pthread_once_t once_control = PTHREAD_ONCE_INIT;
   ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
   ASSERT_EQ(0, pthread_once(&once_control, OnceFn));
-  ASSERT_EQ(1, gOnceFnCallCount);
+  ASSERT_EQ(1, g_once_fn_call_count);
 }
 
-static int gAtForkPrepareCalls = 0;
-static void AtForkPrepare1() { gAtForkPrepareCalls = (gAtForkPrepareCalls << 4) | 1; }
-static void AtForkPrepare2() { gAtForkPrepareCalls = (gAtForkPrepareCalls << 4) | 2; }
-static int gAtForkParentCalls = 0;
-static void AtForkParent1() { gAtForkParentCalls = (gAtForkParentCalls << 4) | 1; }
-static void AtForkParent2() { gAtForkParentCalls = (gAtForkParentCalls << 4) | 2; }
-static int gAtForkChildCalls = 0;
-static void AtForkChild1() { gAtForkChildCalls = (gAtForkChildCalls << 4) | 1; }
-static void AtForkChild2() { gAtForkChildCalls = (gAtForkChildCalls << 4) | 2; }
+static std::string pthread_once_1934122_result = "";
+
+static void Routine2() {
+  pthread_once_1934122_result += "2";
+}
+
+static void Routine1() {
+  pthread_once_t once_control_2 = PTHREAD_ONCE_INIT;
+  pthread_once_1934122_result += "1";
+  pthread_once(&once_control_2, &Routine2);
+}
+
+TEST(pthread, pthread_once_1934122) {
+  // Very old versions of Android couldn't call pthread_once from a
+  // pthread_once init routine. http://b/1934122.
+  pthread_once_t once_control_1 = PTHREAD_ONCE_INIT;
+  ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1));
+  ASSERT_EQ("12", pthread_once_1934122_result);
+}
+
+static int g_atfork_prepare_calls = 0;
+static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls << 4) | 1; }
+static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls << 4) | 2; }
+static int g_atfork_parent_calls = 0;
+static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls << 4) | 1; }
+static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls << 4) | 2; }
+static int g_atfork_child_calls = 0;
+static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls << 4) | 1; }
+static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls << 4) | 2; }
 
 TEST(pthread, pthread_atfork) {
   ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1));
@@ -591,13 +611,13 @@
 
   // Child and parent calls are made in the order they were registered.
   if (pid == 0) {
-    ASSERT_EQ(0x12, gAtForkChildCalls);
+    ASSERT_EQ(0x12, g_atfork_child_calls);
     _exit(0);
   }
-  ASSERT_EQ(0x12, gAtForkParentCalls);
+  ASSERT_EQ(0x12, g_atfork_parent_calls);
 
   // Prepare calls are made in the reverse order.
-  ASSERT_EQ(0x21, gAtForkPrepareCalls);
+  ASSERT_EQ(0x21, g_atfork_prepare_calls);
 }
 
 TEST(pthread, pthread_attr_getscope) {
diff --git a/tests/signal_test.cpp b/tests/signal_test.cpp
index af98964..89b8088 100644
--- a/tests/signal_test.cpp
+++ b/tests/signal_test.cpp
@@ -146,10 +146,10 @@
   ASSERT_EQ(SIGALRM, received_signal);
 }
 
-static int gSigSuspendTestHelperCallCount = 0;
+static int g_sigsuspend_test_helper_call_count = 0;
 
 static void SigSuspendTestHelper(int) {
-  ++gSigSuspendTestHelperCallCount;
+  ++g_sigsuspend_test_helper_call_count;
 }
 
 TEST(signal, sigsuspend_sigpending) {
@@ -172,7 +172,7 @@
 
   // Raise SIGALRM and check our signal handler wasn't called.
   raise(SIGALRM);
-  ASSERT_EQ(0, gSigSuspendTestHelperCallCount);
+  ASSERT_EQ(0, g_sigsuspend_test_helper_call_count);
 
   // We should now have a pending SIGALRM but nothing else.
   sigemptyset(&pending);
@@ -188,7 +188,7 @@
   ASSERT_EQ(-1, sigsuspend(&not_SIGALRM));
   ASSERT_EQ(EINTR, errno);
   // ...and check that we now receive our pending SIGALRM.
-  ASSERT_EQ(1, gSigSuspendTestHelperCallCount);
+  ASSERT_EQ(1, g_sigsuspend_test_helper_call_count);
 
   // Restore the original set.
   ASSERT_EQ(0, sigprocmask(SIG_SETMASK, &original_set, NULL));
diff --git a/tests/stdio_test.cpp b/tests/stdio_test.cpp
index 655ad3f..2a0549a 100644
--- a/tests/stdio_test.cpp
+++ b/tests/stdio_test.cpp
@@ -400,6 +400,13 @@
   EXPECT_STREQ("1.500000e+00", buf);
 }
 
+TEST(stdio, snprintf_negative_zero_5084292) {
+  char buf[BUFSIZ];
+
+  snprintf(buf, sizeof(buf), "%f", -0.0);
+  EXPECT_STREQ("-0.000000", buf);
+}
+
 TEST(stdio, popen) {
   FILE* fp = popen("cat /proc/version", "r");
   ASSERT_TRUE(fp != NULL);
diff --git a/tests/unistd_test.cpp b/tests/unistd_test.cpp
index ff05039..3f31861 100644
--- a/tests/unistd_test.cpp
+++ b/tests/unistd_test.cpp
@@ -114,18 +114,18 @@
   ASSERT_EQ(123, sb.st_size);
 }
 
-static bool gPauseTestFlag = false;
+static bool g_pause_test_flag = false;
 static void PauseTestSignalHandler(int) {
-  gPauseTestFlag = true;
+  g_pause_test_flag = true;
 }
 
 TEST(unistd, pause) {
   ScopedSignalHandler handler(SIGALRM, PauseTestSignalHandler);
 
   alarm(1);
-  ASSERT_FALSE(gPauseTestFlag);
+  ASSERT_FALSE(g_pause_test_flag);
   ASSERT_EQ(-1, pause());
-  ASSERT_TRUE(gPauseTestFlag);
+  ASSERT_TRUE(g_pause_test_flag);
 }
 
 TEST(unistd, read) {