Merge "Support non-zero p_vaddr in first PT_LOAD segment"
diff --git a/libc/Android.mk b/libc/Android.mk
index 95ff1ec..596a856 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -205,6 +205,12 @@
 	string/strtok.c \
 	string/strtotimeval.c \
 	string/strxfrm.c \
+	string/__memcpy_chk.c \
+	string/__memmove_chk.c \
+	string/__strcat_chk.c \
+	string/__strcpy_chk.c \
+	string/__strncat_chk.c \
+	string/__strncpy_chk.c \
 	wchar/wcpcpy.c \
 	wchar/wcpncpy.c \
 	wchar/wcscasecmp.c \
@@ -440,18 +446,19 @@
 # Define some common cflags
 # ========================================================
 libc_common_cflags := \
-		-DWITH_ERRLIST			\
-		-DANDROID_CHANGES		\
-		-DUSE_LOCKS 			\
-		-DREALLOC_ZERO_BYTES_FREES 	\
-		-D_LIBC=1 			\
-		-DSOFTFLOAT                     \
-		-DFLOATING_POINT		\
-		-DINET6 \
-		-I$(LOCAL_PATH)/private \
-		-DUSE_DL_PREFIX \
-		-DPOSIX_MISTAKE \
-                -DLOG_ON_HEAP_ERROR \
+    -DWITH_ERRLIST \
+    -DANDROID_CHANGES \
+    -DUSE_LOCKS \
+    -DREALLOC_ZERO_BYTES_FREES \
+    -D_LIBC=1 \
+    -DSOFTFLOAT \
+    -DFLOATING_POINT \
+    -DINET6 \
+    -I$(LOCAL_PATH)/private \
+    -DUSE_DL_PREFIX \
+    -DPOSIX_MISTAKE \
+    -DLOG_ON_HEAP_ERROR \
+    -std=gnu99
 
 # these macro definitions are required to implement the
 # 'timezone' and 'daylight' global variables, as well as
@@ -515,8 +522,8 @@
     libc_common_cflags += -DANDROID_SMP=0
 endif
 
-# Needed to access private/__dso_handle.S from
-# crtbegin_xxx.S and crtend_xxx.S
+# Needed to access private/__dso_handle.h from
+# crtbegin_xxx.c and crtend_xxx.c
 #
 libc_crt_target_cflags += -I$(LOCAL_PATH)/private
 
@@ -531,9 +538,8 @@
 		$(LOCAL_PATH)/string  \
 		$(LOCAL_PATH)/stdio
 
-# Needed to access private/__dso_handle.S from
+# Needed to access private/__dso_handle.h from
 # crtbegin_xxx.S and crtend_xxx.S
-# and machine/asm.h
 #
 libc_crt_target_cflags += -I$(LOCAL_PATH)/private -I$(LOCAL_PATH)/arch-$(TARGET_ARCH)/include
 
@@ -555,12 +561,16 @@
 #
 
 libc_crt_target_so_cflags := $(libc_crt_target_cflags)
+libc_crt_target_crtstart_file := $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin.c
+libc_crt_target_crtstart_so_file := $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin_so.c
 ifeq ($(TARGET_ARCH),x86)
     # This flag must be added for x86 targets, but not for ARM
     libc_crt_target_so_cflags += -fPIC
+    libc_crt_target_crtstart_file := $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin.S
+    libc_crt_target_crtstart_so_file := $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin_so.S
 endif
 GEN := $(TARGET_OUT_INTERMEDIATE_LIBRARIES)/crtbegin_so.o
-$(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin_so.S
+$(GEN): $(libc_crt_target_crtstart_so_file)
 	@mkdir -p $(dir $@)
 	$(TARGET_CC) $(libc_crt_target_so_cflags) -o $@ -c $<
 ALL_GENERATED_SOURCES += $(GEN)
@@ -574,13 +584,13 @@
 
 
 GEN := $(TARGET_OUT_INTERMEDIATE_LIBRARIES)/crtbegin_static.o
-$(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin.S
+$(GEN): $(libc_crt_target_crtstart_file)
 	@mkdir -p $(dir $@)
 	$(TARGET_CC) $(libc_crt_target_cflags) -o $@ -c $<
 ALL_GENERATED_SOURCES += $(GEN)
 
 GEN := $(TARGET_OUT_INTERMEDIATE_LIBRARIES)/crtbegin_dynamic.o
-$(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin.S
+$(GEN): $(libc_crt_target_crtstart_file)
 	@mkdir -p $(dir $@)
 	$(TARGET_CC) $(libc_crt_target_cflags) -o $@ -c $<
 ALL_GENERATED_SOURCES += $(GEN)
diff --git a/libc/arch-arm/bionic/atexit.S b/libc/arch-arm/bionic/atexit.h
similarity index 61%
copy from libc/arch-arm/bionic/atexit.S
copy to libc/arch-arm/bionic/atexit.h
index beea685..d567bfc 100644
--- a/libc/arch-arm/bionic/atexit.S
+++ b/libc/arch-arm/bionic/atexit.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,37 +26,28 @@
  * SUCH DAMAGE.
  */
 
+/* CRT_LEGACY_WORKAROUND should only be defined when building
+ * this file as part of the platform's C library.
+ *
+ * The C library already defines a function named 'atexit()'
+ * for backwards compatibility with older NDK-generated binaries.
+ *
+ * For newer ones, 'atexit' is actually embedded in the C
+ * runtime objects that are linked into the final ELF
+ * binary (shared library or executable), and will call
+ * __cxa_atexit() in order to un-register any atexit()
+ * handler when a library is unloaded.
+ *
+ * This function must be global *and* hidden. Only the
+ * code inside the same ELF binary should be able to access it.
+ */
+
 #ifndef CRT_LEGACY_WORKAROUND
-	.arch armv5te
-	.fpu softvfp
-	.eabi_attribute 20, 1
-	.eabi_attribute 21, 1
-	.eabi_attribute 23, 3
-	.eabi_attribute 24, 1
-	.eabi_attribute 25, 1
-	.eabi_attribute 26, 2
-	.eabi_attribute 30, 4
-	.eabi_attribute 18, 4
-	.hidden	atexit
-	.code	16
-	.thumb_func
-ENTRY(atexit)
-.LFB0:
-	.save	{r4, lr}
-	push	{r4, lr}
-.LCFI0:
-	ldr	r3, .L3
-	mov	r1, #0
-	@ sp needed for prologue
-.LPIC0:
-	add	r3, pc
-	ldr	r2, [r3]
-	bl	__cxa_atexit
-	pop	{r4, pc}
-.L4:
-	.align	2
-.L3:
-	.word	__dso_handle-(.LPIC0+4)
-.LFE0:
-END(atexit)
+extern void *__dso_handle;
+
+__attribute__ ((visibility ("hidden")))
+int atexit(void (*func)(void))
+{
+  return (__cxa_atexit((void (*)(void *))func, (void *)0, &__dso_handle));
+}
 #endif
diff --git a/libc/arch-arm/bionic/crtbegin.S b/libc/arch-arm/bionic/crtbegin.S
deleted file mode 100644
index 8843204..0000000
--- a/libc/arch-arm/bionic/crtbegin.S
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2008 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.
- */
-	.text
-	.align 4
-	.type _start,#function
-	.globl _start
-
-# this is the small startup code that is first run when
-# any executable that is linked with Bionic runs.
-#
-# it's purpose is to call __libc_init with appropriate
-# arguments, which are:
-#
-#    - the address of the raw data block setup by the Linux
-#      kernel ELF loader
-#
-#    - address of an "onexit" function, not used on any
-#      platform supported by Bionic
-#
-#    - address of the "main" function of the program.
-#
-#    - address of the constructor list
-#
-_start:	
-	mov	r0, sp
-	mov	r1, #0
-	ldr	r2, =main
-	adr	r3, 1f
-	ldr	r4, =__libc_init
-	blx	r4
-	mov	r0, #0
-	bx	r0
-
-1:  .long   __PREINIT_ARRAY__
-    .long   __INIT_ARRAY__
-    .long   __FINI_ARRAY__
-    .long   __CTOR_LIST__
-
-	.section .preinit_array, "aw"
-	.globl __PREINIT_ARRAY__
-__PREINIT_ARRAY__:
-	.long -1
-
-	.section .init_array, "aw"
-	.globl __INIT_ARRAY__
-__INIT_ARRAY__:
-	.long -1
-
-	.section .fini_array, "aw"
-	.globl __FINI_ARRAY__
-__FINI_ARRAY__:
-	.long -1
-
-	.section .ctors, "aw"
-	.globl __CTOR_LIST__
-__CTOR_LIST__:
-	.long -1
-
-#include "__dso_handle.S"
-#include "atexit.S"
diff --git a/libc/arch-arm/bionic/crtbegin.c b/libc/arch-arm/bionic/crtbegin.c
new file mode 100644
index 0000000..9dcd254
--- /dev/null
+++ b/libc/arch-arm/bionic/crtbegin.c
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2012 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.
+ */
+
+typedef struct
+{
+    void (**preinit_array)(void);
+    void (**init_array)(void);
+    void (**fini_array)(void);
+    void (**ctors_array)(void);
+} structors_array_t;
+
+extern int main(int argc, char **argv, char **env);
+
+extern void __libc_init(
+  unsigned int *elfdata,
+  void (*onexit)(void),
+  int (*slingshot)(int, char**, char**),
+  structors_array_t const * const structors
+);
+
+__attribute__ ((section (".preinit_array")))
+void (*__PREINIT_ARRAY__)(void) = (void (*)(void)) -1;
+
+__attribute__ ((section (".init_array")))
+void (*__INIT_ARRAY__)(void) = (void (*)(void)) -1;
+
+__attribute__ ((section (".fini_array")))
+void (*__FINI_ARRAY__)(void) = (void (*)(void)) -1;
+
+__attribute__ ((section (".ctors")))
+void (*__CTOR_LIST__)(void) = (void (*)(void)) -1;
+
+__attribute__((visbility("hidden")))
+void _start() {
+  structors_array_t array;
+  void *elfdata;
+
+  array.preinit_array = &__PREINIT_ARRAY__;
+  array.init_array =    &__INIT_ARRAY__;
+  array.fini_array =    &__FINI_ARRAY__;
+  array.ctors_array =   &__CTOR_LIST__;
+
+  elfdata = __builtin_frame_address(0) + sizeof(void *);
+  __libc_init(elfdata, (void *) 0, &main, &array);
+}
+
+#include "__dso_handle.h"
+#include "atexit.h"
diff --git a/libc/arch-arm/bionic/atexit.S b/libc/arch-arm/bionic/crtbegin_so.c
similarity index 69%
copy from libc/arch-arm/bionic/atexit.S
copy to libc/arch-arm/bionic/crtbegin_so.c
index beea685..57d19bf 100644
--- a/libc/arch-arm/bionic/atexit.S
+++ b/libc/arch-arm/bionic/crtbegin_so.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,37 +26,18 @@
  * SUCH DAMAGE.
  */
 
-#ifndef CRT_LEGACY_WORKAROUND
-	.arch armv5te
-	.fpu softvfp
-	.eabi_attribute 20, 1
-	.eabi_attribute 21, 1
-	.eabi_attribute 23, 3
-	.eabi_attribute 24, 1
-	.eabi_attribute 25, 1
-	.eabi_attribute 26, 2
-	.eabi_attribute 30, 4
-	.eabi_attribute 18, 4
-	.hidden	atexit
-	.code	16
-	.thumb_func
-ENTRY(atexit)
-.LFB0:
-	.save	{r4, lr}
-	push	{r4, lr}
-.LCFI0:
-	ldr	r3, .L3
-	mov	r1, #0
-	@ sp needed for prologue
-.LPIC0:
-	add	r3, pc
-	ldr	r2, [r3]
-	bl	__cxa_atexit
-	pop	{r4, pc}
-.L4:
-	.align	2
-.L3:
-	.word	__dso_handle-(.LPIC0+4)
-.LFE0:
-END(atexit)
+extern void __cxa_finalize(void *);
+extern void *__dso_handle;
+
+__attribute__((visbility("hidden")))
+void __on_dlclose() {
+  __cxa_finalize(&__dso_handle);
+}
+
+#ifdef CRT_LEGACY_WORKAROUND
+#include "__dso_handle.h"
+#else
+#include "__dso_handle_so.h"
 #endif
+
+#include "atexit.h"
diff --git a/libc/private/__dso_handle.S b/libc/arch-x86/bionic/__dso_handle.S
similarity index 100%
rename from libc/private/__dso_handle.S
rename to libc/arch-x86/bionic/__dso_handle.S
diff --git a/libc/private/__dso_handle_so.S b/libc/arch-x86/bionic/__dso_handle_so.S
similarity index 100%
rename from libc/private/__dso_handle_so.S
rename to libc/arch-x86/bionic/__dso_handle_so.S
diff --git a/libc/bionic/pthread-timers.c b/libc/bionic/pthread-timers.c
index ae04029..23d31df 100644
--- a/libc/bionic/pthread-timers.c
+++ b/libc/bionic/pthread-timers.c
@@ -9,7 +9,7 @@
  *    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 
+ *    the documentation and/or other materials provided with the
  *    distribution.
  *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
@@ -19,55 +19,56 @@
  * 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 
+ * 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 "pthread_internal.h"
-#include <linux/time.h>
-#include <string.h>
+
 #include <errno.h>
+#include <linux/time.h>
+#include <stdio.h>
+#include <string.h>
 
-/* This file implements the support required to implement SIGEV_THREAD posix 
- * timers. See the following pages for additionnal details:
- *
- * www.opengroup.org/onlinepubs/000095399/functions/timer_create.html
- * www.opengroup.org/onlinepubs/000095399/functions/timer_settime.html
- * www.opengroup.org/onlinepubs/000095399/functions/xsh_chap02_04.html#tag_02_04_01
- *
- * The Linux kernel doesn't support these, so we need to implement them in the
- * C library. We use a very basic scheme where each timer is associated to a
- * thread that will loop, waiting for timeouts or messages from the program
- * corresponding to calls to timer_settime() and timer_delete().
- *
- * Note also an important thing: Posix mandates that in the case of fork(),
- * the timers of the child process should be disarmed, but not deleted.
- * this is implemented by providing a fork() wrapper (see bionic/fork.c) which
- * stops all timers before the fork, and only re-start them in case of error
- * or in the parent process.
- *
- * the stop/start is implemented by the __timer_table_start_stop() function
- * below.
- */
-
-/* normal (i.e. non-SIGEV_THREAD) timer ids are created directly by the kernel
- * and are passed as is to/from the caller.
- *
- * on the other hand, a SIGEV_THREAD timer ID will have its TIMER_ID_WRAP_BIT
- * always set to 1. In this implementation, this is always bit 31, which is
- * guaranteed to never be used by kernel-provided timer ids
- *
- * (see code in <kernel>/lib/idr.c, used to manage IDs, to see why)
- */
+// Normal (i.e. non-SIGEV_THREAD) timers are created directly by the kernel
+// and are passed as is to/from the caller.
+//
+// This file also implements the support required for SIGEV_THREAD ("POSIX interval")
+// timers. See the following pages for additional details:
+//
+// www.opengroup.org/onlinepubs/000095399/functions/timer_create.html
+// www.opengroup.org/onlinepubs/000095399/functions/timer_settime.html
+// www.opengroup.org/onlinepubs/000095399/functions/xsh_chap02_04.html#tag_02_04_01
+//
+// The Linux kernel doesn't support these, so we need to implement them in the
+// C library. We use a very basic scheme where each timer is associated to a
+// thread that will loop, waiting for timeouts or messages from the program
+// corresponding to calls to timer_settime() and timer_delete().
+//
+// Note also an important thing: Posix mandates that in the case of fork(),
+// the timers of the child process should be disarmed, but not deleted.
+// this is implemented by providing a fork() wrapper (see bionic/fork.c) which
+// stops all timers before the fork, and only re-start them in case of error
+// or in the parent process.
+//
+// This stop/start is implemented by the __timer_table_start_stop() function
+// below.
+//
+// A SIGEV_THREAD timer ID will always have its TIMER_ID_WRAP_BIT
+// set to 1. In this implementation, this is always bit 31, which is
+// guaranteed to never be used by kernel-provided timer ids
+//
+// (See code in <kernel>/lib/idr.c, used to manage IDs, to see why.)
 
 #define  TIMER_ID_WRAP_BIT        0x80000000
 #define  TIMER_ID_WRAP(id)        ((timer_t)((id) |  TIMER_ID_WRAP_BIT))
 #define  TIMER_ID_UNWRAP(id)      ((timer_t)((id) & ~TIMER_ID_WRAP_BIT))
 #define  TIMER_ID_IS_WRAPPED(id)  (((id) & TIMER_ID_WRAP_BIT) != 0)
 
-/* this value is used internally to indicate a 'free' or 'zombie' 
+/* this value is used internally to indicate a 'free' or 'zombie'
  * thr_timer structure. Here, 'zombie' means that timer_delete()
  * has been called, but that the corresponding thread hasn't
  * exited yet.
@@ -171,25 +172,23 @@
 }
 
 
-static void
-thr_timer_table_start_stop( thr_timer_table_t*  t, int  stop )
-{
-    int  nn;
+static void thr_timer_table_start_stop(thr_timer_table_t* t, int stop) {
+  if (t == NULL) {
+    return;
+  }
 
-    pthread_mutex_lock(&t->lock);
-
-    for (nn = 0; nn < MAX_THREAD_TIMERS; nn++) {
-        thr_timer_t*  timer  = &t->timers[nn];
-
-        if (TIMER_ID_IS_VALID(timer->id)) {
-            /* tell the thread to start/stop */
-            pthread_mutex_lock(&timer->mutex);
-            timer->stopped = stop;
-            pthread_cond_signal( &timer->cond );
-            pthread_mutex_unlock(&timer->mutex);
-        }
+  pthread_mutex_lock(&t->lock);
+  for (int nn = 0; nn < MAX_THREAD_TIMERS; ++nn) {
+    thr_timer_t*  timer  = &t->timers[nn];
+    if (TIMER_ID_IS_VALID(timer->id)) {
+      // Tell the thread to start/stop.
+      pthread_mutex_lock(&timer->mutex);
+      timer->stopped = stop;
+      pthread_cond_signal( &timer->cond );
+      pthread_mutex_unlock(&timer->mutex);
     }
-    pthread_mutex_unlock(&t->lock);
+  }
+  pthread_mutex_unlock(&t->lock);
 }
 
 
@@ -234,23 +233,19 @@
  * pretty infrequent
  */
 
-static pthread_once_t      __timer_table_once = PTHREAD_ONCE_INIT;
-static thr_timer_table_t*  __timer_table;
+static pthread_once_t __timer_table_once = PTHREAD_ONCE_INIT;
+static thr_timer_table_t* __timer_table;
 
-static void
-__timer_table_init( void )
-{
-    __timer_table = calloc(1,sizeof(*__timer_table));
-
-    if (__timer_table != NULL)
-        thr_timer_table_init( __timer_table );
+static void __timer_table_init(void) {
+  __timer_table = calloc(1, sizeof(*__timer_table));
+  if (__timer_table != NULL) {
+    thr_timer_table_init(__timer_table);
+  }
 }
 
-static thr_timer_table_t*
-__timer_table_get(void)
-{
-    pthread_once( &__timer_table_once, __timer_table_init );
-    return __timer_table;
+static thr_timer_table_t* __timer_table_get(void) {
+  pthread_once(&__timer_table_once, __timer_table_init);
+  return __timer_table;
 }
 
 /** POSIX THREAD TIMERS CLEANUP ON FORK
@@ -260,13 +255,9 @@
  ** requirements: the timers of fork child processes must be
  ** disarmed but not deleted.
  **/
-__LIBC_HIDDEN__ void
-__timer_table_start_stop( int  stop )
-{
-    if (__timer_table != NULL) {
-        thr_timer_table_t*  table = __timer_table_get();
-        thr_timer_table_start_stop(table, stop);
-    }
+__LIBC_HIDDEN__ void __timer_table_start_stop(int stop) {
+  // We access __timer_table directly so we don't create it if it doesn't yet exist.
+  thr_timer_table_start_stop(__timer_table, stop);
 }
 
 static thr_timer_t*
@@ -293,85 +284,76 @@
 
 /** POSIX TIMERS APIs */
 
-/* first, declare the syscall stubs */
-extern int __timer_create( clockid_t, struct sigevent*, timer_t* );
-extern int __timer_delete( timer_t );
-extern int __timer_gettime( timer_t, struct itimerspec* );
-extern int __timer_settime( timer_t, int, const struct itimerspec*, struct itimerspec* );
+extern int __timer_create(clockid_t, struct sigevent*, timer_t*);
+extern int __timer_delete(timer_t);
+extern int __timer_gettime(timer_t, struct itimerspec*);
+extern int __timer_settime(timer_t, int, const struct itimerspec*, struct itimerspec*);
 extern int __timer_getoverrun(timer_t);
 
-static void*  timer_thread_start( void* );
+static void* timer_thread_start(void*);
 
-/* then the wrappers themselves */
-int
-timer_create( clockid_t  clockid, struct sigevent*  evp, timer_t  *ptimerid)
-{
-    /* if not a SIGEV_THREAD timer, direct creation by the kernel */
-    if (__likely(evp == NULL || evp->sigev_notify != SIGEV_THREAD))
-        return __timer_create( clockid, evp, ptimerid );
+int timer_create(clockid_t clock_id, struct sigevent* evp, timer_t* timer_id) {
+  // If not a SIGEV_THREAD timer, the kernel can handle it without our help.
+  if (__likely(evp == NULL || evp->sigev_notify != SIGEV_THREAD)) {
+    return __timer_create(clock_id, evp, timer_id);
+  }
 
-    // check arguments
-    if (evp->sigev_notify_function == NULL) {
-        errno = EINVAL;
-        return -1;
-    }
+  // Check arguments.
+  if (evp->sigev_notify_function == NULL) {
+    errno = EINVAL;
+    return -1;
+  }
 
-    {
-        struct timespec  dummy;
+  // Check that the clock id is supported by the kernel.
+  struct timespec dummy;
+  if (clock_gettime(clock_id, &dummy) < 0 && errno == EINVAL) {
+    return -1;
+  }
 
-        /* check that the clock id is supported by the kernel */
-        if (clock_gettime( clockid, &dummy ) < 0 && errno == EINVAL )
-            return -1;
-    }
+  // Create a new timer and its thread.
+  // TODO: use a single global thread for all timers.
+  thr_timer_table_t* table = __timer_table_get();
+  thr_timer_t* timer = thr_timer_table_alloc(table);
+  if (timer == NULL) {
+    errno = ENOMEM;
+    return -1;
+  }
 
-    /* create a new timer and its thread */
-    {
-        thr_timer_table_t*  table = __timer_table_get();
-        thr_timer_t*        timer = thr_timer_table_alloc( table );
-        struct sigevent     evp0;
+  // Copy the thread attributes.
+  if (evp->sigev_notify_attributes == NULL) {
+    pthread_attr_init(&timer->attributes);
+  } else {
+    timer->attributes = ((pthread_attr_t*) evp->sigev_notify_attributes)[0];
+  }
 
-        if (timer == NULL) {
-            errno = ENOMEM;
-            return -1;
-        }
+  // Posix says that the default is PTHREAD_CREATE_DETACHED and
+  // that PTHREAD_CREATE_JOINABLE has undefined behavior.
+  // So simply always use DETACHED :-)
+  pthread_attr_setdetachstate(&timer->attributes, PTHREAD_CREATE_DETACHED);
 
-        /* copy the thread attributes */
-        if (evp->sigev_notify_attributes == NULL) {
-            pthread_attr_init(&timer->attributes);
-        }
-        else {
-            timer->attributes = ((pthread_attr_t*)evp->sigev_notify_attributes)[0];
-        }
+  timer->callback = evp->sigev_notify_function;
+  timer->value = evp->sigev_value;
+  timer->clock = clock_id;
 
-        /* Posix says that the default is PTHREAD_CREATE_DETACHED and
-         * that PTHREAD_CREATE_JOINABLE has undefined behaviour.
-         * So simply always use DETACHED :-)
-         */
-        pthread_attr_setdetachstate(&timer->attributes, PTHREAD_CREATE_DETACHED);
+  pthread_mutex_init(&timer->mutex, NULL);
+  pthread_cond_init(&timer->cond, NULL);
 
-        timer->callback = evp->sigev_notify_function;
-        timer->value    = evp->sigev_value;
-        timer->clock    = clockid;
+  timer->done = 0;
+  timer->stopped = 0;
+  timer->expires.tv_sec = timer->expires.tv_nsec = 0;
+  timer->period.tv_sec = timer->period.tv_nsec  = 0;
+  timer->overruns = 0;
 
-        pthread_mutex_init( &timer->mutex, NULL );
-        pthread_cond_init( &timer->cond, NULL );
+  // Create the thread.
+  int rc = pthread_create(&timer->thread, &timer->attributes, timer_thread_start, timer);
+  if (rc != 0) {
+    thr_timer_table_free(table, timer);
+    errno = rc;
+    return -1;
+  }
 
-        timer->done           = 0;
-        timer->stopped        = 0;
-        timer->expires.tv_sec = timer->expires.tv_nsec = 0;
-        timer->period.tv_sec  = timer->period.tv_nsec  = 0;
-        timer->overruns       = 0;
-
-        /* create the thread */
-        if (pthread_create( &timer->thread, &timer->attributes, timer_thread_start, timer ) < 0) {
-            thr_timer_table_free( __timer_table, timer );
-            errno = ENOMEM;
-            return -1;
-        }
-
-        *ptimerid = timer->id;
-        return 0;
-    }
+  *timer_id = timer->id;
+  return 0;
 }
 
 
@@ -414,7 +396,7 @@
     struct timespec  diff;
 
     diff = timer->expires;
-    if (!timespec_is_zero(&diff)) 
+    if (!timespec_is_zero(&diff))
     {
         struct timespec  now;
 
@@ -532,108 +514,93 @@
 }
 
 
-static void*
-timer_thread_start( void*  _arg )
-{
-    thr_timer_t*  timer = _arg;
+static void* timer_thread_start(void* arg) {
+  thr_timer_t* timer = arg;
 
-    thr_timer_lock( timer );
+  thr_timer_lock(timer);
 
-    /* we loop until timer->done is set in timer_delete() */
-    while (!timer->done) 
-    {
-        struct timespec   expires = timer->expires;
-        struct timespec   period  = timer->period;
-        struct timespec   now;
+  // Give this thread a meaningful name.
+  char name[32];
+  snprintf(name, sizeof(name), "POSIX interval timer 0x%08x", timer->id);
+  pthread_setname_np(pthread_self(), name);
 
-        /* if the timer is stopped or disarmed, wait indefinitely
-         * for a state change from timer_settime/_delete/_start_stop
-         */
-        if ( timer->stopped || timespec_is_zero(&expires) )
-        {
-            pthread_cond_wait( &timer->cond, &timer->mutex );
-            continue;
-        }
+  // We loop until timer->done is set in timer_delete().
+  while (!timer->done) {
+    struct timespec expires = timer->expires;
+    struct timespec period = timer->period;
 
-        /* otherwise, we need to do a timed wait until either a
-        * state change of the timer expiration time.
-        */
-        clock_gettime(timer->clock, &now);
-
-        if (timespec_cmp( &expires, &now ) > 0)
-        {
-            /* cool, there was no overrun, so compute the
-             * relative timeout as 'expires - now', then wait
-             */
-            int              ret;
-            struct timespec  diff = expires;
-            timespec_sub( &diff, &now );
-
-            ret = __pthread_cond_timedwait_relative(
-                        &timer->cond, &timer->mutex, &diff);
-
-            /* if we didn't timeout, it means that a state change
-                * occured, so reloop to take care of it.
-                */
-            if (ret != ETIMEDOUT)
-                continue;
-        }
-        else
-        {
-            /* overrun was detected before we could wait ! */
-            if (!timespec_is_zero( &period ) )
-            {
-                /* for periodic timers, compute total overrun count */
-                do {
-                    timespec_add( &expires, &period );
-                    if (timer->overruns < DELAYTIMER_MAX)
-                        timer->overruns += 1;
-                } while ( timespec_cmp( &expires, &now ) < 0 );
-
-                /* backtrack the last one, because we're going to
-                 * add the same value just a bit later */
-                timespec_sub( &expires, &period );
-            }
-            else
-            {
-                /* for non-periodic timer, things are simple */
-                timer->overruns = 1;
-            }
-        }
-
-        /* if we get there, a timeout was detected.
-         * first reload/disarm the timer has needed
-         */
-        if ( !timespec_is_zero(&period) ) {
-            timespec_add( &expires, &period );
-        } else {
-            timespec_zero( &expires );
-        }
-        timer->expires = expires;
-
-        /* now call the timer callback function. release the
-         * lock to allow the function to modify the timer setting
-         * or call timer_getoverrun().
-         *
-         * NOTE: at this point we trust the callback not to be a
-         *       total moron and pthread_kill() the timer thread
-         */
-        thr_timer_unlock(timer);
-        timer->callback( timer->value );
-        thr_timer_lock(timer);
-
-        /* now clear the overruns counter. it only makes sense
-         * within the callback */
-        timer->overruns = 0;
+    // If the timer is stopped or disarmed, wait indefinitely
+    // for a state change from timer_settime/_delete/_start_stop.
+    if (timer->stopped || timespec_is_zero(&expires)) {
+      pthread_cond_wait(&timer->cond, &timer->mutex);
+      continue;
     }
 
-    thr_timer_unlock( timer );
+    // Otherwise, we need to do a timed wait until either a
+    // state change of the timer expiration time.
+    struct timespec now;
+    clock_gettime(timer->clock, &now);
 
-    /* free the timer object now. there is no need to call
-     * __timer_table_get() since we're guaranteed that __timer_table
-     * is initialized in this thread
-     */
-    thr_timer_table_free(__timer_table, timer);
+    if (timespec_cmp(&expires, &now) > 0) {
+      // Cool, there was no overrun, so compute the
+      // relative timeout as 'expires - now', then wait.
+      struct timespec diff = expires;
+      timespec_sub(&diff, &now);
 
-    return NULL;
+      int ret = __pthread_cond_timedwait_relative(&timer->cond, &timer->mutex, &diff);
+
+      // If we didn't time out, it means that a state change
+      // occurred, so loop to take care of it.
+      if (ret != ETIMEDOUT) {
+        continue;
+      }
+    } else {
+      // Overrun was detected before we could wait!
+      if (!timespec_is_zero(&period)) {
+        // For periodic timers, compute total overrun count.
+        do {
+          timespec_add(&expires, &period);
+          if (timer->overruns < DELAYTIMER_MAX) {
+            timer->overruns += 1;
+          }
+        } while (timespec_cmp(&expires, &now) < 0);
+
+        // Backtrack the last one, because we're going to
+        // add the same value just a bit later.
+        timespec_sub(&expires, &period);
+      } else {
+        // For non-periodic timers, things are simple.
+        timer->overruns = 1;
+      }
+    }
+
+    // If we get here, a timeout was detected.
+    // First reload/disarm the timer as needed.
+    if (!timespec_is_zero(&period)) {
+      timespec_add(&expires, &period);
+    } else {
+      timespec_zero(&expires);
+    }
+    timer->expires = expires;
+
+    // Now call the timer callback function. Release the
+    // lock to allow the function to modify the timer setting
+    // or call timer_getoverrun().
+    // NOTE: at this point we trust the callback not to be a
+    //      total moron and pthread_kill() the timer thread
+    thr_timer_unlock(timer);
+    timer->callback(timer->value);
+    thr_timer_lock(timer);
+
+    // Now clear the overruns counter. it only makes sense
+    // within the callback.
+    timer->overruns = 0;
+  }
+
+  thr_timer_unlock(timer);
+
+  // Free the timer object.
+  thr_timer_table_free(__timer_table_get(), timer);
+
+  return NULL;
 }
diff --git a/libc/include/string.h b/libc/include/string.h
index 6e6c8e6..12c9500 100644
--- a/libc/include/string.h
+++ b/libc/include/string.h
@@ -85,6 +85,47 @@
 extern int    strcoll(const char *, const char *) __purefunc;
 extern size_t strxfrm(char *, const char *, size_t);
 
+#if defined(_FORTIFY_SOURCE) && _FORTIFY_SOURCE > 0 && defined(__OPTIMIZE__) && __OPTIMIZE__ > 0
+
+#define __BIONIC_FORTIFY_INLINE \
+    extern inline \
+    __attribute__ ((always_inline)) \
+    __attribute__ ((gnu_inline)) \
+    __attribute__ ((artificial))
+
+__BIONIC_FORTIFY_INLINE
+void *memcpy (void *dest, const void *src, size_t len) {
+    return __builtin___memcpy_chk (dest, src, len, __builtin_object_size (dest, 0));
+}
+
+__BIONIC_FORTIFY_INLINE
+void *memmove (void *dest, const void *src, size_t len) {
+    return __builtin___memmove_chk (dest, src, len, __builtin_object_size (dest, 0));
+}
+
+__BIONIC_FORTIFY_INLINE
+char *strcpy(char *dest, const char *src) {
+    return __builtin___strcpy_chk (dest, src, __builtin_object_size (dest, 0));
+}
+
+__BIONIC_FORTIFY_INLINE
+char *strncpy(char *dest, const char *src, size_t n) {
+    return __builtin___strncpy_chk(dest, src, n, __builtin_object_size (dest, 0));
+}
+
+__BIONIC_FORTIFY_INLINE
+char *strcat(char *dest, const char *src) {
+    return __builtin___strcat_chk (dest, src, __builtin_object_size (dest, 0));
+}
+
+__BIONIC_FORTIFY_INLINE
+char *strncat(char *dest, const char *src, size_t n) {
+    return __builtin___strncat_chk(dest, src, n, __builtin_object_size (dest, 0));
+}
+
+#undef __BIONIC_FORTIFY_INLINE
+#endif
+
 __END_DECLS
 
 #endif /* _STRING_H_ */
diff --git a/libc/arch-arm/bionic/atexit.S b/libc/private/__dso_handle.h
similarity index 70%
rename from libc/arch-arm/bionic/atexit.S
rename to libc/private/__dso_handle.h
index beea685..e67ce7c 100644
--- a/libc/arch-arm/bionic/atexit.S
+++ b/libc/private/__dso_handle.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,37 +26,9 @@
  * SUCH DAMAGE.
  */
 
+
 #ifndef CRT_LEGACY_WORKAROUND
-	.arch armv5te
-	.fpu softvfp
-	.eabi_attribute 20, 1
-	.eabi_attribute 21, 1
-	.eabi_attribute 23, 3
-	.eabi_attribute 24, 1
-	.eabi_attribute 25, 1
-	.eabi_attribute 26, 2
-	.eabi_attribute 30, 4
-	.eabi_attribute 18, 4
-	.hidden	atexit
-	.code	16
-	.thumb_func
-ENTRY(atexit)
-.LFB0:
-	.save	{r4, lr}
-	push	{r4, lr}
-.LCFI0:
-	ldr	r3, .L3
-	mov	r1, #0
-	@ sp needed for prologue
-.LPIC0:
-	add	r3, pc
-	ldr	r2, [r3]
-	bl	__cxa_atexit
-	pop	{r4, pc}
-.L4:
-	.align	2
-.L3:
-	.word	__dso_handle-(.LPIC0+4)
-.LFE0:
-END(atexit)
+__attribute__ ((visibility ("hidden")))
 #endif
+__attribute__ ((section (".bss")))
+void *__dso_handle = (void *) 0;
diff --git a/libc/arch-arm/bionic/atexit.S b/libc/private/__dso_handle_so.c
similarity index 68%
copy from libc/arch-arm/bionic/atexit.S
copy to libc/private/__dso_handle_so.c
index beea685..198e64b 100644
--- a/libc/arch-arm/bionic/atexit.S
+++ b/libc/private/__dso_handle_so.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,37 +26,7 @@
  * SUCH DAMAGE.
  */
 
-#ifndef CRT_LEGACY_WORKAROUND
-	.arch armv5te
-	.fpu softvfp
-	.eabi_attribute 20, 1
-	.eabi_attribute 21, 1
-	.eabi_attribute 23, 3
-	.eabi_attribute 24, 1
-	.eabi_attribute 25, 1
-	.eabi_attribute 26, 2
-	.eabi_attribute 30, 4
-	.eabi_attribute 18, 4
-	.hidden	atexit
-	.code	16
-	.thumb_func
-ENTRY(atexit)
-.LFB0:
-	.save	{r4, lr}
-	push	{r4, lr}
-.LCFI0:
-	ldr	r3, .L3
-	mov	r1, #0
-	@ sp needed for prologue
-.LPIC0:
-	add	r3, pc
-	ldr	r2, [r3]
-	bl	__cxa_atexit
-	pop	{r4, pc}
-.L4:
-	.align	2
-.L3:
-	.word	__dso_handle-(.LPIC0+4)
-.LFE0:
-END(atexit)
-#endif
+
+__attribute__ ((visibility ("hidden")))
+__attribute__ ((section (".data")))
+void *__dso_handle;
diff --git a/libc/arch-arm/bionic/atexit.S b/libc/string/__memcpy_chk.c
similarity index 64%
copy from libc/arch-arm/bionic/atexit.S
copy to libc/string/__memcpy_chk.c
index beea685..aed3ec2 100644
--- a/libc/arch-arm/bionic/atexit.S
+++ b/libc/string/__memcpy_chk.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,37 +26,29 @@
  * SUCH DAMAGE.
  */
 
-#ifndef CRT_LEGACY_WORKAROUND
-	.arch armv5te
-	.fpu softvfp
-	.eabi_attribute 20, 1
-	.eabi_attribute 21, 1
-	.eabi_attribute 23, 3
-	.eabi_attribute 24, 1
-	.eabi_attribute 25, 1
-	.eabi_attribute 26, 2
-	.eabi_attribute 30, 4
-	.eabi_attribute 18, 4
-	.hidden	atexit
-	.code	16
-	.thumb_func
-ENTRY(atexit)
-.LFB0:
-	.save	{r4, lr}
-	push	{r4, lr}
-.LCFI0:
-	ldr	r3, .L3
-	mov	r1, #0
-	@ sp needed for prologue
-.LPIC0:
-	add	r3, pc
-	ldr	r2, [r3]
-	bl	__cxa_atexit
-	pop	{r4, pc}
-.L4:
-	.align	2
-.L3:
-	.word	__dso_handle-(.LPIC0+4)
-.LFE0:
-END(atexit)
-#endif
+#include <string.h>
+#include <stdlib.h>
+#include <private/logd.h>
+
+/*
+ * Runtime implementation of __builtin____memcpy_chk.
+ *
+ * See
+ *   http://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html
+ *   http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
+ * for details.
+ *
+ * This memcpy check is called if _FORTIFY_SOURCE is defined and
+ * greater than 0.
+ */
+void *__memcpy_chk (void *dest, const void *src,
+              size_t len, size_t dest_len)
+{
+    if (len > dest_len) {
+        __libc_android_log_print(ANDROID_LOG_FATAL, "libc",
+            "*** memcpy buffer overflow detected ***\n");
+        abort();
+    }
+
+    return memcpy(dest, src, len);
+}
diff --git a/libc/arch-arm/bionic/atexit.S b/libc/string/__memmove_chk.c
similarity index 64%
copy from libc/arch-arm/bionic/atexit.S
copy to libc/string/__memmove_chk.c
index beea685..5a6eb4d 100644
--- a/libc/arch-arm/bionic/atexit.S
+++ b/libc/string/__memmove_chk.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,37 +26,29 @@
  * SUCH DAMAGE.
  */
 
-#ifndef CRT_LEGACY_WORKAROUND
-	.arch armv5te
-	.fpu softvfp
-	.eabi_attribute 20, 1
-	.eabi_attribute 21, 1
-	.eabi_attribute 23, 3
-	.eabi_attribute 24, 1
-	.eabi_attribute 25, 1
-	.eabi_attribute 26, 2
-	.eabi_attribute 30, 4
-	.eabi_attribute 18, 4
-	.hidden	atexit
-	.code	16
-	.thumb_func
-ENTRY(atexit)
-.LFB0:
-	.save	{r4, lr}
-	push	{r4, lr}
-.LCFI0:
-	ldr	r3, .L3
-	mov	r1, #0
-	@ sp needed for prologue
-.LPIC0:
-	add	r3, pc
-	ldr	r2, [r3]
-	bl	__cxa_atexit
-	pop	{r4, pc}
-.L4:
-	.align	2
-.L3:
-	.word	__dso_handle-(.LPIC0+4)
-.LFE0:
-END(atexit)
-#endif
+#include <string.h>
+#include <stdlib.h>
+#include <private/logd.h>
+
+/*
+ * Runtime implementation of __builtin____memmove_chk.
+ *
+ * See
+ *   http://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html
+ *   http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
+ * for details.
+ *
+ * This memmove check is called if _FORTIFY_SOURCE is defined and
+ * greater than 0.
+ */
+void *__memmove_chk (void *dest, const void *src,
+              size_t len, size_t dest_len)
+{
+    if (len > dest_len) {
+        __libc_android_log_print(ANDROID_LOG_FATAL, "libc",
+            "*** memmove buffer overflow detected ***\n");
+        abort();
+    }
+
+    return memmove(dest, src, len);
+}
diff --git a/libc/arch-arm/bionic/crtbegin_so.S b/libc/string/__strcat_chk.c
similarity index 61%
rename from libc/arch-arm/bionic/crtbegin_so.S
rename to libc/string/__strcat_chk.c
index 104d214..3e02052 100644
--- a/libc/arch-arm/bionic/crtbegin_so.S
+++ b/libc/string/__strcat_chk.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,39 +26,32 @@
  * SUCH DAMAGE.
  */
 
-#include <machine/asm.h>
+#include <string.h>
+#include <stdlib.h>
+#include <private/logd.h>
 
-# Implement static C++ destructors when the shared
-# library is unloaded through dlclose().
-#
-# A call to this function must be the first entry
-# in the .fini_array. See 3.3.5.3.C of C++ ABI
-# standard.
-#
-ENTRY(__on_dlclose)
-        adr     r0, 0f
-        ldr     r0, [r0]
-        b       __cxa_finalize
-END(__on_dlclose)
+/*
+ * Runtime implementation of __builtin____strcat_chk.
+ *
+ * See
+ *   http://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html
+ *   http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
+ * for details.
+ *
+ * This strcat check is called if _FORTIFY_SOURCE is defined and
+ * greater than 0.
+ */
+char *__strcat_chk (char *dest, const char *src, size_t dest_buf_size)
+{
+    // TODO: optimize so we don't scan src/dest twice.
+    size_t src_len  = strlen(src);
+    size_t dest_len = strlen(dest);
 
-0:
-        .long   __dso_handle
+    if (src_len + dest_len + 1 > dest_buf_size) {
+        __libc_android_log_print(ANDROID_LOG_FATAL, "libc",
+            "*** strcat buffer overflow detected ***\n");
+        abort();
+    }
 
-	.section .init_array, "aw"
-	.globl __INIT_ARRAY__
-__INIT_ARRAY__:
-	.long -1
-
-        .section .fini_array, "aw"
-        .globl __FINI_ARRAY__
-__FINI_ARRAY__:
-        .long -1
-        .long __on_dlclose
-
-#ifdef CRT_LEGACY_WORKAROUND
-#include "__dso_handle.S"
-#else
-#include "__dso_handle_so.S"
-#endif
-
-#include "atexit.S"
+    return strcat(dest, src);
+}
diff --git a/libc/arch-arm/bionic/atexit.S b/libc/string/__strcpy_chk.c
similarity index 62%
copy from libc/arch-arm/bionic/atexit.S
copy to libc/string/__strcpy_chk.c
index beea685..85aa19d 100644
--- a/libc/arch-arm/bionic/atexit.S
+++ b/libc/string/__strcpy_chk.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,37 +26,30 @@
  * SUCH DAMAGE.
  */
 
-#ifndef CRT_LEGACY_WORKAROUND
-	.arch armv5te
-	.fpu softvfp
-	.eabi_attribute 20, 1
-	.eabi_attribute 21, 1
-	.eabi_attribute 23, 3
-	.eabi_attribute 24, 1
-	.eabi_attribute 25, 1
-	.eabi_attribute 26, 2
-	.eabi_attribute 30, 4
-	.eabi_attribute 18, 4
-	.hidden	atexit
-	.code	16
-	.thumb_func
-ENTRY(atexit)
-.LFB0:
-	.save	{r4, lr}
-	push	{r4, lr}
-.LCFI0:
-	ldr	r3, .L3
-	mov	r1, #0
-	@ sp needed for prologue
-.LPIC0:
-	add	r3, pc
-	ldr	r2, [r3]
-	bl	__cxa_atexit
-	pop	{r4, pc}
-.L4:
-	.align	2
-.L3:
-	.word	__dso_handle-(.LPIC0+4)
-.LFE0:
-END(atexit)
-#endif
+#include <string.h>
+#include <stdlib.h>
+#include <private/logd.h>
+
+/*
+ * Runtime implementation of __builtin____strcpy_chk.
+ *
+ * See
+ *   http://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html
+ *   http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
+ * for details.
+ *
+ * This strcpy check is called if _FORTIFY_SOURCE is defined and
+ * greater than 0.
+ */
+char *__strcpy_chk (char *dest, const char *src, size_t dest_len)
+{
+    // TODO: optimize so we don't scan src twice.
+    size_t src_len = strlen(src) + 1;
+    if (src_len > dest_len) {
+        __libc_android_log_print(ANDROID_LOG_FATAL, "libc",
+            "*** strcpy buffer overflow detected ***\n");
+        abort();
+    }
+
+    return strcpy(dest, src);
+}
diff --git a/libc/string/__strncat_chk.c b/libc/string/__strncat_chk.c
new file mode 100644
index 0000000..9b0b84a
--- /dev/null
+++ b/libc/string/__strncat_chk.c
@@ -0,0 +1,61 @@
+/*
+ * Copyright (C) 2012 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 <string.h>
+#include <stdlib.h>
+#include <private/logd.h>
+
+/*
+ * Runtime implementation of __builtin____strncat_chk.
+ *
+ * See
+ *   http://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html
+ *   http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
+ * for details.
+ *
+ * This strncat check is called if _FORTIFY_SOURCE is defined and
+ * greater than 0.
+ */
+char *__strncat_chk (char *dest, const char *src,
+              size_t len, size_t dest_buf_size)
+{
+    // TODO: optimize so we don't scan src/dest twice.
+    size_t dest_len = strlen(dest);
+    size_t src_len = strlen(src);
+    if (src_len > len) {
+        src_len = len;
+    }
+
+    if (dest_len + src_len + 1 > dest_buf_size) {
+        __libc_android_log_print(ANDROID_LOG_FATAL, "libc",
+            "*** strncat buffer overflow detected ***\n");
+        abort();
+    }
+
+    return strncat(dest, src, len);
+}
diff --git a/libc/arch-arm/bionic/atexit.S b/libc/string/__strncpy_chk.c
similarity index 64%
copy from libc/arch-arm/bionic/atexit.S
copy to libc/string/__strncpy_chk.c
index beea685..b87ef4b 100644
--- a/libc/arch-arm/bionic/atexit.S
+++ b/libc/string/__strncpy_chk.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -26,37 +26,29 @@
  * SUCH DAMAGE.
  */
 
-#ifndef CRT_LEGACY_WORKAROUND
-	.arch armv5te
-	.fpu softvfp
-	.eabi_attribute 20, 1
-	.eabi_attribute 21, 1
-	.eabi_attribute 23, 3
-	.eabi_attribute 24, 1
-	.eabi_attribute 25, 1
-	.eabi_attribute 26, 2
-	.eabi_attribute 30, 4
-	.eabi_attribute 18, 4
-	.hidden	atexit
-	.code	16
-	.thumb_func
-ENTRY(atexit)
-.LFB0:
-	.save	{r4, lr}
-	push	{r4, lr}
-.LCFI0:
-	ldr	r3, .L3
-	mov	r1, #0
-	@ sp needed for prologue
-.LPIC0:
-	add	r3, pc
-	ldr	r2, [r3]
-	bl	__cxa_atexit
-	pop	{r4, pc}
-.L4:
-	.align	2
-.L3:
-	.word	__dso_handle-(.LPIC0+4)
-.LFE0:
-END(atexit)
-#endif
+#include <string.h>
+#include <stdlib.h>
+#include <private/logd.h>
+
+/*
+ * Runtime implementation of __builtin____strncpy_chk.
+ *
+ * See
+ *   http://gcc.gnu.org/onlinedocs/gcc/Object-Size-Checking.html
+ *   http://gcc.gnu.org/ml/gcc-patches/2004-09/msg02055.html
+ * for details.
+ *
+ * This strncpy check is called if _FORTIFY_SOURCE is defined and
+ * greater than 0.
+ */
+char *__strncpy_chk (char *dest, const char *src,
+              size_t len, size_t dest_len)
+{
+    if (len > dest_len) {
+        __libc_android_log_print(ANDROID_LOG_FATAL, "libc",
+            "*** strncpy buffer overflow detected ***\n");
+        abort();
+    }
+
+    return strncpy(dest, src, len);
+}
diff --git a/libc/unistd/sysconf.c b/libc/unistd/sysconf.c
index 9377802..7caa4e9 100644
--- a/libc/unistd/sysconf.c
+++ b/libc/unistd/sysconf.c
@@ -25,16 +25,19 @@
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-#include <unistd.h>
-#include <sys/sysconf.h>
-#include <limits.h>
-#include <bionic_tls.h>
+
 #include <asm/page.h>
-#include <stdio.h>  /* for FOPEN_MAX */
+#include <bionic_tls.h>
+#include <ctype.h>
+#include <dirent.h>
 #include <errno.h>
 #include <fcntl.h>
+#include <limits.h>
+#include <stdbool.h>
+#include <stdio.h>  // For FOPEN_MAX.
 #include <string.h>
-#include <ctype.h>
+#include <sys/sysconf.h>
+#include <unistd.h>
 
 /* seems to be the default on Linux, per the GLibc sources and my own digging */
 
@@ -62,18 +65,88 @@
 #define  SYSTEM_2_FORT_DEV   -1       /* Fortran development unsupported */
 #define  SYSTEM_2_FORT_RUN   -1       /* Fortran runtime unsupported */
 #define  SYSTEM_2_SW_DEV     -1       /* posix software dev utilities unsupported */
-#define  SYSTEM_2_LOCALEDEF  -1       /* localdef() unimplemented */
+#define  SYSTEM_2_LOCALEDEF  -1       /* localedef() unimplemented */
 #define  SYSTEM_2_UPE        -1       /* No UPE for you ! (User Portability Utilities) */
 #define  SYSTEM_2_VERSION    -1       /* No posix command-line tools */
 
-static int  __get_nproc_conf(void);
-static int  __get_nproc_onln(void);
-static int  __get_phys_pages(void);
-static int  __get_avphys_pages(void);
+static bool __matches_cpuN(const char* s) {
+  // The %c trick is to ensure that we have the anchored match "^cpu[0-9]+$".
+  unsigned cpu;
+  char dummy;
+  return (sscanf(s, "cpu%u%c", &cpu, &dummy) == 1);
+}
 
-int
-sysconf( int  name )
-{
+static int __get_nproc_conf(void) {
+  // On x86 kernels you can use /proc/cpuinfo for this, but on ARM kernels offline CPUs disappear
+  // from there. This method works on both.
+  DIR* d = opendir("/sys/devices/system/cpu");
+  if (!d) {
+    return 1;
+  }
+
+  int result = 0;
+  struct dirent de;
+  struct dirent* e;
+  while (!readdir_r(d, &de, &e) && e != NULL) {
+    if (e->d_type == DT_DIR && __matches_cpuN(e->d_name)) {
+      ++result;
+    }
+  }
+  closedir(d);
+  return result;
+}
+
+static int __get_nproc_onln(void) {
+  FILE* fp = fopen("/proc/stat", "r");
+  if (fp == NULL) {
+    return 1;
+  }
+
+  int result = 0;
+  char buf[256];
+  while (fgets(buf, sizeof(buf), fp) != NULL) {
+    // Extract just the first word from the line.
+    // 'cpu0 7976751 1364388 3116842 469770388 8629405 0 49047 0 0 0'
+    char* p = strchr(buf, ' ');
+    if (p != NULL) {
+      *p = 0;
+    }
+    if (__matches_cpuN(buf)) {
+      ++result;
+    }
+  }
+  fclose(fp);
+  return result;
+}
+
+static int __get_meminfo(const char* pattern) {
+  FILE* fp = fopen("/proc/meminfo", "r");
+  if (fp == NULL) {
+    return -1;
+  }
+
+  int result = -1;
+  char buf[256];
+  while (fgets(buf, sizeof(buf), fp) != NULL) {
+    long total;
+    if (sscanf(buf, pattern, &total) == 1) {
+      result = (int) (total / (PAGE_SIZE/1024));
+      break;
+    }
+  }
+  fclose(fp);
+  return result;
+}
+
+static int __get_phys_pages(void) {
+  return __get_meminfo("MemTotal: %ld kB");
+}
+
+static int __get_avphys_pages(void) {
+  return __get_meminfo("MemFree: %ld kB");
+}
+
+int sysconf(int name) {
     switch (name) {
 #ifdef _POSIX_ARG_MAX
     case _SC_ARG_MAX:           return _POSIX_ARG_MAX;
@@ -266,169 +339,3 @@
         return -1;
     }
 }
-
-
-typedef struct {
-    int   rpos;
-    int   len;
-    int   overflow;
-    int   fd;
-    int   in_len;
-    int   in_pos;
-    char  buff[128];
-    char  input[128];
-} LineParser;
-
-static int
-line_parser_init( LineParser*  p, const char*  path )
-{
-    p->rpos     = 0;
-    p->len      = (int)sizeof(p->buff);
-    p->overflow = 0;
-
-    p->in_len   = 0;
-    p->in_pos   = 0;
-    p->fd       = open( path, O_RDONLY );
-
-    return p->fd;
-}
-
-
-static int
-line_parser_addc( LineParser*  p, int  c )
-{
-    if (p->overflow) {
-        p->overflow = (c == '\n');
-        return 0;
-    }
-    if (p->rpos >= p->len) {
-        p->overflow = 1;
-        return 0;
-    }
-    if (c == '\n') {
-        p->buff[p->rpos] = 0;
-        p->rpos = 0;
-        return 1;
-    }
-    p->buff[p->rpos++] = (char) c;
-    return 0;
-}
-
-static int
-line_parser_getc( LineParser*  p )
-{
-    if (p->in_pos >= p->in_len) {
-        int  ret;
-
-        p->in_len = p->in_pos = 0;
-        do {
-            ret = read(p->fd, p->input, sizeof(p->input));
-        } while (ret < 0 && errno == EINTR);
-
-        if (ret <= 0)
-            return -1;
-
-        p->in_len = ret;
-    }
-    return p->input[ p->in_pos++ ];
-}
-
-static const char*
-line_parser_gets( LineParser*  p )
-{
-    for (;;) {
-        for (;;) {
-            int  c = line_parser_getc(p);
-
-            if (c < 0) {
-                close(p->fd);
-                p->fd = -1;
-                return NULL;
-             }
-             if (line_parser_addc(p, c))
-                return p->buff;
-        }
-    }
-}
-
-static void
-line_parser_done( LineParser* p )
-{
-    if (p->fd >= 0) {
-        close(p->fd);
-        p->fd = -1;
-    }
-}
-
-static int
-__get_nproc_conf(void)
-{
-    LineParser   parser[1];
-    const char*  p;
-    int          count = 0;
-
-    if (line_parser_init(parser, "/proc/cpuinfo") < 0)
-        return 1;
-
-    while ((p = line_parser_gets(parser))) {
-        if ( !memcmp(p, "processor", 9) )
-            count += 1;
-    }
-    return (count < 1) ? 1 : count;
-}
-
-
-static int
-__get_nproc_onln(void)
-{
-    LineParser   parser[1];
-    const char*  p;
-    int          count = 0;
-
-    if (line_parser_init(parser, "/proc/stat") < 0)
-        return 1;
-
-    while ((p = line_parser_gets(parser))) {
-        if ( !memcmp(p, "cpu", 3) && isdigit(p[3]) )
-            count += 1;
-    }
-    return (count < 1) ? 1 : count;
-}
-
-static int
-__get_phys_pages(void)
-{
-    LineParser   parser[1];
-    const char*  p;
-
-    if (line_parser_init(parser, "/proc/meminfo") < 0)
-        return -2;  /* what ? */
-
-    while ((p = line_parser_gets(parser))) {
-        long  total;
-        if ( sscanf(p, "MemTotal: %ld kB", &total) == 1 ) {
-            line_parser_done(parser);
-            return (int) (total / (PAGE_SIZE/1024));
-        }
-    }
-    return -3;
-}
-
-static int
-__get_avphys_pages(void)
-{
-    LineParser   parser[1];
-    const char*  p;
-
-    if (line_parser_init(parser, "/proc/meminfo") < 0)
-        return -1;  /* what ? */
-
-    while ((p = line_parser_gets(parser))) {
-        long  total;
-        if ( sscanf(p, "MemFree: %ld kB", &total) == 1 ) {
-            line_parser_done(parser);
-            return (int) (total / (PAGE_SIZE/1024));
-        }
-    }
-    return -1;
-}