Merge change 10541

* changes:
  added and modified libdl to support SuperH architecture
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..0db5b03
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+*.pyc
+libc/kernel/original
diff --git a/MAINTAINERS b/MAINTAINERS
new file mode 100644
index 0000000..a76dc24
--- /dev/null
+++ b/MAINTAINERS
@@ -0,0 +1,6 @@
+
+Bionic support for SuperH
+-------------------------
+Bionic support for SuperH architecture is written by
+Shin-ichiro KAWASAKI <shinichiro.kawasaki.mg@hitachi.com>
+and Contributed to Android by Hitachi, Ltd. and Renesas Solutions Corp.
diff --git a/libc/Android.mk b/libc/Android.mk
index 330802a..59a4c6b 100644
--- a/libc/Android.mk
+++ b/libc/Android.mk
@@ -1,6 +1,9 @@
 LOCAL_PATH:= $(call my-dir)
 
 include $(LOCAL_PATH)/arch-$(TARGET_ARCH)/syscalls.mk
+
+# Define the common source files for all the libc instances
+# =========================================================
 libc_common_src_files := \
 	$(syscall_src) \
 	unistd/abort.c \
@@ -272,6 +275,8 @@
 	netbsd/nameser/ns_print.c \
 	netbsd/nameser/ns_samedomain.c
 
+# Architecture specific source files go here
+# =========================================================
 ifeq ($(TARGET_ARCH),arm)
 libc_common_src_files += \
 	bionic/eabi.c \
@@ -301,6 +306,14 @@
 	bionic/pthread.c.arm \
 	bionic/pthread-timers.c.arm \
 	bionic/ptrace.c.arm
+
+# these are used by the static and dynamic versions of the libc
+# respectively
+libc_arch_static_src_files := \
+	arch-arm/bionic/exidx_static.c
+
+libc_arch_dynamic_src_files := \
+	arch-arm/bionic/exidx_dynamic.c
 else # !arm
 
 ifeq ($(TARGET_ARCH),x86)
@@ -322,10 +335,17 @@
 	bionic/pthread.c \
 	bionic/pthread-timers.c \
 	bionic/ptrace.c
-endif # x86
 
+# this is needed for static versions of libc
+libc_arch_static_src_files := \
+	arch-x86/bionic/dl_iterate_phdr_static.c
+
+libc_arch_dynamic_src_files :=
+endif # x86
 endif # !arm
 
+# Define some common cflags
+# ========================================================
 libc_common_cflags := \
 		-DWITH_ERRLIST			\
 		-DANDROID_CHANGES		\
@@ -337,162 +357,158 @@
 		-DNEED_PSELECT=1		\
 		-DINET6 \
 		-I$(LOCAL_PATH)/private \
+		-DUSE_DL_PREFIX
 
-ifeq ($(TARGET_BUILD_TYPE),debug)
+ifeq ($(strip $(DEBUG_BIONIC_LIBC)),true)
   libc_common_cflags += -DDEBUG
 endif
 
 ifeq ($(TARGET_ARCH),arm)
   libc_common_cflags += -fstrict-aliasing
-endif
+  libc_crt_target_cflags := -mthumb-interwork
+else # !arm
+  ifeq ($(TARGET_ARCH),x86)
+    libc_crt_target_cflags := -m32
+  endif # x86
+endif # !arm
 
+# Define some common includes
+# ========================================================
 libc_common_c_includes := \
 		$(LOCAL_PATH)/stdlib  \
 		$(LOCAL_PATH)/string  \
 		$(LOCAL_PATH)/stdio
 
-# libc_common.a
-# ========================================================
 
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES := $(libc_common_src_files)
-LOCAL_CFLAGS := $(libc_common_cflags) -DUSE_DL_PREFIX
-LOCAL_C_INCLUDES := $(libc_common_c_includes)
-
-ifneq ($(TARGET_SIMULATOR),true)
-  ifeq ($(TARGET_ARCH),arm)
-    crtend_target_cflags := -mthumb-interwork
-  else
-    ifeq ($(TARGET_ARCH),x86)
-      crtend_target_cflags := -m32
-    endif
-  endif
-# We rename crtend.o to crtend_android.o to avoid a
-# name clash between gcc and bionic.
-GEN := $(TARGET_OUT_STATIC_LIBRARIES)/crtend_android.o
-$(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtend.S
-	@mkdir -p $(dir $@)
-	$(TARGET_CC) $(crtend_target_cflags) -o $@ -c $<
-ALL_GENERATED_SOURCES += $(GEN)
-endif
-
-
-# crtbegin_so.o/crtend_so.o
-# These are needed for building the shared libs.
-ifneq ($(TARGET_SIMULATOR),true)
+# Define the libc run-time (crt) support object files that must be built,
+# which are needed to build all other objects (shared/static libs and
+# executables)
+# ==========================================================================
 
 ifeq ($(TARGET_ARCH),x86)
-
-crt_begin_end_so_target_cflags := -m32
-
+# we only need begin_so/end_so for x86, since it needs an appropriate .init
+# section in the shared library with a function to call all the entries in
+# .ctors section. ARM uses init_array, and does not need the function.
 GEN := $(TARGET_OUT_STATIC_LIBRARIES)/crtbegin_so.o
 $(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin_so.S
 	@mkdir -p $(dir $@)
-	$(TARGET_CC) $(crt_begin_end_so_target_cflags) -o $@ -c $<
+	$(TARGET_CC) $(libc_crt_target_cflags) -o $@ -c $<
 ALL_GENERATED_SOURCES += $(GEN)
 
 GEN := $(TARGET_OUT_STATIC_LIBRARIES)/crtend_so.o
 $(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtend_so.S
 	@mkdir -p $(dir $@)
-	$(TARGET_CC) $(crt_begin_end_so_target_cflags) -o $@ -c $<
+	$(TARGET_CC) $(libc_crt_target_cflags) -o $@ -c $<
 ALL_GENERATED_SOURCES += $(GEN)
-
 endif # TARGET_ARCH == x86
 
-endif # !TARGET_SIMULATOR
+
+GEN := $(TARGET_OUT_STATIC_LIBRARIES)/crtbegin_static.o
+$(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin_static.S
+	@mkdir -p $(dir $@)
+	$(TARGET_CC) $(libc_crt_target_cflags) -o $@ -c $<
+ALL_GENERATED_SOURCES += $(GEN)
+
+GEN := $(TARGET_OUT_STATIC_LIBRARIES)/crtbegin_dynamic.o
+$(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin_dynamic.S
+	@mkdir -p $(dir $@)
+	$(TARGET_CC) $(libc_crt_target_cflags) -o $@ -c $<
+ALL_GENERATED_SOURCES += $(GEN)
 
 
+# We rename crtend.o to crtend_android.o to avoid a
+# name clash between gcc and bionic.
+GEN := $(TARGET_OUT_STATIC_LIBRARIES)/crtend_android.o
+$(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtend.S
+	@mkdir -p $(dir $@)
+	$(TARGET_CC) $(libc_crt_target_cflags) -o $@ -c $<
+ALL_GENERATED_SOURCES += $(GEN)
+
+
+# To enable malloc leak check for statically linked programs, add
+# "WITH_MALLOC_CHECK_LIBC_A := true" to buildspec.mk
+WITH_MALLOC_CHECK_LIBC_A := $(strip $(WITH_MALLOC_CHECK_LIBC_A))
+
+# ========================================================
+# libc_common.a
+# ========================================================
+include $(CLEAR_VARS)
+
+LOCAL_SRC_FILES := $(libc_common_src_files)
+LOCAL_CFLAGS := $(libc_common_cflags)
+LOCAL_C_INCLUDES := $(libc_common_c_includes)
 LOCAL_MODULE := libc_common
 LOCAL_SYSTEM_SHARED_LIBRARIES :=
 
 include $(BUILD_STATIC_LIBRARY)
 
 
-# libc.a
 # ========================================================
+# libc_nomalloc.a
+# ========================================================
+#
+# This is a version of the static C library that does not
+# include malloc. It's useful in situations when calling
+# the user wants to provide their own malloc implementation,
+# or wants to explicitly disallow the use of the use of malloc,
+# like the dynamic loader.
 
 include $(CLEAR_VARS)
 
-include $(LOCAL_PATH)/arch-$(TARGET_ARCH)/syscalls.mk
-
-# To enable malloc leak check for statically linked programs, add
-# "WITH_MALLOC_CHECK_LIBC_A := true" to device/buildspec.mk
-WITH_MALLOC_CHECK_LIBC_A := $(strip $(WITH_MALLOC_CHECK_LIBC_A))
-
 LOCAL_SRC_FILES := \
-	$(libc_common_src_files) \
-	bionic/dlmalloc.c \
+	$(libc_arch_static_src_files) \
 	bionic/libc_init_static.c
 
-ifeq ($(WITH_MALLOC_CHECK_LIBC_A),true)
-  LOCAL_SRC_FILES += bionic/malloc_leak.c.arm
-endif
-
-ifeq ($(TARGET_ARCH),arm)
-LOCAL_SRC_FILES += \
-	arch-arm/bionic/exidx_static.c
-
-else # TARGET_ARCH != arm
-
-ifeq ($(TARGET_ARCH),x86)
-LOCAL_SRC_FILES += \
-	arch-x86/bionic/dl_iterate_phdr_static.c
-endif
-
-endif
-
-ifneq ($(TARGET_SIMULATOR),true)
-  ifeq ($(TARGET_ARCH),arm)
-    crtbegin_static_target_cflags := -mthumb-interwork
-  else
-    ifeq ($(TARGET_ARCH),x86)
-      crtbegin_static_target_cflags := -m32
-    endif
-  endif
-GEN := $(TARGET_OUT_STATIC_LIBRARIES)/crtbegin_static.o
-$(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin_static.S
-	@mkdir -p $(dir $@)
-	$(TARGET_CC) $(crtbegin_static_target_cflags) -o $@ -c $<
-ALL_GENERATED_SOURCES += $(GEN)
-endif
-
+LOCAL_C_INCLUDES := $(libc_common_c_includes)
 LOCAL_CFLAGS := $(libc_common_cflags)
 
-LOCAL_C_INCLUDES := $(libc_common_c_includes)
-
-ifeq ($(WITH_MALLOC_CHECK_LIBC_A),true)
-  LOCAL_CFLAGS += -DUSE_DL_PREFIX -DMALLOC_LEAK_CHECK
-endif
-
+LOCAL_MODULE := libc_nomalloc
 LOCAL_WHOLE_STATIC_LIBRARIES := libc_common
-LOCAL_MODULE:= libc
 LOCAL_SYSTEM_SHARED_LIBRARIES :=
 
 include $(BUILD_STATIC_LIBRARY)
 
 
-# libc.so
 # ========================================================
-
+# libc.a
+# ========================================================
 include $(CLEAR_VARS)
 
+LOCAL_SRC_FILES := \
+	$(libc_arch_static_src_files) \
+	bionic/dlmalloc.c \
+	bionic/libc_init_static.c
+
 LOCAL_CFLAGS := $(libc_common_cflags)
 
-LOCAL_CFLAGS += -DUSE_DL_PREFIX
+ifeq ($(WITH_MALLOC_CHECK_LIBC_A),true)
+  LOCAL_CFLAGS += -DMALLOC_LEAK_CHECK
+  LOCAL_SRC_FILES += bionic/malloc_leak.c.arm
+endif
 
 LOCAL_C_INCLUDES := $(libc_common_c_includes)
 
+LOCAL_MODULE := libc
+LOCAL_WHOLE_STATIC_LIBRARIES := libc_common
+LOCAL_SYSTEM_SHARED_LIBRARIES :=
+
+include $(BUILD_STATIC_LIBRARY)
+
+
+# ========================================================
+# libc.so
+# ========================================================
+include $(CLEAR_VARS)
+
+LOCAL_CFLAGS := $(libc_common_cflags)
+LOCAL_C_INCLUDES := $(libc_common_c_includes)
+
 LOCAL_SRC_FILES := \
+	$(libc_arch_dynamic_src_files) \
 	bionic/dlmalloc.c \
 	bionic/malloc_leak.c.arm \
 	bionic/libc_init_dynamic.c
 
-ifeq ($(TARGET_ARCH),arm)
-LOCAL_SRC_FILES += \
-	arch-arm/bionic/exidx_dynamic.c
-endif
-
 LOCAL_MODULE:= libc
 
 # WARNING: The only library libc.so should depend on is libdl.so!  If you add other libraries,
@@ -507,45 +523,26 @@
 LOCAL_WHOLE_STATIC_LIBRARIES := libc_common
 LOCAL_SYSTEM_SHARED_LIBRARIES :=
 
-ifneq ($(TARGET_SIMULATOR),true)
-  ifeq ($(TARGET_ARCH),arm)
-    crtbegin_dynamic_target_cflags := -mthumb-interwork
-  else
-    ifeq ($(TARGET_ARCH),x86)
-      crtbegin_dynamic_target_cflags := -m32
-    endif
-  endif
-GEN := $(TARGET_OUT_STATIC_LIBRARIES)/crtbegin_dynamic.o
-$(GEN): $(LOCAL_PATH)/arch-$(TARGET_ARCH)/bionic/crtbegin_dynamic.S
-	@mkdir -p $(dir $@)
-	$(TARGET_CC) $(crtbegin_dynamic_target_cflags) -o $@ -c $<
-ALL_GENERATED_SOURCES += $(GEN)
-endif
-
 include $(BUILD_SHARED_LIBRARY)
 
 
+# ========================================================
 # libc_debug.so
 # ========================================================
-
 include $(CLEAR_VARS)
 
-LOCAL_CFLAGS := $(libc_common_cflags)
-
-LOCAL_CFLAGS += -DUSE_DL_PREFIX -DMALLOC_LEAK_CHECK
+LOCAL_CFLAGS := \
+	$(libc_common_cflags) \
+	-DMALLOC_LEAK_CHECK
 
 LOCAL_C_INCLUDES := $(libc_common_c_includes)
 
 LOCAL_SRC_FILES := \
+	$(libc_arch_dynamic_src_files) \
 	bionic/dlmalloc.c \
 	bionic/malloc_leak.c.arm \
 	bionic/libc_init_dynamic.c
 
-ifeq ($(TARGET_ARCH),arm)
-LOCAL_SRC_FILES += \
-	arch-arm/bionic/exidx_dynamic.c
-endif
-
 LOCAL_MODULE:= libc_debug
 
 # WARNING: The only library libc.so should depend on is libdl.so!  If you add other libraries,
@@ -564,9 +561,6 @@
 # Don't install on release build
 LOCAL_MODULE_TAGS := eng
 
-GEN := $(TARGET_OUT_STATIC_LIBRARIES)/crtbegin_dynamic.o
-ALL_GENERATED_SOURCES += $(GEN)
-
 include $(BUILD_SHARED_LIBRARY)
 
 # ========================================================
diff --git a/libc/README b/libc/README
index 4e29f12..d92d85d 100644
--- a/libc/README
+++ b/libc/README
@@ -1,4 +1,5 @@
-Welcome to Bionic, Android small and custom C library for the Android platform
+Welcome to Bionic, Android's small and custom C library for the Android
+platform.
 
 Bionic is mainly a port of the BSD C library to our Linux kernel with the
 following additions/changes:
diff --git a/libc/arch-arm/bionic/atomics_arm.S b/libc/arch-arm/bionic/atomics_arm.S
index b2da09f..57c4239 100644
--- a/libc/arch-arm/bionic/atomics_arm.S
+++ b/libc/arch-arm/bionic/atomics_arm.S
@@ -129,8 +129,18 @@
 #endif
 
 /* r0(new) r1(addr) -> r0(old) */
+/* replaced swp instruction with ldrex/strex for ARMv6 & ARMv7 */
 __atomic_swap:
+#if defined (_ARM_HAVE_LDREX_STREX)
+1:  ldrex   r2, [r1]
+    strex   r3, r0, [r1]
+    teq     r3, #0
+    bne     1b
+    mov     r0, r2
+    mcr     p15, 0, r0, c7, c10, 5 /* or, use dmb */
+#else
     swp     r0, r0, [r1]
+#endif
     bx      lr
 
 /* __futex_wait(*ftx, val, *timespec) */
diff --git a/libc/arch-arm/include/machine/cpu-features.h b/libc/arch-arm/include/machine/cpu-features.h
index f836006..ecf6ff6 100644
--- a/libc/arch-arm/include/machine/cpu-features.h
+++ b/libc/arch-arm/include/machine/cpu-features.h
@@ -149,6 +149,13 @@
 #  define __ARM_HAVE_PC_INTERWORK
 #endif
 
+/* define _ARM_HAVE_LDREX_STREX for ARMv6 and ARMv7 architecure to be
+ * used in replacement of depricated swp instruction
+ */
+#if __ARM_ARCH__ >= 6
+#  define _ARM_HAVE_LDREX_STREX
+#endif
+
 
 /* Assembly-only macros */
 
diff --git a/libc/bionic/dlmalloc.c b/libc/bionic/dlmalloc.c
index 78f20c0..f6f878e 100644
--- a/libc/bionic/dlmalloc.c
+++ b/libc/bionic/dlmalloc.c
@@ -1154,6 +1154,23 @@
 */
 void* mspace_realloc(mspace msp, void* mem, size_t newsize);
 
+#if ANDROID /* Added for Android, not part of dlmalloc as released */
+/*
+  mspace_merge_objects will merge allocated memory mema and memb
+  together, provided memb immediately follows mema.  It is roughly as
+  if memb has been freed and mema has been realloced to a larger size.
+  On successfully merging, mema will be returned. If either argument
+  is null or memb does not immediately follow mema, null will be
+  returned.
+
+  Both mema and memb should have been previously allocated using
+  malloc or a related routine such as realloc. If either mema or memb
+  was not malloced or was previously freed, the result is undefined,
+  but like mspace_free, the default is to abort the program.
+*/
+void* mspace_merge_objects(mspace msp, void* mema, void* memb);
+#endif
+
 /*
   mspace_calloc behaves as calloc, but operates within
   the given space.
@@ -4872,6 +4889,62 @@
   }
 }
 
+#if ANDROID
+void* mspace_merge_objects(mspace msp, void* mema, void* memb)
+{
+  /* PREACTION/POSTACTION aren't necessary because we are only
+     modifying fields of inuse chunks owned by the current thread, in
+     which case no other malloc operations can touch them.
+   */
+  if (mema == NULL || memb == NULL) {
+    return NULL;
+  }
+  mchunkptr pa = mem2chunk(mema);
+  mchunkptr pb = mem2chunk(memb);
+
+#if FOOTERS
+  mstate fm = get_mstate_for(pa);
+#else /* FOOTERS */
+  mstate fm = (mstate)msp;
+#endif /* FOOTERS */
+  if (!ok_magic(fm)) {
+    USAGE_ERROR_ACTION(fm, pa);
+    return NULL;
+  }
+  check_inuse_chunk(fm, pa);
+  if (RTCHECK(ok_address(fm, pa) && ok_cinuse(pa))) {
+    if (next_chunk(pa) != pb) {
+      /* Since pb may not be in fm, we can't check ok_address(fm, pb);
+         since ok_cinuse(pb) would be unsafe before an address check,
+         return NULL rather than invoke USAGE_ERROR_ACTION if pb is not
+         in use or is a bogus address.
+       */
+      return NULL;
+    }
+    /* Since b follows a, they share the mspace. */
+#if FOOTERS
+    assert(fm == get_mstate_for(pb));
+#endif /* FOOTERS */
+    check_inuse_chunk(fm, pb);
+    if (RTCHECK(ok_address(fm, pb) && ok_cinuse(pb))) {
+      size_t sz = chunksize(pb);
+      pa->head += sz;
+      /* Make sure pa still passes. */
+      check_inuse_chunk(fm, pa);
+      return mema;
+    }
+    else {
+      USAGE_ERROR_ACTION(fm, pb);
+      return NULL;
+    }
+  }
+  else {
+    USAGE_ERROR_ACTION(fm, pa);
+    return NULL;
+  }
+}
+#endif /* ANDROID */
+
 void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) {
   mstate ms = (mstate)msp;
   if (!ok_magic(ms)) {
diff --git a/libc/bionic/dlmalloc.h b/libc/bionic/dlmalloc.h
index 75b5e1f..e5f7d4a 100644
--- a/libc/bionic/dlmalloc.h
+++ b/libc/bionic/dlmalloc.h
@@ -547,6 +547,21 @@
 void* mspace_realloc(mspace msp, void* mem, size_t newsize);
 
 /*
+  mspace_merge_objects will merge allocated memory mema and memb
+  together, provided memb immediately follows mema.  It is roughly as
+  if memb has been freed and mema has been realloced to a larger size.
+  On successfully merging, mema will be returned. If either argument
+  is null or memb does not immediately follow mema, null will be
+  returned.
+
+  Both mema and memb should have been previously allocated using
+  malloc or a related routine such as realloc. If either mema or memb
+  was not malloced or was previously freed, the result is undefined,
+  but like mspace_free, the default is to abort the program.
+*/
+void* mspace_merge_objects(mspace msp, void* mema, void* memb);
+
+/*
   mspace_calloc behaves as calloc, but operates within
   the given space.
 */
diff --git a/libc/bionic/eabi.c b/libc/bionic/eabi.c
index f212d05..a5f6627 100644
--- a/libc/bionic/eabi.c
+++ b/libc/bionic/eabi.c
@@ -28,15 +28,24 @@
 #include <stddef.h>
 #include <string.h>
 
+extern int  __cxa_atexit(void (*)(void*), void*, void* );
+
 void* __dso_handle = 0;
 
+/* The "C++ ABI for ARM" document states that static C++ constructors,
+ * which are called from the .init_array, should manually call
+ * __aeabi_atexit() to register static destructors explicitely.
+ *
+ * Note that 'dso_handle' is the address of a magic linker-generate
+ * variable from the shared object that contains the constructor/destructor
+ */
+
 /* Make this a weak symbol to avoid a multiple definition error when linking
  * with libstdc++-v3.  */
 int __attribute__((weak))
 __aeabi_atexit (void *object, void (*destructor) (void *), void *dso_handle)
 {
-    //return __cxa_atexit(destructor, object, dso_handle);
-    return 0;
+    return __cxa_atexit(destructor, object, dso_handle);
 }
 
 
diff --git a/libc/bionic/libc_init_common.c b/libc/bionic/libc_init_common.c
index de4919d..d78d673 100644
--- a/libc/bionic/libc_init_common.c
+++ b/libc/bionic/libc_init_common.c
@@ -39,23 +39,6 @@
 #include <bionic_tls.h>
 #include <errno.h>
 
-extern void _init(void);
-extern void _fini(void);
-
-static void call_array(void(**list)())
-{
-    // First element is -1, list is null-terminated
-    while (*++list) {
-        (*list)();
-    }
-}
-
-static void __bionic_do_global_dtors(structors_array_t const * const p)
-{
-    call_array(p->fini_array);
-    //_fini();
-}
-
 extern unsigned __get_sp(void);
 extern pid_t    gettid(void);
 
@@ -69,23 +52,19 @@
 
 int __system_properties_init(void);
 
-void __libc_init_common(uintptr_t *elfdata,
-                       void (*onexit)(void),
-                       int (*slingshot)(int, char**, char**),
-                       structors_array_t const * const structors,
-                       void (*pre_ctor_hook)())
+void __libc_init_common(uintptr_t *elfdata)
 {
-    pthread_internal_t thread;
-    pthread_attr_t thread_attr;
-    void *tls_area[BIONIC_TLS_SLOTS];
-    int argc;
-    char **argv, **envp, **envend;
-    struct auxentry *auxentry;
-    unsigned int page_size = 0, page_shift = 0;
+    int     argc = *elfdata;
+    char**  argv = (char**)(elfdata + 1);
+    char**  envp = argv + argc + 1;
 
-    /* The main thread's stack has empirically shown to be 84k */
+    pthread_attr_t             thread_attr;
+    static pthread_internal_t  thread;
+    static void*               tls_area[BIONIC_TLS_SLOTS];
+
+    /* setup pthread runtime and maint thread descriptor */
     unsigned stacktop = (__get_sp() & ~(PAGE_SIZE - 1)) + PAGE_SIZE;
-    unsigned stacksize = 128 * 1024; //84 * 1024;
+    unsigned stacksize = 128 * 1024;
     unsigned stackbottom = stacktop - stacksize;
 
     pthread_attr_init(&thread_attr);
@@ -93,30 +72,15 @@
     _init_thread(&thread, gettid(), &thread_attr, (void*)stackbottom);
     __init_tls(tls_area, &thread);
 
-    argc = (int) *elfdata++;
-    argv = (char**) elfdata;
-    envp = argv+(argc+1);
-    environ = envp;
-
-    __progname = argv[0] ? argv[0] : "<unknown>";
-
+    /* clear errno - requires TLS area */
     errno = 0;
 
+    /* set program name */
+    __progname = argv[0] ? argv[0] : "<unknown>";
+
+    /* setup environment pointer */
+    environ = envp;
+
+    /* setup system properties - requires environment */
     __system_properties_init();
-
-    if (pre_ctor_hook) pre_ctor_hook();
-
-    // XXX: we should execute the .fini_array upon exit
-
-    // pre-init array.
-    // XXX: I'm not sure what's the different with the init array.
-    call_array(structors->preinit_array);
-
-    // for compatibility with non-eabi binary, call the .ctors section
-    call_array(structors->ctors_array);
-
-    // call static constructors
-    call_array(structors->init_array);
-
-    exit(slingshot(argc, argv, envp));
 }
diff --git a/libc/bionic/libc_init_common.h b/libc/bionic/libc_init_common.h
index bbc82e4..8663c61 100644
--- a/libc/bionic/libc_init_common.h
+++ b/libc/bionic/libc_init_common.h
@@ -38,10 +38,6 @@
     void (**ctors_array)(void);
 } structors_array_t;
 
-extern __noreturn void __libc_init_common(uintptr_t *elfdata,
-                       void (*onexit)(void),
-                       int (*slingshot)(int, char**, char**),
-                       structors_array_t const * const structors,
-                       void (*pre_ctor_hook)());
+extern void __libc_init_common(uintptr_t *elfdata);
 
 #endif
diff --git a/libc/bionic/libc_init_dynamic.c b/libc/bionic/libc_init_dynamic.c
index 8cf24b4..b479b27 100644
--- a/libc/bionic/libc_init_dynamic.c
+++ b/libc/bionic/libc_init_dynamic.c
@@ -26,41 +26,81 @@
  * SUCH DAMAGE.
  */
 /*
- * libc_init_static.c
+ * libc_init_dynamic.c
  *
- * This function takes the raw data block set up by the ELF loader
- * in the kernel and parses it.  It is invoked by crt0.S which makes
- * any necessary adjustments and passes calls this function using
- * the standard C calling convention.
+ * This source files provides two important functions for dynamic
+ * executables:
  *
- * The arguments are:
- *  uintptr_t *elfdata	 -- The ELF loader data block; usually from the stack.
- *                          Basically a pointer to argc.
- *  void (*onexit)(void) -- Function to install into onexit
+ * - a C runtime initializer (__libc_preinit), which is called by
+ *   the dynamic linker when libc.so is loaded. This happens before
+ *   any other initializer (e.g. static C++ constructors in other
+ *   shared libraries the program depends on).
+ *
+ * - a program launch function (__libc_init), which is called after
+ *   all dynamic linking has been performed. Technically, it is called
+ *   from arch-$ARCH/bionic/crtbegin_dynamic.S which is itself called
+ *   by the dynamic linker after all libraries have been loaded and
+ *   initialized.
  */
 
-/*
- * Several Linux ABIs don't pass the onexit pointer, and the ones that
- * do never use it.  Therefore, unless USE_ONEXIT is defined, we just
- * ignore the onexit pointer.
- */
-/* #define USE_ONEXIT */
-
 #include <stddef.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <stdint.h>
 #include <elf.h>
-#include "pthread_internal.h"
 #include "atexit.h"
 #include "libc_init_common.h"
+#include <bionic_tls.h>
 
 extern void malloc_debug_init();
 
+/* We flag the __libc_preinit function as a constructor to ensure
+ * that its address is listed in libc.so's .init_array section.
+ * This ensures that the function is called by the dynamic linker
+ * as soon as the shared library is loaded.
+ */
+void __attribute__((constructor)) __libc_prenit(void);
+
+void __libc_prenit(void)
+{
+    /* Read the ELF data pointer form a special slot of the
+     * TLS area, then call __libc_init_common with it.
+     *
+     * Note that:
+     * - we clear the slot so no other initializer sees its value.
+     * - __libc_init_common() will change the TLS area so the old one
+     *   won't be accessible anyway.
+     */
+    void**      tls_area = (void**)__get_tls();
+    unsigned*   elfdata   = tls_area[TLS_SLOT_BIONIC_PREINIT];
+
+    tls_area[TLS_SLOT_BIONIC_PREINIT] = NULL;
+
+    __libc_init_common(elfdata);
+
+#ifdef MALLOC_LEAK_CHECK
+    /* setup malloc leak checker, requires system properties */
+    extern void malloc_debug_init(void);
+    malloc_debug_init();
+#endif
+
+}
+
 __noreturn void __libc_init(uintptr_t *elfdata,
                        void (*onexit)(void),
                        int (*slingshot)(int, char**, char**),
                        structors_array_t const * const structors)
 {
-    __libc_init_common(elfdata, onexit, slingshot, structors, malloc_debug_init);
+    /* When we reach this point, all initializers have been already
+     * run by the dynamic linker, so ignore 'structors'.
+     */
+    int     argc = (int)*elfdata;
+    char**  argv = (char**)(elfdata + 1);
+    char**  envp = argv + argc + 1;
+
+    /* Several Linux ABIs don't pass the onexit pointer, and the ones that
+     * do never use it.  Therefore, we ignore it.
+     */
+
+    exit(slingshot(argc, argv, envp));
 }
diff --git a/libc/bionic/libc_init_static.c b/libc/bionic/libc_init_static.c
index ec463f7..e6264bb 100644
--- a/libc/bionic/libc_init_static.c
+++ b/libc/bionic/libc_init_static.c
@@ -28,24 +28,15 @@
 /*
  * libc_init_static.c
  *
- * This function takes the raw data block set up by the ELF loader
- * in the kernel and parses it.  It is invoked by crt0.S which makes
- * any necessary adjustments and passes calls this function using
- * the standard C calling convention.
+ * The program startup function __libc_init() defined here is
+ * used for static executables only (i.e. those that don't depend
+ * on shared libraries). It is called from arch-$ARCH/bionic/crtbegin_static.S
+ * which is directly invoked by the kernel when the program is launched.
  *
- * The arguments are:
- *  uintptr_t *elfdata	 -- The ELF loader data block; usually from the stack.
- *                          Basically a pointer to argc.
- *  void (*onexit)(void) -- Function to install into onexit
+ * The 'structors' parameter contains pointers to various initializer
+ * arrays that must be run before the program's 'main' routine is launched.
  */
 
-/*
- * Several Linux ABIs don't pass the onexit pointer, and the ones that
- * do never use it.  Therefore, unless USE_ONEXIT is defined, we just
- * ignore the onexit pointer.
- */
-/* #define USE_ONEXIT */
-
 #include <stddef.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -58,19 +49,47 @@
 #include <bionic_tls.h>
 #include <errno.h>
 
+static void call_array(void(**list)())
+{
+    // First element is -1, list is null-terminated
+    while (*++list) {
+        (*list)();
+    }
+}
+
 __noreturn void __libc_init(uintptr_t *elfdata,
                        void (*onexit)(void),
                        int (*slingshot)(int, char**, char**),
                        structors_array_t const * const structors)
 {
-/* 
- * To enable malloc checks for statically linked programs, add
- * "WITH_MALLOC_CHECK_LIBC_A := true" in device/buildspec.mk
- */
+    int  argc;
+    char **argv, **envp;
+
+    /* Initialize the C runtime environment */
+    __libc_init_common(elfdata);
+
 #ifdef MALLOC_LEAK_CHECK
-    extern void malloc_debug_init();
-    __libc_init_common(elfdata, onexit, slingshot, structors, malloc_debug_init);
-#else
-    __libc_init_common(elfdata, onexit, slingshot, structors, NULL);
+    /* setup malloc leak checker, requires system properties */
+    extern void malloc_debug_init(void);
+    malloc_debug_init();
 #endif
+
+    /* Several Linux ABIs don't pass the onexit pointer, and the ones that
+     * do never use it.  Therefore, we ignore it.
+     */
+
+    /* pre-init array. */
+    call_array(structors->preinit_array);
+
+    /* .ctors section initializers, for non-arm-eabi ABIs */
+    call_array(structors->ctors_array);
+
+    // call static constructors
+    call_array(structors->init_array);
+
+    argc = (int) *elfdata;
+    argv = (char**)(elfdata + 1);
+    envp = argv + argc + 1;
+
+    exit(slingshot(argc, argv, envp));
 }
diff --git a/libc/bionic/logd_write.c b/libc/bionic/logd_write.c
index 7c3608b..3336428 100644
--- a/libc/bionic/logd_write.c
+++ b/libc/bionic/logd_write.c
@@ -46,62 +46,80 @@
 #define LOG_BUF_SIZE	1024
 
 typedef enum {
-    LOG_ID_MAIN = 0,
+    LOG_ID_NONE = 0,
+    LOG_ID_MAIN,
     LOG_ID_RADIO,
     LOG_ID_MAX
 } log_id_t;
 
-static int __write_to_log_init(log_id_t, struct iovec *vec);
-static int (*write_to_log)(log_id_t, struct iovec *vec) = __write_to_log_init;
+/* logger handles writing to object, pointed by log channel id */
+typedef int (*logger_function_t)(log_id_t log_id, struct iovec *vec);
+
+typedef struct {
+    logger_function_t logger;
+    int               fd;
+    const char        *path;
+} log_channel_t;
+
+static int __write_to_log_init(log_id_t log_id, struct iovec *vec);
+static int __write_to_log_null(log_id_t log_id, struct iovec *vec);
+
 static pthread_mutex_t log_init_lock = PTHREAD_MUTEX_INITIALIZER;
 
-static int log_fds[(int)LOG_ID_MAX] = { -1, -1 };
+log_channel_t log_channels[LOG_ID_MAX] = {
+    { __write_to_log_null, -1, NULL },
+    { __write_to_log_init, -1, "/dev/"LOGGER_LOG_MAIN },
+    { __write_to_log_init, -1, "/dev/"LOGGER_LOG_RADIO }
+};
 
-static int __write_to_log_null(log_id_t log_fd, struct iovec *vec)
+static int __write_to_log_null(log_id_t log_id, struct iovec *vec)
 {
-    return -1;
+    /* 
+     * ALTERED behaviour from previous version
+     * always returns successful result
+     */
+    int    i = 0;
+    size_t res = 0;
+
+    for ( ; i < 3; ++i) {
+        res += vec[i].iov_len;
+    }
+
+    return (int)res;
 }
 
+/*
+ *  it's supposed, that log_id contains valid id always.
+ *  this check must be performed in higher level functions
+ */
 static int __write_to_log_kernel(log_id_t log_id, struct iovec *vec)
 {
     ssize_t ret;
-    int log_fd;
-
-    if ((int)log_id >= 0 && (int)log_id < (int)LOG_ID_MAX) {
-        log_fd = log_fds[(int)log_id];
-    } else {
-        return EBADF;
-    }
 
     do {
-        ret = writev(log_fd, vec, 3);
-    } while (ret < 0 && errno == EINTR);
+        ret = writev(log_channels[log_id].fd, vec, 3);
+    } while ((ret < 0) && (errno == EINTR));
 
     return ret;
 }
 
 static int __write_to_log_init(log_id_t log_id, struct iovec *vec)
 {
-    pthread_mutex_lock(&log_init_lock);
+    if ((LOG_ID_NONE < log_id) && (log_id < LOG_ID_MAX)) {
+        pthread_mutex_lock(&log_init_lock);
 
-    if (write_to_log == __write_to_log_init) {
-        log_fds[LOG_ID_MAIN] = open("/dev/"LOGGER_LOG_MAIN, O_WRONLY);
-        log_fds[LOG_ID_RADIO] = open("/dev/"LOGGER_LOG_RADIO, O_WRONLY);
+        int fd = open(log_channels[log_id].path, O_WRONLY);
 
-        write_to_log = __write_to_log_kernel;
+        log_channels[log_id].logger =
+            (fd < 0) ? __write_to_log_null : __write_to_log_kernel;
 
-        if (log_fds[LOG_ID_MAIN] < 0 || log_fds[LOG_ID_RADIO] < 0) {
-            close(log_fds[LOG_ID_MAIN]);
-            close(log_fds[LOG_ID_RADIO]);
-            log_fds[LOG_ID_MAIN] = -1;
-            log_fds[LOG_ID_RADIO] = -1;
-            write_to_log = __write_to_log_null;
-        }
+        pthread_mutex_unlock(&log_init_lock);
+
+        return log_channels[log_id].logger(log_id, vec);
     }
 
-    pthread_mutex_unlock(&log_init_lock);
-
-    return write_to_log(log_id, vec);
+    /* log_id is invalid */
+    return -1;
 }
 
 static int __android_log_write(int prio, const char *tag, const char *msg)
@@ -109,7 +127,7 @@
     struct iovec vec[3];
     log_id_t log_id = LOG_ID_MAIN;
 
-    if (!tag)
+    if (tag == NULL)
         tag = "";
 
     if (!strcmp(tag, "HTC_RIL"))
@@ -122,14 +140,14 @@
     vec[2].iov_base   = (void *) msg;
     vec[2].iov_len    = strlen(msg) + 1;
 
-    return write_to_log(log_id, vec);
+    return log_channels[log_id].logger(log_id, vec);
 }
 
 
-static int __android_log_vprint(int prio, const char *tag, const char *fmt,
-				va_list ap)
+int __libc_android_log_vprint(int prio, const char *tag, const char *fmt,
+                              va_list ap)
 {
-    char buf[LOG_BUF_SIZE];    
+    char buf[LOG_BUF_SIZE];
 
     vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
 
@@ -139,7 +157,7 @@
 int __libc_android_log_print(int prio, const char *tag, const char *fmt, ...)
 {
     va_list ap;
-    char buf[LOG_BUF_SIZE];    
+    char buf[LOG_BUF_SIZE];
 
     va_start(ap, fmt);
     vsnprintf(buf, LOG_BUF_SIZE, fmt, ap);
diff --git a/libc/bionic/malloc_leak.c b/libc/bionic/malloc_leak.c
index a0aa2ae..305f954 100644
--- a/libc/bionic/malloc_leak.c
+++ b/libc/bionic/malloc_leak.c
@@ -91,7 +91,14 @@
 static HashTable gHashTable;
 
 // =============================================================================
-// output fucntions
+// log functions
+// =============================================================================
+
+#define debug_log(format, ...)  \
+    __libc_android_log_print(ANDROID_LOG_DEBUG, "malloc_leak", (format), ##__VA_ARGS__ )
+
+// =============================================================================
+// output functions
 // =============================================================================
 
 static int hash_entry_compare(const void* arg1, const void* arg2)
@@ -257,12 +264,6 @@
     uint32_t guard;
 };
 
-// =============================================================================
-// log funtions
-// =============================================================================
-
-#define debug_log(format, ...)  \
-    __libc_android_log_print(ANDROID_LOG_DEBUG, "malloc_leak", (format), ##__VA_ARGS__ )
 
 // =============================================================================
 // Hash Table functions
@@ -515,8 +516,8 @@
 
     tmp[0] = 0; // Need to initialize tmp[0] for the first strcat
     for (i=0 ; i<c; i++) {
-        sprintf(buf, "%2d: %08x\n", i, addrs[i]);
-        strcat(tmp, buf);
+        snprintf(buf, sizeof buf, "%2d: %08x\n", i, addrs[i]);
+        strlcat(tmp, buf, sizeof tmp);
     }
     __libc_android_log_print(ANDROID_LOG_ERROR, "libc", "call stack:\n%s", tmp);
 }
@@ -526,69 +527,90 @@
     return 1;
 }
 
+static void assert_log_message(const char* format, ...)
+{
+    va_list  args;
+
+    pthread_mutex_lock(&gAllocationsMutex);
+        gMallocDispatch = &gMallocEngineTable[INDEX_NORMAL];
+        va_start(args, format);
+        __libc_android_log_vprint(ANDROID_LOG_ERROR, "libc",
+                                format, args);
+        va_end(args);
+        dump_stack_trace();
+        if (gTrapOnError) {
+            __builtin_trap();
+        }
+        gMallocDispatch = &gMallocEngineTable[INDEX_MALLOC_CHECK];
+    pthread_mutex_unlock(&gAllocationsMutex);
+}
+
 static void assert_valid_malloc_pointer(void* mem)
 {
     if (mem && !is_valid_malloc_pointer(mem)) {
-        pthread_mutex_lock(&gAllocationsMutex);
-        gMallocDispatch = &gMallocEngineTable[INDEX_NORMAL];
-            __libc_android_log_print(ANDROID_LOG_ERROR, "libc",
-                    "*** MALLOC CHECK: buffer %p, is not a valid "
-                    "malloc pointer (are you mixing up new/delete "
-                    "and malloc/free?)", mem);
-            dump_stack_trace();
-                if (gTrapOnError) {
-                    __builtin_trap();
-                }
-        gMallocDispatch = &gMallocEngineTable[INDEX_MALLOC_CHECK];
-        pthread_mutex_unlock(&gAllocationsMutex);
+        assert_log_message(
+            "*** MALLOC CHECK: buffer %p, is not a valid "
+            "malloc pointer (are you mixing up new/delete "
+            "and malloc/free?)", mem);
     }
 }
 
-static void chk_out_of_bounds_check__locked(void* buffer, size_t size)
+/* Check that a given address corresponds to a guarded block,
+ * and returns its original allocation size in '*allocated'.
+ * 'func' is the capitalized name of the caller function.
+ * Returns 0 on success, or -1 on failure.
+ * NOTE: Does not return if gTrapOnError is set.
+ */
+static int chk_mem_check(void*       mem,
+                         size_t*     allocated,
+                         const char* func)
 {
-    int i;
-    char* buf = (char*)buffer - CHK_SENTINEL_HEAD_SIZE;
+    char*  buffer;
+    size_t offset, bytes;
+    int    i;
+    char*  buf;
+
+    /* first check the bytes in the sentinel header */
+    buf = (char*)mem - CHK_SENTINEL_HEAD_SIZE;
     for (i=0 ; i<CHK_SENTINEL_HEAD_SIZE ; i++) {
         if (buf[i] != CHK_SENTINEL_VALUE) {
-            gMallocDispatch = &gMallocEngineTable[INDEX_NORMAL];
-            __libc_android_log_print(ANDROID_LOG_ERROR, "libc",
-                    "*** MALLOC CHECK: buffer %p, size=%lu, "
-                    "corrupted %d bytes before allocation",
-                    buffer, size, CHK_SENTINEL_HEAD_SIZE-i);
-            dump_stack_trace();
-            if (gTrapOnError) {
-                __builtin_trap();
-            }
-            gMallocDispatch = &gMallocEngineTable[INDEX_MALLOC_CHECK];
+            assert_log_message( 
+                "*** %s CHECK: buffer %p "
+                "corrupted %d bytes before allocation",
+                func, mem, CHK_SENTINEL_HEAD_SIZE-i);
+            return -1;
         }
     }
-    buf = (char*)buffer + size;
+
+    /* then the ones in the sentinel trailer */
+    buffer = (char*)mem - CHK_SENTINEL_HEAD_SIZE;
+    offset = dlmalloc_usable_size(buffer) - sizeof(size_t);
+    bytes  = *(size_t *)(buffer + offset);
+
+    buf = (char*)mem + bytes;
     for (i=CHK_SENTINEL_TAIL_SIZE-1 ; i>=0 ; i--) {
         if (buf[i] != CHK_SENTINEL_VALUE) {
-            gMallocDispatch = &gMallocEngineTable[INDEX_NORMAL];
-            __libc_android_log_print(ANDROID_LOG_ERROR, "libc",
-                    "*** MALLOC CHECK: buffer %p, size=%lu, "
-                    "corrupted %d bytes after allocation",
-                    buffer, size, i+1);
-            dump_stack_trace();
-            if (gTrapOnError) {
-                __builtin_trap();
-            }
-            gMallocDispatch = &gMallocEngineTable[INDEX_MALLOC_CHECK];
+            assert_log_message( 
+                "*** %s CHECK: buffer %p, size=%lu, "
+                "corrupted %d bytes after allocation",
+                func, buffer, bytes, i+1);
+            return -1;
         }
     }
+
+    *allocated = bytes;
+    return 0;
 }
 
+
 void* chk_malloc(size_t bytes)
 {
     char* buffer = (char*)dlmalloc(bytes + CHK_OVERHEAD_SIZE);
     if (buffer) {
-        pthread_mutex_lock(&gAllocationsMutex);
-            memset(buffer, CHK_SENTINEL_VALUE, bytes + CHK_OVERHEAD_SIZE);
-            size_t offset = dlmalloc_usable_size(buffer) - sizeof(size_t);
-            *(size_t *)(buffer + offset) = bytes;
-            buffer += CHK_SENTINEL_HEAD_SIZE;
-        pthread_mutex_unlock(&gAllocationsMutex);
+        memset(buffer, CHK_SENTINEL_VALUE, bytes + CHK_OVERHEAD_SIZE);
+        size_t offset = dlmalloc_usable_size(buffer) - sizeof(size_t);
+        *(size_t *)(buffer + offset) = bytes;
+        buffer += CHK_SENTINEL_HEAD_SIZE;
     }
     return buffer;
 }
@@ -597,14 +619,14 @@
 {
     assert_valid_malloc_pointer(mem);
     if (mem) {
-        pthread_mutex_lock(&gAllocationsMutex);
-            char* buffer = (char*)mem - CHK_SENTINEL_HEAD_SIZE;
-            size_t offset = dlmalloc_usable_size(buffer) - sizeof(size_t);
-            size_t bytes = *(size_t *)(buffer + offset);
-            chk_out_of_bounds_check__locked(mem, bytes);
-        pthread_mutex_unlock(&gAllocationsMutex);
-        memset(buffer, CHK_FILL_FREE, bytes);
-        dlfree(buffer);
+        size_t  size;
+        char*   buffer;
+
+        if (chk_mem_check(mem, &size, "FREE") == 0) {
+            buffer = (char*)mem - CHK_SENTINEL_HEAD_SIZE;
+            memset(buffer, CHK_FILL_FREE, size + CHK_OVERHEAD_SIZE);
+            dlfree(buffer);
+        }
     }
 }
 
@@ -628,19 +650,20 @@
 
 void* chk_realloc(void* mem, size_t bytes)
 {
+    char*   buffer;
+    int     ret;
+    size_t  old_bytes = 0;
+
     assert_valid_malloc_pointer(mem);
+
+    if (mem != NULL && chk_mem_check(mem, &old_bytes, "REALLOC") < 0)
+        return NULL;
+
     char* new_buffer = chk_malloc(bytes);
     if (mem == NULL) {
         return new_buffer;
     }
 
-    pthread_mutex_lock(&gAllocationsMutex);
-        char* buffer = (char*)mem - CHK_SENTINEL_HEAD_SIZE;
-        size_t offset = dlmalloc_usable_size(buffer) - sizeof(size_t);
-        size_t old_bytes = *(size_t *)(buffer + offset);
-        chk_out_of_bounds_check__locked(mem, old_bytes);
-    pthread_mutex_unlock(&gAllocationsMutex);
-
     if (new_buffer) {
         size_t size = (bytes < old_bytes)?(bytes):(old_bytes);
         memcpy(new_buffer, mem, size);
diff --git a/libc/bionic/pthread.c b/libc/bionic/pthread.c
index ec3c459..d2c81a3 100644
--- a/libc/bionic/pthread.c
+++ b/libc/bionic/pthread.c
@@ -1215,22 +1215,12 @@
                             pthread_mutex_t * mutex,
                             unsigned msecs)
 {
-    int oldvalue;
     struct timespec ts;
-    int status;
 
     ts.tv_sec = msecs / 1000;
     ts.tv_nsec = (msecs % 1000) * 1000000;
 
-    oldvalue = cond->value;
-
-    pthread_mutex_unlock(mutex);
-    status = __futex_wait(&cond->value, oldvalue, &ts);
-    pthread_mutex_lock(mutex);
-
-    if(status == (-ETIMEDOUT)) return ETIMEDOUT;
-
-    return 0;
+    return __pthread_cond_timedwait_relative(cond, mutex, &ts);
 }
 
 
diff --git a/libc/docs/ISSUES.TXT b/libc/docs/ISSUES.TXT
new file mode 100644
index 0000000..b53eb16
--- /dev/null
+++ b/libc/docs/ISSUES.TXT
@@ -0,0 +1,20 @@
+Bionic C Library Issues:
+========================
+
+This document lists important known issues of various releases
+of the Bionic C library. Note that these differ from specific
+implementation choices that are documented in the OVERVIEW.TXT
+document.
+
+Currently known issues:
+-----------------------
+
+- The C library initialization will improperly run static C++
+  constructors located in shared libraries twice.
+
+Android-1.5 issues:
+-------------------
+
+- getservbyname() returned the port number in the s_port field of
+  the 'struct servent' structure in host-byte-order, instead of
+  network-byte-order.
diff --git a/libc/include/stdint.h b/libc/include/stdint.h
index 39a8ab8..237baa2 100644
--- a/libc/include/stdint.h
+++ b/libc/include/stdint.h
@@ -46,13 +46,17 @@
 #  define  __STDINT_MACROS
 #endif
 
+#if !defined __STRICT_ANSI__ || __STDC_VERSION__ >= 199901L
+#  define __STDC_INT64__
+#endif
+
 typedef __int8_t      int8_t;
 typedef __uint8_t     uint8_t;
 typedef __int16_t     int16_t;
 typedef __uint16_t    uint16_t;
 typedef __int32_t     int32_t;
 typedef __uint32_t    uint32_t;
-#if !defined(__STRICT_ANSI__)
+#if defined(__STDC_INT64__)
 typedef __int64_t     int64_t;
 typedef __uint64_t    uint64_t;
 #endif
@@ -157,7 +161,7 @@
 #  define UINT_FAST32_C(c) UINT32_C(c)
 #endif
 
-#if !defined(__STRICT_ANSI__)
+#if defined(__STDC_INT64__)
 /*
  *  int64_t
  */
@@ -198,7 +202,7 @@
 #  define __PRIFAST_RANK ""
 #  define __PRIPTR_RANK  ""
 
-#endif /* !__STRICT_ANSI__ */
+#endif /* __STDC_INT64__ */
 
 /*
  * intptr_t & uintptr_t
@@ -221,7 +225,7 @@
  *  intmax_t & uintmax_t
  */
 
-#if !defined(__STRICT_ANSI__)
+#if defined(__STDC_INT64__)
 
 typedef uint64_t uintmax_t;
 typedef int64_t  intmax_t;
@@ -233,7 +237,7 @@
 #define INTMAX_C(c)	INT64_C(c)
 #define UINTMAX_C(c)	UINT64_C(c)
 
-#else /* __STRICT_ANSI__ */
+#else /* !__STDC_INT64__ */
 
 typedef uint32_t  uintmax_t;
 typedef int32_t   intmax_t;
@@ -245,7 +249,7 @@
 #define INTMAX_C(c)	INT32_C(c)
 #define UINTMAX_C(c)	UINT32_C(c)
 
-#endif /* __STRICT_ANSI__ */
+#endif /* !__STDC_INT64__ */
 
 
 /* size_t is defined by the GCC-specific <stddef.h> */
diff --git a/libc/include/strings.h b/libc/include/strings.h
index 1f73e21..fee7dc4 100644
--- a/libc/include/strings.h
+++ b/libc/include/strings.h
@@ -39,6 +39,7 @@
 #ifndef _STRINGS_H_
 #define _STRINGS_H_
 
+#include <sys/types.h>
 #include <sys/cdefs.h>
 
 __BEGIN_DECLS
diff --git a/libc/include/sys/stat.h b/libc/include/sys/stat.h
index 23ab5ae..091ee6d 100644
--- a/libc/include/sys/stat.h
+++ b/libc/include/sys/stat.h
@@ -71,6 +71,13 @@
     unsigned long long  st_ino;
 };
 
+/* For compatibility with GLibc, we provide macro aliases
+ * for the non-Posix nano-seconds accessors.
+ */
+#define  st_atimensec  st_atime_nsec
+#define  st_mtimensec  st_mtime_nsec
+#define  st_ctimensec  st_ctime_nsec
+
 extern int    chmod(const char *, mode_t);
 extern int    fchmod(int, mode_t);
 extern int    mkdir(const char *, mode_t);
diff --git a/libc/kernel/common/linux/if_pppolac.h b/libc/kernel/common/linux/if_pppolac.h
new file mode 100644
index 0000000..bf6eba0
--- /dev/null
+++ b/libc/kernel/common/linux/if_pppolac.h
@@ -0,0 +1,29 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ ***   This header was automatically generated from a Linux kernel header
+ ***   of the same name, to make information necessary for userspace to
+ ***   call into the kernel available to libc.  It contains only constants,
+ ***   structures, and macros generated from the original header, and thus,
+ ***   contains no copyrightable information.
+ ***
+ ****************************************************************************
+ ****************************************************************************/
+#ifndef __LINUX_IF_PPPOLAC_H
+#define __LINUX_IF_PPPOLAC_H
+
+#include <linux/socket.h>
+#include <linux/types.h>
+
+#define PX_PROTO_OLAC 2
+
+struct sockaddr_pppolac {
+ sa_family_t sa_family;
+ unsigned int sa_protocol;
+ int udp_socket;
+ struct __attribute__((packed)) {
+ __u16 tunnel, session;
+ } local, remote;
+} __attribute__((packed));
+
+#endif
diff --git a/libc/kernel/common/linux/if_pppopns.h b/libc/kernel/common/linux/if_pppopns.h
new file mode 100644
index 0000000..ac75210
--- /dev/null
+++ b/libc/kernel/common/linux/if_pppopns.h
@@ -0,0 +1,28 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ ***   This header was automatically generated from a Linux kernel header
+ ***   of the same name, to make information necessary for userspace to
+ ***   call into the kernel available to libc.  It contains only constants,
+ ***   structures, and macros generated from the original header, and thus,
+ ***   contains no copyrightable information.
+ ***
+ ****************************************************************************
+ ****************************************************************************/
+#ifndef __LINUX_IF_PPPOPNS_H
+#define __LINUX_IF_PPPOPNS_H
+
+#include <linux/socket.h>
+#include <linux/types.h>
+
+#define PX_PROTO_OPNS 3
+
+struct sockaddr_pppopns {
+ sa_family_t sa_family;
+ unsigned int sa_protocol;
+ int tcp_socket;
+ __u16 local;
+ __u16 remote;
+} __attribute__((packed));
+
+#endif
diff --git a/libc/kernel/common/linux/ipsec.h b/libc/kernel/common/linux/ipsec.h
new file mode 100644
index 0000000..56acafa
--- /dev/null
+++ b/libc/kernel/common/linux/ipsec.h
@@ -0,0 +1,56 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ ***   This header was automatically generated from a Linux kernel header
+ ***   of the same name, to make information necessary for userspace to
+ ***   call into the kernel available to libc.  It contains only constants,
+ ***   structures, and macros generated from the original header, and thus,
+ ***   contains no copyrightable information.
+ ***
+ ****************************************************************************
+ ****************************************************************************/
+#ifndef _LINUX_IPSEC_H
+#define _LINUX_IPSEC_H
+
+#include <linux/pfkeyv2.h>
+
+#define IPSEC_PORT_ANY 0
+#define IPSEC_ULPROTO_ANY 255
+#define IPSEC_PROTO_ANY 255
+
+enum {
+ IPSEC_MODE_ANY = 0,
+ IPSEC_MODE_TRANSPORT = 1,
+ IPSEC_MODE_TUNNEL = 2,
+ IPSEC_MODE_BEET = 3
+};
+
+enum {
+ IPSEC_DIR_ANY = 0,
+ IPSEC_DIR_INBOUND = 1,
+ IPSEC_DIR_OUTBOUND = 2,
+ IPSEC_DIR_FWD = 3,
+ IPSEC_DIR_MAX = 4,
+ IPSEC_DIR_INVALID = 5
+};
+
+enum {
+ IPSEC_POLICY_DISCARD = 0,
+ IPSEC_POLICY_NONE = 1,
+ IPSEC_POLICY_IPSEC = 2,
+ IPSEC_POLICY_ENTRUST = 3,
+ IPSEC_POLICY_BYPASS = 4
+};
+
+enum {
+ IPSEC_LEVEL_DEFAULT = 0,
+ IPSEC_LEVEL_USE = 1,
+ IPSEC_LEVEL_REQUIRE = 2,
+ IPSEC_LEVEL_UNIQUE = 3
+};
+
+#define IPSEC_MANUAL_REQID_MAX 0x3fff
+
+#define IPSEC_REPLAYWSIZE 32
+
+#endif
diff --git a/libc/kernel/common/linux/msm_adsp.h b/libc/kernel/common/linux/msm_adsp.h
index 6f12707..b138a5d 100644
--- a/libc/kernel/common/linux/msm_adsp.h
+++ b/libc/kernel/common/linux/msm_adsp.h
@@ -14,7 +14,6 @@
 
 #include <linux/types.h>
 #include <linux/ioctl.h>
-#include <asm/sizes.h>
 
 #define ADSP_IOCTL_MAGIC 'q'
 
@@ -33,25 +32,32 @@
  uint8_t *data;
 };
 
-struct adsp_pmem_info_t {
+#define ADSP_IOCTL_ENABLE _IOR(ADSP_IOCTL_MAGIC, 1, unsigned)
+
+#define ADSP_IOCTL_DISABLE _IOR(ADSP_IOCTL_MAGIC, 2, unsigned)
+
+#define ADSP_IOCTL_DISABLE_ACK _IOR(ADSP_IOCTL_MAGIC, 3, unsigned)
+
+#define ADSP_IOCTL_WRITE_COMMAND _IOR(ADSP_IOCTL_MAGIC, 4, struct adsp_command_t *)
+
+#define ADSP_IOCTL_GET_EVENT _IOWR(ADSP_IOCTL_MAGIC, 5, struct adsp_event_data_t *)
+
+#define ADSP_IOCTL_SET_CLKRATE _IOR(ADSP_IOCTL_MAGIC, 6, unsigned)
+
+#define ADSP_IOCTL_DISABLE_EVENT_RSP _IOR(ADSP_IOCTL_MAGIC, 10, unsigned)
+
+struct adsp_pmem_info {
  int fd;
  void *vaddr;
 };
 
-#define ADSP_IOCTL_ENABLE   _IOR(ADSP_IOCTL_MAGIC, 1, unsigned)
+#define ADSP_IOCTL_REGISTER_PMEM _IOW(ADSP_IOCTL_MAGIC, 13, unsigned)
 
-#define ADSP_IOCTL_DISABLE   _IOR(ADSP_IOCTL_MAGIC, 2, unsigned)
+#define ADSP_IOCTL_UNREGISTER_PMEM _IOW(ADSP_IOCTL_MAGIC, 14, unsigned)
 
-#define ADSP_IOCTL_DISABLE_ACK   _IOR(ADSP_IOCTL_MAGIC, 3, unsigned)
+#define ADSP_IOCTL_ABORT_EVENT_READ _IOW(ADSP_IOCTL_MAGIC, 15, unsigned)
 
-#define ADSP_IOCTL_WRITE_COMMAND   _IOR(ADSP_IOCTL_MAGIC, 4, struct adsp_command_t *)
-
-#define ADSP_IOCTL_GET_EVENT   _IOWR(ADSP_IOCTL_MAGIC, 5, struct adsp_event_data_t *)
-
-#define ADSP_IOCTL_DISABLE_EVENT_RSP   _IOR(ADSP_IOCTL_MAGIC, 10, unsigned)
-
-#define ADSP_IOCTL_REGISTER_PMEM   _IOW(ADSP_IOCTL_MAGIC, 13, struct adsp_pmem_info *)
-
-#define ADSP_IOCTL_ABORT_EVENT_READ   _IOW(ADSP_IOCTL_MAGIC, 15, unsigned)
+#define ADSP_IOCTL_LINK_TASK _IOW(ADSP_IOCTL_MAGIC, 16, unsigned)
 
 #endif
+
diff --git a/libc/kernel/common/linux/msm_audio.h b/libc/kernel/common/linux/msm_audio.h
index 9ac58aa..eed5901 100644
--- a/libc/kernel/common/linux/msm_audio.h
+++ b/libc/kernel/common/linux/msm_audio.h
@@ -82,4 +82,3 @@
 #define SND_GET_ENDPOINT _IOWR(SND_IOCTL_MAGIC, 5, struct msm_snd_endpoint *)
 
 #endif
-
diff --git a/libc/kernel/common/linux/uinput.h b/libc/kernel/common/linux/uinput.h
new file mode 100644
index 0000000..b7a6add
--- /dev/null
+++ b/libc/kernel/common/linux/uinput.h
@@ -0,0 +1,67 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ ***   This header was automatically generated from a Linux kernel header
+ ***   of the same name, to make information necessary for userspace to
+ ***   call into the kernel available to libc.  It contains only constants,
+ ***   structures, and macros generated from the original header, and thus,
+ ***   contains no copyrightable information.
+ ***
+ ****************************************************************************
+ ****************************************************************************/
+#ifndef __UINPUT_H_
+#define __UINPUT_H_
+
+#include <linux/input.h>
+
+#define UINPUT_VERSION 3
+
+struct uinput_ff_upload {
+ int request_id;
+ int retval;
+ struct ff_effect effect;
+ struct ff_effect old;
+};
+
+struct uinput_ff_erase {
+ int request_id;
+ int retval;
+ int effect_id;
+};
+
+#define UINPUT_IOCTL_BASE 'U'
+#define UI_DEV_CREATE _IO(UINPUT_IOCTL_BASE, 1)
+#define UI_DEV_DESTROY _IO(UINPUT_IOCTL_BASE, 2)
+
+#define UI_SET_EVBIT _IOW(UINPUT_IOCTL_BASE, 100, int)
+#define UI_SET_KEYBIT _IOW(UINPUT_IOCTL_BASE, 101, int)
+#define UI_SET_RELBIT _IOW(UINPUT_IOCTL_BASE, 102, int)
+#define UI_SET_ABSBIT _IOW(UINPUT_IOCTL_BASE, 103, int)
+#define UI_SET_MSCBIT _IOW(UINPUT_IOCTL_BASE, 104, int)
+#define UI_SET_LEDBIT _IOW(UINPUT_IOCTL_BASE, 105, int)
+#define UI_SET_SNDBIT _IOW(UINPUT_IOCTL_BASE, 106, int)
+#define UI_SET_FFBIT _IOW(UINPUT_IOCTL_BASE, 107, int)
+#define UI_SET_PHYS _IOW(UINPUT_IOCTL_BASE, 108, char*)
+#define UI_SET_SWBIT _IOW(UINPUT_IOCTL_BASE, 109, int)
+
+#define UI_BEGIN_FF_UPLOAD _IOWR(UINPUT_IOCTL_BASE, 200, struct uinput_ff_upload)
+#define UI_END_FF_UPLOAD _IOW(UINPUT_IOCTL_BASE, 201, struct uinput_ff_upload)
+#define UI_BEGIN_FF_ERASE _IOWR(UINPUT_IOCTL_BASE, 202, struct uinput_ff_erase)
+#define UI_END_FF_ERASE _IOW(UINPUT_IOCTL_BASE, 203, struct uinput_ff_erase)
+
+#define EV_UINPUT 0x0101
+#define UI_FF_UPLOAD 1
+#define UI_FF_ERASE 2
+
+#define UINPUT_MAX_NAME_SIZE 80
+struct uinput_user_dev {
+ char name[UINPUT_MAX_NAME_SIZE];
+ struct input_id id;
+ int ff_effects_max;
+ int absmax[ABS_MAX + 1];
+ int absmin[ABS_MAX + 1];
+ int absfuzz[ABS_MAX + 1];
+ int absflat[ABS_MAX + 1];
+};
+#endif
+
diff --git a/libc/kernel/common/media/msm_camera.h b/libc/kernel/common/media/msm_camera.h
new file mode 100644
index 0000000..6596d6b
--- /dev/null
+++ b/libc/kernel/common/media/msm_camera.h
@@ -0,0 +1,356 @@
+/****************************************************************************
+ ****************************************************************************
+ ***
+ ***   This header was automatically generated from a Linux kernel header
+ ***   of the same name, to make information necessary for userspace to
+ ***   call into the kernel available to libc.  It contains only constants,
+ ***   structures, and macros generated from the original header, and thus,
+ ***   contains no copyrightable information.
+ ***
+ ****************************************************************************
+ ****************************************************************************/
+#ifndef __LINUX_MSM_CAMERA_H
+#define __LINUX_MSM_CAMERA_H
+
+#include <linux/types.h>
+#include <asm/sizes.h>
+#include <linux/ioctl.h>
+
+#define MSM_CAM_IOCTL_MAGIC 'm'
+
+#define MSM_CAM_IOCTL_GET_SENSOR_INFO   _IOR(MSM_CAM_IOCTL_MAGIC, 1, struct msm_camsensor_info *)
+
+#define MSM_CAM_IOCTL_REGISTER_PMEM   _IOW(MSM_CAM_IOCTL_MAGIC, 2, struct msm_pmem_info *)
+
+#define MSM_CAM_IOCTL_UNREGISTER_PMEM   _IOW(MSM_CAM_IOCTL_MAGIC, 3, unsigned)
+
+#define MSM_CAM_IOCTL_CTRL_COMMAND   _IOW(MSM_CAM_IOCTL_MAGIC, 4, struct msm_ctrl_cmd *)
+
+#define MSM_CAM_IOCTL_CONFIG_VFE   _IOW(MSM_CAM_IOCTL_MAGIC, 5, struct msm_camera_vfe_cfg_cmd *)
+
+#define MSM_CAM_IOCTL_GET_STATS   _IOR(MSM_CAM_IOCTL_MAGIC, 6, struct msm_camera_stats_event_ctrl *)
+
+#define MSM_CAM_IOCTL_GETFRAME   _IOR(MSM_CAM_IOCTL_MAGIC, 7, struct msm_camera_get_frame *)
+
+#define MSM_CAM_IOCTL_ENABLE_VFE   _IOW(MSM_CAM_IOCTL_MAGIC, 8, struct camera_enable_cmd *)
+
+#define MSM_CAM_IOCTL_CTRL_CMD_DONE   _IOW(MSM_CAM_IOCTL_MAGIC, 9, struct camera_cmd *)
+
+#define MSM_CAM_IOCTL_CONFIG_CMD   _IOW(MSM_CAM_IOCTL_MAGIC, 10, struct camera_cmd *)
+
+#define MSM_CAM_IOCTL_DISABLE_VFE   _IOW(MSM_CAM_IOCTL_MAGIC, 11, struct camera_enable_cmd *)
+
+#define MSM_CAM_IOCTL_PAD_REG_RESET2   _IOW(MSM_CAM_IOCTL_MAGIC, 12, struct camera_enable_cmd *)
+
+#define MSM_CAM_IOCTL_VFE_APPS_RESET   _IOW(MSM_CAM_IOCTL_MAGIC, 13, struct camera_enable_cmd *)
+
+#define MSM_CAM_IOCTL_RELEASE_FRAME_BUFFER   _IOW(MSM_CAM_IOCTL_MAGIC, 14, struct camera_enable_cmd *)
+
+#define MSM_CAM_IOCTL_RELEASE_STATS_BUFFER   _IOW(MSM_CAM_IOCTL_MAGIC, 15, struct msm_stats_buf *)
+
+#define MSM_CAM_IOCTL_AXI_CONFIG   _IOW(MSM_CAM_IOCTL_MAGIC, 16, struct msm_camera_vfe_cfg_cmd *)
+
+#define MSM_CAM_IOCTL_GET_PICTURE   _IOW(MSM_CAM_IOCTL_MAGIC, 17, struct msm_camera_ctrl_cmd *)
+
+#define MSM_CAM_IOCTL_SET_CROP   _IOW(MSM_CAM_IOCTL_MAGIC, 18, struct crop_info *)
+
+#define MSM_CAM_IOCTL_PICT_PP   _IOW(MSM_CAM_IOCTL_MAGIC, 19, uint8_t *)
+
+#define MSM_CAM_IOCTL_PICT_PP_DONE   _IOW(MSM_CAM_IOCTL_MAGIC, 20, struct msm_snapshot_pp_status *)
+
+#define MSM_CAM_IOCTL_SENSOR_IO_CFG   _IOW(MSM_CAM_IOCTL_MAGIC, 21, struct sensor_cfg_data *)
+
+#define MSM_CAMERA_LED_OFF 0
+#define MSM_CAMERA_LED_LOW 1
+#define MSM_CAMERA_LED_HIGH 2
+
+#define MSM_CAM_IOCTL_FLASH_LED_CFG   _IOW(MSM_CAM_IOCTL_MAGIC, 22, unsigned *)
+
+#define MSM_CAM_IOCTL_UNBLOCK_POLL_FRAME   _IO(MSM_CAM_IOCTL_MAGIC, 23)
+
+#define MSM_CAM_IOCTL_CTRL_COMMAND_2   _IOW(MSM_CAM_IOCTL_MAGIC, 24, struct msm_ctrl_cmd *)
+
+#define MAX_SENSOR_NUM 3
+#define MAX_SENSOR_NAME 32
+
+#define MSM_CAM_CTRL_CMD_DONE 0
+#define MSM_CAM_SENSOR_VFE_CMD 1
+
+struct msm_ctrl_cmd {
+ uint16_t type;
+ uint16_t length;
+ void *value;
+ uint16_t status;
+ uint32_t timeout_ms;
+ int resp_fd;
+};
+
+struct msm_vfe_evt_msg {
+ unsigned short type;
+ unsigned short msg_id;
+ unsigned int len;
+ void *data;
+};
+
+#define MSM_CAM_RESP_CTRL 0
+#define MSM_CAM_RESP_STAT_EVT_MSG 1
+#define MSM_CAM_RESP_V4L2 2
+#define MSM_CAM_RESP_MAX 3
+
+struct msm_stats_event_ctrl {
+
+ int resptype;
+ int timeout_ms;
+ struct msm_ctrl_cmd ctrl_cmd;
+
+ struct msm_vfe_evt_msg stats_event;
+};
+
+struct msm_camera_cfg_cmd {
+
+ uint16_t cfg_type;
+
+ uint16_t cmd_type;
+ uint16_t queue;
+ uint16_t length;
+ void *value;
+};
+
+#define CMD_GENERAL 0
+#define CMD_AXI_CFG_OUT1 1
+#define CMD_AXI_CFG_SNAP_O1_AND_O2 2
+#define CMD_AXI_CFG_OUT2 3
+#define CMD_PICT_T_AXI_CFG 4
+#define CMD_PICT_M_AXI_CFG 5
+#define CMD_RAW_PICT_AXI_CFG 6
+#define CMD_STATS_AXI_CFG 7
+#define CMD_STATS_AF_AXI_CFG 8
+#define CMD_FRAME_BUF_RELEASE 9
+#define CMD_PREV_BUF_CFG 10
+#define CMD_SNAP_BUF_RELEASE 11
+#define CMD_SNAP_BUF_CFG 12
+#define CMD_STATS_DISABLE 13
+#define CMD_STATS_ENABLE 14
+#define CMD_STATS_AF_ENABLE 15
+#define CMD_STATS_BUF_RELEASE 16
+#define CMD_STATS_AF_BUF_RELEASE 17
+#define UPDATE_STATS_INVALID 18
+
+struct msm_vfe_cfg_cmd {
+ int cmd_type;
+ uint16_t length;
+ void *value;
+};
+
+#define MAX_CAMERA_ENABLE_NAME_LEN 32
+struct camera_enable_cmd {
+ char name[MAX_CAMERA_ENABLE_NAME_LEN];
+};
+
+#define MSM_PMEM_OUTPUT1 0
+#define MSM_PMEM_OUTPUT2 1
+#define MSM_PMEM_OUTPUT1_OUTPUT2 2
+#define MSM_PMEM_THUMBAIL 3
+#define MSM_PMEM_MAINIMG 4
+#define MSM_PMEM_RAW_MAINIMG 5
+#define MSM_PMEM_AEC_AWB 6
+#define MSM_PMEM_AF 7
+#define MSM_PMEM_MAX 8
+
+#define FRAME_PREVIEW_OUTPUT1 0
+#define FRAME_PREVIEW_OUTPUT2 1
+#define FRAME_SNAPSHOT 2
+#define FRAME_THUMBAIL 3
+#define FRAME_RAW_SNAPSHOT 4
+#define FRAME_MAX 5
+
+struct msm_pmem_info {
+ int type;
+ int fd;
+ void *vaddr;
+ uint32_t offset;
+ uint32_t len;
+ uint32_t y_off;
+ uint32_t cbcr_off;
+ uint8_t active;
+};
+
+struct outputCfg {
+ uint32_t height;
+ uint32_t width;
+
+ uint32_t window_height_firstline;
+ uint32_t window_height_lastline;
+};
+
+#define OUTPUT_1 0
+#define OUTPUT_2 1
+#define OUTPUT_1_AND_2 2
+#define CAMIF_TO_AXI_VIA_OUTPUT_2 3
+#define OUTPUT_1_AND_CAMIF_TO_AXI_VIA_OUTPUT_2 4
+#define OUTPUT_2_AND_CAMIF_TO_AXI_VIA_OUTPUT_1 5
+#define LAST_AXI_OUTPUT_MODE_ENUM = OUTPUT_2_AND_CAMIF_TO_AXI_VIA_OUTPUT_1 6
+
+#define MSM_FRAME_PREV_1 0
+#define MSM_FRAME_PREV_2 1
+#define MSM_FRAME_ENC 2
+
+struct msm_frame {
+ int path;
+ unsigned long buffer;
+ uint32_t y_off;
+ uint32_t cbcr_off;
+ int fd;
+
+ void *cropinfo;
+ int croplen;
+};
+
+#define STAT_AEAW 0
+#define STAT_AF 1
+#define STAT_MAX 2
+
+struct msm_stats_buf {
+ int type;
+ unsigned long buffer;
+ int fd;
+};
+
+#define MSM_V4L2_VID_CAP_TYPE 0
+#define MSM_V4L2_STREAM_ON 1
+#define MSM_V4L2_STREAM_OFF 2
+#define MSM_V4L2_SNAPSHOT 3
+#define MSM_V4L2_QUERY_CTRL 4
+#define MSM_V4L2_GET_CTRL 5
+#define MSM_V4L2_SET_CTRL 6
+#define MSM_V4L2_QUERY 7
+#define MSM_V4L2_MAX 8
+
+struct crop_info {
+ void *info;
+ int len;
+};
+
+struct msm_postproc {
+ int ftnum;
+ struct msm_frame fthumnail;
+ int fmnum;
+ struct msm_frame fmain;
+};
+
+struct msm_snapshot_pp_status {
+ void *status;
+};
+
+#define CFG_SET_MODE 0
+#define CFG_SET_EFFECT 1
+#define CFG_START 2
+#define CFG_PWR_UP 3
+#define CFG_PWR_DOWN 4
+#define CFG_WRITE_EXPOSURE_GAIN 5
+#define CFG_SET_DEFAULT_FOCUS 6
+#define CFG_MOVE_FOCUS 7
+#define CFG_REGISTER_TO_REAL_GAIN 8
+#define CFG_REAL_TO_REGISTER_GAIN 9
+#define CFG_SET_FPS 10
+#define CFG_SET_PICT_FPS 11
+#define CFG_SET_BRIGHTNESS 12
+#define CFG_SET_CONTRAST 13
+#define CFG_SET_ZOOM 14
+#define CFG_SET_EXPOSURE_MODE 15
+#define CFG_SET_WB 16
+#define CFG_SET_ANTIBANDING 17
+#define CFG_SET_EXP_GAIN 18
+#define CFG_SET_PICT_EXP_GAIN 19
+#define CFG_SET_LENS_SHADING 20
+#define CFG_GET_PICT_FPS 21
+#define CFG_GET_PREV_L_PF 22
+#define CFG_GET_PREV_P_PL 23
+#define CFG_GET_PICT_L_PF 24
+#define CFG_GET_PICT_P_PL 25
+#define CFG_GET_AF_MAX_STEPS 26
+#define CFG_GET_PICT_MAX_EXP_LC 27
+#define CFG_MAX 28
+
+#define MOVE_NEAR 0
+#define MOVE_FAR 1
+
+#define SENSOR_PREVIEW_MODE 0
+#define SENSOR_SNAPSHOT_MODE 1
+#define SENSOR_RAW_SNAPSHOT_MODE 2
+
+#define SENSOR_QTR_SIZE 0
+#define SENSOR_FULL_SIZE 1
+#define SENSOR_INVALID_SIZE 2
+
+#define CAMERA_EFFECT_OFF 0
+#define CAMERA_EFFECT_MONO 1
+#define CAMERA_EFFECT_NEGATIVE 2
+#define CAMERA_EFFECT_SOLARIZE 3
+#define CAMERA_EFFECT_PASTEL 4
+#define CAMERA_EFFECT_MOSAIC 5
+#define CAMERA_EFFECT_RESIZE 6
+#define CAMERA_EFFECT_SEPIA 7
+#define CAMERA_EFFECT_POSTERIZE 8
+#define CAMERA_EFFECT_WHITEBOARD 9
+#define CAMERA_EFFECT_BLACKBOARD 10
+#define CAMERA_EFFECT_AQUA 11
+#define CAMERA_EFFECT_MAX 12
+
+struct sensor_pict_fps {
+ uint16_t prevfps;
+ uint16_t pictfps;
+};
+
+struct exp_gain_cfg {
+ uint16_t gain;
+ uint32_t line;
+};
+
+struct focus_cfg {
+ int32_t steps;
+ int dir;
+};
+
+struct fps_cfg {
+ uint16_t f_mult;
+ uint16_t fps_div;
+ uint32_t pict_fps_div;
+};
+
+struct sensor_cfg_data {
+ int cfgtype;
+ int mode;
+ int rs;
+ uint8_t max_steps;
+
+ union {
+ int8_t effect;
+ uint8_t lens_shading;
+ uint16_t prevl_pf;
+ uint16_t prevp_pl;
+ uint16_t pictl_pf;
+ uint16_t pictp_pl;
+ uint32_t pict_max_exp_lc;
+ uint16_t p_fps;
+ struct sensor_pict_fps gfps;
+ struct exp_gain_cfg exp_gain;
+ struct focus_cfg focus;
+ struct fps_cfg fps;
+ } cfg;
+};
+
+#define GET_NAME 0
+#define GET_PREVIEW_LINE_PER_FRAME 1
+#define GET_PREVIEW_PIXELS_PER_LINE 2
+#define GET_SNAPSHOT_LINE_PER_FRAME 3
+#define GET_SNAPSHOT_PIXELS_PER_LINE 4
+#define GET_SNAPSHOT_FPS 5
+#define GET_SNAPSHOT_MAX_EP_LINE_CNT 6
+
+struct msm_camsensor_info {
+ char name[MAX_SENSOR_NAME];
+ uint8_t flash_enabled;
+};
+#endif
+
diff --git a/libc/kernel/tools/update_all.py b/libc/kernel/tools/update_all.py
index 6272fcf..d25dc0e 100755
--- a/libc/kernel/tools/update_all.py
+++ b/libc/kernel/tools/update_all.py
@@ -73,7 +73,9 @@
 
     print "cleaning: %-*s -> %-*s (%s)" % ( 35, path, 35, dst_path, r )
 
-usePerforce = os.environ.has_key("ANDROID_PRODUCT_OUT")
+# We don't use Perforce anymore, but just in case, define ANDROID_USE_P4
+# in your environment if you think you need it.
+usePerforce = os.environ.has_key("ANDROID_USE_P4")
 
 if usePerforce:
     b.updateP4Files()
diff --git a/libc/netbsd/net/getaddrinfo.c b/libc/netbsd/net/getaddrinfo.c
index 2dd3d97..f2189fb 100644
--- a/libc/netbsd/net/getaddrinfo.c
+++ b/libc/netbsd/net/getaddrinfo.c
@@ -912,7 +912,11 @@
 		allownumeric = 1;
 		break;
 	case ANY:
+#if 1  /* ANDROID-SPECIFIC CHANGE TO MATCH GLIBC */	
+		allownumeric = 1;
+#else
 		allownumeric = 0;
+#endif
 		break;
 	default:
 		return EAI_SOCKTYPE;
@@ -1271,7 +1275,7 @@
 	name = va_arg(ap, char *);
 	pai = va_arg(ap, const struct addrinfo *);
 
-	fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
+	//fprintf(stderr, "_dns_getaddrinfo() name = '%s'\n", name);
 
 	memset(&q, 0, sizeof(q));
 	memset(&q2, 0, sizeof(q2));
@@ -1630,7 +1634,7 @@
 		trailing_dot++;
 
 
-fprintf(stderr, "res_searchN() name = '%s'\n", name);
+        //fprintf(stderr, "res_searchN() name = '%s'\n", name);
 
 	/*
 	 * if there aren't any dots, it could be a user-level alias
diff --git a/libc/netbsd/net/getservent.c b/libc/netbsd/net/getservent.c
index 45207df..9f6ec32 100644
--- a/libc/netbsd/net/getservent.c
+++ b/libc/netbsd/net/getservent.c
@@ -27,6 +27,7 @@
  */
 #include <sys/cdefs.h>
 #include <sys/types.h>
+#include <endian.h>
 #include <netdb.h>
 #include "servent.h"
 #include "services.h"
@@ -54,6 +55,7 @@
     int          namelen;
     int          nn,count;
     int          total = 0;
+    int          port;
     char*        p2;
 
     p = rs->servent_ptr;
@@ -92,9 +94,12 @@
     memcpy( rs->servent.s_name, p+1, namelen );
     rs->servent.s_name[namelen] = 0;
     p += 1 + namelen;
-    rs->servent.s_port = ((((unsigned char*)p)[0] << 8) |
-                           ((unsigned char*)p)[1]);
 
+    /* s_port must be in network byte order */
+    port = ((((unsigned char*)p)[0] << 8) |
+             ((unsigned char*)p)[1]);
+
+    rs->servent.s_port  = htons(port);
     rs->servent.s_proto = p[2] == 't' ? "tcp" : "udp";
     p += 4;  /* skip port(2) + proto(1) + aliascount(1) */
 
diff --git a/libc/netbsd/resolv/res_comp.c b/libc/netbsd/resolv/res_comp.c
index 6991e8b..77b81b4 100644
--- a/libc/netbsd/resolv/res_comp.c
+++ b/libc/netbsd/resolv/res_comp.c
@@ -147,6 +147,12 @@
  * tell us anything about network-format data.  The rest of the BIND system
  * is not careful about this, but for some reason, we're doing it right here.
  */
+
+/* BIONIC: We also accept underscores in the middle of labels.
+ *         This extension is needed to make resolution on some VPN networks
+ *         work properly.
+ */
+
 #define PERIOD 0x2e
 #define	hyphenchar(c) ((c) == 0x2d)
 #define bslashchar(c) ((c) == 0x5c)
@@ -155,9 +161,10 @@
 #define alphachar(c) (((c) >= 0x41 && (c) <= 0x5a) \
 		   || ((c) >= 0x61 && (c) <= 0x7a))
 #define digitchar(c) ((c) >= 0x30 && (c) <= 0x39)
+#define underscorechar(c)  ((c) == 0x5f)
 
 #define borderchar(c) (alphachar(c) || digitchar(c))
-#define middlechar(c) (borderchar(c) || hyphenchar(c))
+#define middlechar(c) (borderchar(c) || hyphenchar(c) || underscorechar(c))
 #define	domainchar(c) ((c) > 0x20 && (c) < 0x7f)
 
 int
diff --git a/libc/netbsd/resolv/res_init.c b/libc/netbsd/resolv/res_init.c
index fc0272c..751603d 100644
--- a/libc/netbsd/resolv/res_init.c
+++ b/libc/netbsd/resolv/res_init.c
@@ -112,6 +112,7 @@
 #define MAX_DNS_PROPERTIES 8
 #define DNS_PROP_NAME_PREFIX "net.dns"
 #define DNS_CHANGE_PROP_NAME "net.dnschange"
+#define DNS_SEARCH_PROP_NAME "net.dns.search"
 const prop_info *dns_change_prop;
 int dns_last_change_counter;
 static int _get_dns_change_count();
@@ -168,6 +169,39 @@
 	return (__res_vinit(statp, 0));
 }
 
+#ifdef ANDROID_CHANGES
+int load_domain_search_list(res_state statp) {
+	char propvalue[PROP_VALUE_MAX];
+	register char *cp, **pp;
+
+	if(__system_property_get(DNS_SEARCH_PROP_NAME, propvalue) >= 1) {
+		strlcpy(statp->defdname, propvalue, sizeof(statp->defdname));
+		if ((cp = strchr(statp->defdname, '\n')) != NULL)
+			*cp = '\0';
+		cp = statp->defdname;
+		pp = statp->dnsrch;
+		while ( pp < statp->dnsrch + MAXDNSRCH ) {
+			while (*cp == ' ' || *cp == '\t') /* skip leading white space */
+				cp++;
+			if (*cp == '\0')  /* stop if nothing more */
+				break;
+			*pp++ = cp;  /* record this search domain */
+			while (*cp) { /* zero-terminate it */
+				if (*cp == ' ' || *cp == '\t') {
+					*cp++ = '\0';
+					break;
+				}
+				cp++;
+			}
+		}
+		*pp = NULL; /* statp->dnsrch has MAXDNSRCH+1 items */
+		if (pp > statp->dnsrch)
+			return 1;
+	}
+	return 0;
+}
+#endif
+
 /* This function has to be reachable by res_data.c but not publicly. */
 int
 __res_vinit(res_state statp, int preinit) {
@@ -344,6 +378,9 @@
 			}
 		}
 	}
+
+	/* Add the domain search list */
+	havesearch = load_domain_search_list(statp);
 #else /* IGNORE resolv.conf */
 #define	MATCH(line, name) \
 	(!strncmp(line, name, sizeof(name) - 1) && \
diff --git a/libc/private/bionic_tls.h b/libc/private/bionic_tls.h
index da34344..82c8cd9 100644
--- a/libc/private/bionic_tls.h
+++ b/libc/private/bionic_tls.h
@@ -60,6 +60,13 @@
 #define TLS_SLOT_OPENGL_API         3
 #define TLS_SLOT_OPENGL             4
 
+/* this slot is only used to pass information from the dynamic linker to
+ * libc.so when the C library is loaded in to memory. The C runtime init
+ * function will then clear it. Since its use is extremely temporary,
+ * we reuse an existing location.
+ */
+#define  TLS_SLOT_BIONIC_PREINIT    (TLS_SLOT_ERRNO+1)
+
 /* small technical note: it is not possible to call pthread_setspecific
  * on keys that are <= TLS_SLOT_MAX_WELL_KNOWN, which is why it is set to
  * TLS_SLOT_ERRNO.
diff --git a/libc/private/logd.h b/libc/private/logd.h
index 671cb48..43fa742 100644
--- a/libc/private/logd.h
+++ b/libc/private/logd.h
@@ -28,6 +28,8 @@
 #ifndef _ANDROID_BIONIC_LOGD_H
 #define _ANDROID_BIONIC_LOGD_H
 
+#include <stdarg.h>
+
 enum  {
     ANDROID_LOG_UNKNOWN = 0,
     ANDROID_LOG_DEFAULT,    /* only for SetMinPriority() */
@@ -43,5 +45,6 @@
 };
 
 int __libc_android_log_print(int prio, const char *tag, const char *fmt, ...);
+int __libc_android_log_vprint(int prio, const char *tag, const char *fmt, va_list ap);
 
 #endif /* _ANDROID_BIONIC_LOGD_H */
diff --git a/libc/stdlib/atexit.c b/libc/stdlib/atexit.c
index 5bf82ba..4ba2177 100644
--- a/libc/stdlib/atexit.c
+++ b/libc/stdlib/atexit.c
@@ -147,10 +147,19 @@
 				p->fns[n].fn_ptr.cxa_func = NULL;
 				mprotect(p, pgsize, PROT_READ);
 			}
+#if ANDROID
+                        /* it looks like we should always call the function
+                         * with an argument, even if dso is not NULL. Otherwise
+                         * static destructors will not be called properly on
+                         * the ARM.
+                         */
+                        (*fn.fn_ptr.cxa_func)(fn.fn_arg);
+#else /* !ANDROID */
 			if (dso != NULL)
 				(*fn.fn_ptr.cxa_func)(fn.fn_arg);
 			else
 				(*fn.fn_ptr.std_func)();
+#endif /* !ANDROID */
 		}
 	}
 
diff --git a/libm/Android.mk b/libm/Android.mk
index 8f0c3b1..fa73aff 100644
--- a/libm/Android.mk
+++ b/libm/Android.mk
@@ -170,7 +170,17 @@
 
     libm_common_includes = $(LOCAL_PATH)/i386 $(LOCAL_PATH)/i387
   else
-    $(error "Unknown architecture")
+    ifeq ($(TARGET_OS)-$(TARGET_ARCH),linux-sh)
+      libm_common_src_files += \
+		sh/fenv.c \
+		src/s_scalbln.c \
+		src/s_scalbn.c \
+		src/s_scalbnf.c
+
+      libm_common_includes = $(LOCAL_PATH)/sh
+    else
+      $(error "Unknown architecture")
+    endif
   endif
 endif
 
diff --git a/libm/sh/_fpmath.h b/libm/sh/_fpmath.h
new file mode 100644
index 0000000..f75ec7b
--- /dev/null
+++ b/libm/sh/_fpmath.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2009 Android Open Source Project, All rights reserved.
+ *   Derived from "bionic/libm/arm/_fpmath.h"
+ *   Copyright (c) 2002, 2003 David Schultz <das@FreeBSD.ORG>
+ *
+ * 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.
+ */
+
+/*
+ * Assumes that 'long double' on SH-linux is just an alias for 'double'.
+ */
+union IEEEl2bits {
+	long double	e;
+	struct {
+#if  __BYTE_ORDER == __LITTLE_ENDIAN
+		unsigned int	manl	:32;
+		unsigned int	manh	:20;
+		unsigned int	exp	:11;
+		unsigned int	sign	:1;
+#elif __BYTE_ORDER == __BIG_ENDIAN
+		unsigned int	sign	:1;
+		unsigned int	exp	:11;
+		unsigned int	manh	:20;
+		unsigned int	manl	:32;
+#endif
+	} bits;
+};
+
+/*
+ * LDBL_NBIT is a mask indicating the position of the integer
+ * bit in a long double.  But SH4 does not support it.
+ */
+#define	LDBL_NBIT	0
+#define	mask_nbit_l(u)	((void)0)
+
+#define	LDBL_MANH_SIZE	20
+#define	LDBL_MANL_SIZE	32
diff --git a/libm/sh/fenv.c b/libm/sh/fenv.c
new file mode 100644
index 0000000..ca8f476
--- /dev/null
+++ b/libm/sh/fenv.c
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2009 Android Open Source Project, All rights reserved.
+ *   Derived from "bionic/libm/arm/fenv.c"
+ *   Copyright (c) 2004 David Schultz <das@FreeBSD.ORG>
+ *
+ * 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.
+ */
+
+long __fpscr_values[2] = { 0L, 0x80000L };
diff --git a/libm/sh/fenv.h b/libm/sh/fenv.h
new file mode 100644
index 0000000..e872f47
--- /dev/null
+++ b/libm/sh/fenv.h
@@ -0,0 +1,240 @@
+/*
+ * Copyright (C) 2009 Android Open Source Project, All rights reserved.
+ *   Derived from "bionic/libm/arm/fenv.h"
+ *   Copyright (c) 2004-2005 David Schultz <das@FreeBSD.ORG>
+ *
+ * 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.
+ */
+
+#ifndef _FENV_H_
+#define _FENV_H_
+
+#include <stdio.h>
+#include <sys/types.h>
+
+typedef	uint32_t	fenv_t;
+typedef	uint32_t	fexcept_t;
+
+/* Exception flags */
+#define	FE_INVALID		0x0010
+#define	FE_DIVBYZERO	0x0008
+#define	FE_OVERFLOW		0x0004
+#define	FE_UNDERFLOW	0x0002
+#define	FE_INEXACT		0x0001
+#define	FE_ALL_EXCEPT	(FE_DIVBYZERO | FE_INEXACT | \
+				 FE_INVALID | FE_OVERFLOW | FE_UNDERFLOW)
+
+/* Rounding modes */
+#define	FE_TONEAREST	0x0000
+#define	FE_TOWARDZERO	0x0001
+#define	FE_UPWARD	0x0002 /* not supporetd */
+#define	FE_DOWNWARD	0x0003 /* not supporetd */
+#define	_ROUND_MASK	(FE_TONEAREST | FE_DOWNWARD | \
+				 FE_UPWARD | FE_TOWARDZERO)
+
+/* bit shift for FPSCR mapping */
+#define	_FPUE_CAUSE_SHIFT	12
+#define	_FPUE_ENABLE_SHIFT	17
+#define	_FPUE_FLAG_SHIFT	 2
+
+/* bit shifters */
+#define	_FPUE_CAUSE(_EXCS)	((_EXCS) << _FPUE_CAUSE_SHIFT)
+#define	_FPUE_ENABLE(_EXCS)	((_EXCS) << _FPUE_ENABLE_SHIFT)
+#define	_FPUE_FLAG(_EXCS)	((_EXCS) << _FPUE_FLAG_SHIFT)
+
+#define	_GET_FPUE_CAUSE(_FPUE)		(((_FPUE) >> _FPUE_CAUSE_SHIFT) & FE_ALL_EXCEPT)
+#define	_GET_FPUE_ENABLE(_FPUE)	(((_FPUE) >> _FPUE_ENABLE_SHIFT)& FE_ALL_EXCEPT)
+#define	_GET_FPUE_FLAG(_FPUE)		(((_FPUE) >> _FPUE_FLAG_SHIFT) & FE_ALL_EXCEPT)
+
+
+/* FPSCR register accessors */
+#ifdef	__SH4_NOFPU__
+#define	__read_fpscr(_ptr)
+#define	__write_fpscr(_val)
+#else
+#define	__read_fpscr(_ptr)	__asm __volatile("sts fpscr, %0" : "=r" (*(_ptr)))
+#define	__write_fpscr(_val)	__asm __volatile("lds %0, fpscr" : : "r" (_val))
+#endif
+
+
+/* functions for libm */
+static __inline int
+feclearexcept(int __excepts)
+{
+	uint32_t __fpscr;
+
+	__read_fpscr(&__fpscr);
+	__fpscr &= ~_FPUE_FLAG(__excepts);
+	__write_fpscr(__fpscr);
+	return (0);
+}
+
+static __inline int
+fegetexceptflag(fexcept_t *__flagp, int __excepts)
+{
+	uint32_t __fpscr;
+
+	__read_fpscr(&__fpscr);
+	*__flagp = _GET_FPUE_FLAG(__fpscr) & __excepts;
+	return (0);
+}
+
+
+static __inline int
+fesetexceptflag(const fexcept_t *__flagp, int __excepts)
+{
+	uint32_t __fpscr;
+
+	__read_fpscr(&__fpscr);
+	__fpscr &= ~_FPUE_FLAG(__excepts);
+	__fpscr |= ~_FPUE_FLAG(*__flagp & __excepts);
+	__write_fpscr(__fpscr);
+	return (0);
+}
+
+
+static __inline int
+feraiseexcept(int __excepts)
+{
+	fexcept_t __ex = __excepts;
+
+	fesetexceptflag(&__ex, __excepts);	/* XXX */
+	return (0);
+}
+
+
+static __inline int
+fetestexcept(int __excepts)
+{
+	fexcept_t __ex;
+
+	fegetexceptflag(&__ex,  __excepts);
+	return (__ex);
+}
+
+
+static __inline int
+fegetround(void)
+{
+	uint32_t __fpscr = 0;
+
+	__read_fpscr(&__fpscr);
+	return (__fpscr & _ROUND_MASK);	
+}
+
+static __inline int
+fesetround(int __round)
+{
+	uint32_t __fpscr = 0;
+
+	if (__round == FE_UPWARD || __round == FE_DOWNWARD) {
+		fprintf(stderr, "libm superh : "
+			"upward/downward rounding not supporetd.\n");
+		return -1;
+	}
+
+	__read_fpscr(&__fpscr);
+	__fpscr &= ~_ROUND_MASK;
+	__fpscr |= (__round & _ROUND_MASK);
+	__write_fpscr(__fpscr);
+	return (0);
+}
+
+static __inline int
+fegetenv(fenv_t *__envp)
+{
+	__read_fpscr(__envp);
+	return (0);
+}
+
+static __inline int
+feholdexcept(fenv_t *__envp)
+{
+	uint32_t __fpscr;
+
+	__read_fpscr(&__fpscr);
+	*__envp = __fpscr;
+	__fpscr &= ~_FPUE_FLAG(FE_ALL_EXCEPT);
+	__write_fpscr(__fpscr);
+	return (0);
+}
+
+
+static __inline int
+fesetenv(const fenv_t *__envp)
+{
+	__write_fpscr(*__envp);
+	return (0);
+}
+
+
+static __inline int
+feupdateenv(const fenv_t *__envp)
+{
+	uint32_t __fpscr;
+
+	__read_fpscr(&__fpscr);
+	__write_fpscr(*__envp);
+	feraiseexcept(_GET_FPUE_FLAG(__fpscr));
+	return (0);
+}
+
+#if __BSD_VISIBLE
+
+static __inline int
+feenableexcept(int __mask)
+{
+	uint32_t __old_fpscr, __new_fpscr;
+
+	__read_fpscr(&__old_fpscr);
+	__new_fpscr = __old_fpscr | _FPUE_ENABLE(__mask & FE_ALL_EXCEPT);
+	__write_fpscr(__new_fpscr);
+	return (_GET_FPUE_ENABLE(__old_fpscr));
+}
+
+static __inline int
+fedisableexcept(int __mask)
+{
+	uint32_t __old_fpscr, __new_fpscr;
+
+	__read_fpscr(&__old_fpscr);
+	__new_fpscr = __old_fpscr & ~(_FPUE_ENABLE(__mask & FE_ALL_EXCEPT));
+	__write_fpscr(__new_fpscr);
+	return (_GET_FPUE_ENABLE(__old_fpscr));
+}
+
+static __inline int
+fegetexcept(void)
+{
+	uint32_t __fpscr;
+
+	__read_fpscr(&__fpscr);
+	return (_GET_FPUE_ENABLE(__fpscr));
+}
+
+#endif /* __BSD_VISIBLE */
+
+
+#endif /* _FENV_H_ */
+
diff --git a/libstdc++/include/cassert b/libstdc++/include/cassert
new file mode 100644
index 0000000..5753e34
--- /dev/null
+++ b/libstdc++/include/cassert
@@ -0,0 +1,39 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+/*
+ * Standard C++ Library wrapper around the C assert.h header file.  This file
+ * can be included multiple times with different definition of NDEBUG, hence the
+ * absence of include guards.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CASSERT__
+#define BIONIC_LIBSTDCPP_INCLUDE_CASSERT__
+#endif
+#include <assert.h>
diff --git a/libstdc++/include/cctype b/libstdc++/include/cctype
new file mode 100644
index 0000000..e236561
--- /dev/null
+++ b/libstdc++/include/cctype
@@ -0,0 +1,56 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CCTYPE__
+#define BIONIC_LIBSTDCPP_INCLUDE_CCTYPE__
+
+/*
+ * Standard C++ Library wrapper around the C ctype.h header file.
+ */
+
+#include <ctype.h>
+
+namespace std 
+{
+using ::isalnum;
+using ::isalpha;
+using ::iscntrl;
+using ::isdigit;
+using ::isgraph;
+using ::islower;
+using ::isprint;
+using ::ispunct;
+using ::isspace;
+using ::isupper;
+using ::isxdigit;
+using ::tolower;
+using ::toupper;
+}  // namespace std
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CCTYPE__
diff --git a/libstdc++/include/cerrno b/libstdc++/include/cerrno
new file mode 100644
index 0000000..e53ca25
--- /dev/null
+++ b/libstdc++/include/cerrno
@@ -0,0 +1,40 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CERRNO__
+#define BIONIC_LIBSTDCPP_INCLUDE_CERRNO__
+
+/*
+ * Standard C++ Library wrapper around the C errno.h header file.
+ */
+#include <errno.h>
+
+// errno is a macro, so we can't define std::errno
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CERRNO__
diff --git a/libstdc++/include/cfloat b/libstdc++/include/cfloat
new file mode 100644
index 0000000..21c01d9
--- /dev/null
+++ b/libstdc++/include/cfloat
@@ -0,0 +1,39 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CFLOAT__
+#define BIONIC_LIBSTDCPP_INCLUDE_CFLOAT__
+
+/*
+ * Standard C++ Library wrapper around the C float.h header file.
+ */
+#include <sys/limits.h>
+#include <float.h>
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CFLOAT__
diff --git a/libstdc++/include/climits b/libstdc++/include/climits
new file mode 100644
index 0000000..df85cb9
--- /dev/null
+++ b/libstdc++/include/climits
@@ -0,0 +1,39 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CLIMITS__
+#define BIONIC_LIBSTDCPP_INCLUDE_CLIMITS__
+
+/*
+ * Standard C++ Library wrapper around the C limits.h header file.
+ */
+
+#include <limits.h>
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CLIMITS__
diff --git a/libstdc++/include/cmath b/libstdc++/include/cmath
new file mode 100644
index 0000000..bf697ff
--- /dev/null
+++ b/libstdc++/include/cmath
@@ -0,0 +1,71 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CMATH__
+#define BIONIC_LIBSTDCPP_INCLUDE_CMATH__
+
+/*
+ * Standard C++ Library wrapper around the C time.h header file.
+ */
+
+#include <cstddef>
+#include <math.h>
+
+namespace std
+{
+// Functions.
+using ::cos;
+using ::sin;
+using ::tan;
+using ::acos;
+using ::asin;
+using ::atan;
+using ::atan2;
+
+using ::cosh;
+using ::sinh;
+using ::tanh;
+
+using ::exp;
+using ::frexp;
+using ::ldexp;
+using ::log;
+using ::log10;
+using ::modf;
+
+using ::pow;
+using ::sqrt;
+
+using ::ceil;
+using ::fabs;
+using ::floor;
+using ::fmod;
+}  // namespace std
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CMATH__
diff --git a/libstdc++/include/csetjmp b/libstdc++/include/csetjmp
new file mode 100644
index 0000000..a68d127
--- /dev/null
+++ b/libstdc++/include/csetjmp
@@ -0,0 +1,49 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CSETJMP__
+#define BIONIC_LIBSTDCPP_INCLUDE_CSETJMP__
+
+/*
+ * Standard C++ Library wrapper around the C setjmp.h header file.
+ */
+
+#include <setjmp.h>
+
+#ifndef setjmp
+#define setjmp(env) setjmp (env)
+#endif
+
+namespace std
+{
+using ::jmp_buf;
+using ::longjmp;
+}  // namespace std
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CSETJMP__
diff --git a/libstdc++/include/csignal b/libstdc++/include/csignal
new file mode 100644
index 0000000..2600a75
--- /dev/null
+++ b/libstdc++/include/csignal
@@ -0,0 +1,46 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CSIGNAL__
+#define BIONIC_LIBSTDCPP_INCLUDE_CSIGNAL__
+
+/*
+ * Standard C++ Library wrapper around the C signal.h header file.
+ */
+
+#include <signal.h>
+
+namespace std
+{
+using ::sig_atomic_t;
+using ::signal;
+using ::raise;
+}  // namespace std
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CSIGNAL__
diff --git a/libstdc++/include/cstddef b/libstdc++/include/cstddef
index e69de29..fc1ca9d 100644
--- a/libstdc++/include/cstddef
+++ b/libstdc++/include/cstddef
@@ -0,0 +1,46 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CSTDDEF__
+#define BIONIC_LIBSTDCPP_INCLUDE_CSTDDEF__
+
+/*
+ * Standard C++ Library wrapper around the C stddef.h header file.
+ * The following 2 types are also declared in the 'std' namespace:
+ *   . ptrdiff_t
+ *   . size_t
+ */
+#include <stddef.h>
+
+namespace std {
+using ::ptrdiff_t;
+using ::size_t;
+}  // namespace std
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CSTDDEF__
diff --git a/libstdc++/include/cstdint b/libstdc++/include/cstdint
new file mode 100644
index 0000000..3df56df
--- /dev/null
+++ b/libstdc++/include/cstdint
@@ -0,0 +1,40 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CSTDINT__
+#define BIONIC_LIBSTDCPP_INCLUDE_CSTDINT__
+
+/*
+ * Standard C++ Library wrapper around the C stdint.h header file.
+ */
+
+#include <stdint.h>
+
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CSTDINT__
diff --git a/libstdc++/include/cstdio b/libstdc++/include/cstdio
new file mode 100644
index 0000000..d46a18b
--- /dev/null
+++ b/libstdc++/include/cstdio
@@ -0,0 +1,92 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CSTDIO__
+#define BIONIC_LIBSTDCPP_INCLUDE_CSTDIO__
+
+/*
+ * Standard C++ Library wrapper around the C stdio.h header file.
+ */
+#include <cstddef>
+#include <stdio.h>
+
+namespace std {
+using ::FILE;
+using ::fpos_t;
+
+using ::clearerr;
+using ::fclose;
+using ::feof;
+using ::ferror;
+using ::fflush;
+using ::fgetc;
+using ::fgetpos;
+using ::fgets;
+using ::fopen;
+using ::fprintf;
+using ::fputc;
+using ::fputs;
+using ::fread;
+using ::freopen;
+using ::fscanf;
+using ::fseek;
+using ::fsetpos;
+using ::ftell;
+using ::fwrite;
+using ::getc;
+using ::getchar;
+using ::gets;
+using ::perror;
+using ::printf;
+using ::putc;
+using ::putchar;
+using ::puts;
+using ::remove;
+using ::rename;
+using ::rewind;
+using ::scanf;
+using ::setbuf;
+using ::setvbuf;
+using ::sprintf;
+using ::sscanf;
+using ::tmpfile;
+using ::tmpnam;
+using ::ungetc;
+using ::vfprintf;
+using ::vprintf;
+using ::vsprintf;
+
+using ::snprintf;
+using ::vfscanf;
+using ::vscanf;
+using ::vsnprintf;
+using ::vsscanf;
+}  // namespace std
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CSTDIO__
diff --git a/libstdc++/include/cstdlib b/libstdc++/include/cstdlib
new file mode 100644
index 0000000..5e6a0b3
--- /dev/null
+++ b/libstdc++/include/cstdlib
@@ -0,0 +1,113 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CSTDLIB__
+#define BIONIC_LIBSTDCPP_INCLUDE_CSTDLIB__
+
+/*
+ * Standard C++ Library wrapper around the C stdlib.h header file.
+ */
+#include <stdlib.h>
+
+namespace std {
+
+using ::exit;
+using ::abort;
+using ::atexit;
+using ::on_exit;
+
+using ::getenv;
+using ::putenv;
+using ::setenv;
+using ::unsetenv;
+using ::clearenv;
+
+using ::mktemp;
+using ::mkstemp;
+
+using ::strtol;
+using ::strtoll;
+using ::strtoul;
+using ::strtoull;
+using ::strtod;
+using ::strtof;
+
+using ::atoi;
+using ::atol;
+using ::atoll;
+using ::atof;
+
+using ::abs;
+using ::labs;
+using ::llabs;
+
+using ::realpath;
+using ::system;
+
+using ::bsearch;
+using ::qsort;
+
+using ::jrand48;
+using ::mrand48;
+using ::nrand48;
+using ::lrand48;
+using ::seed48;
+using ::srand48;
+
+using ::rand;
+using ::srand;
+using ::random;
+using ::srandom;
+
+using ::malloc;
+using ::free;
+using ::calloc;
+using ::realloc;
+
+using ::unlockpt;
+using ::ptsname;
+using ::ptsname_r;
+using ::getpt;
+using ::grantpt;
+
+using ::div_t;
+using ::div;
+using ::ldiv_t;
+using ::ldiv;
+using ::lldiv_t;
+using ::lldiv;
+
+using ::mblen;
+using ::mbstowcs;
+using ::mbtowc;
+using ::wctomb;
+using ::wcstombs;
+}  // namespace std
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CSTDLIB__
diff --git a/libstdc++/include/cstring b/libstdc++/include/cstring
new file mode 100644
index 0000000..4ff7a6f
--- /dev/null
+++ b/libstdc++/include/cstring
@@ -0,0 +1,97 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CSTRING__
+#define BIONIC_LIBSTDCPP_INCLUDE_CSTRING__
+
+/*
+ * Standard C++ Library wrapper around the C string.h header file.
+ */
+
+#include <cstddef>
+#include <string.h>
+
+namespace std
+{
+using ::memccpy;
+using ::memchr;
+using ::memrchr;
+using ::memcmp;
+using ::memcpy;
+using ::memmove;
+using ::memset;
+using ::memmem;
+// In string.h but not part of the std
+// using ::memswap;
+
+using ::index;
+using ::rindex;
+using ::strchr;
+using ::strrchr;
+
+using ::strlen;
+using ::strcmp;
+using ::strcpy;
+using ::strcat;
+
+using ::strcasecmp;
+using ::strncasecmp;
+using ::strdup;
+
+using ::strstr;
+using ::strcasestr;
+using ::strtok;
+using ::strtok_r;
+
+using ::strerror;
+using ::strerror_r;
+
+using ::strnlen;
+using ::strncat;
+using ::strndup;
+using ::strncmp;
+using ::strncpy;
+
+// In string.h but not part of the std
+// using ::strlcat;
+// using ::strlcpy;
+
+using ::strcspn;
+using ::strpbrk;
+using ::strsep;
+using ::strspn;
+
+using ::strsignal;
+
+using ::strcoll;
+using ::strxfrm;
+
+}  // namespace std
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CSTRING__
diff --git a/libstdc++/include/ctime b/libstdc++/include/ctime
new file mode 100644
index 0000000..36fe7d5
--- /dev/null
+++ b/libstdc++/include/ctime
@@ -0,0 +1,59 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+#ifndef BIONIC_LIBSTDCPP_INCLUDE_CTIME__
+#define BIONIC_LIBSTDCPP_INCLUDE_CTIME__
+
+/*
+ * Standard C++ Library wrapper around the C time.h header file.
+ */
+
+#include <cstddef>
+#include <time.h>
+
+namespace std 
+{
+// Types.
+using ::clock_t;
+using ::time_t;
+using ::tm;
+
+// Functions.
+using ::clock;
+using ::difftime;
+using ::mktime;
+using ::time;
+using ::asctime;
+using ::ctime;
+using ::gmtime;
+using ::localtime;
+using ::strftime;
+}  // namespace std
+
+#endif  // BIONIC_LIBSTDCPP_INCLUDE_CTIME__
diff --git a/libstdc++/include/cwchar b/libstdc++/include/cwchar
new file mode 100644
index 0000000..a4f9f42
--- /dev/null
+++ b/libstdc++/include/cwchar
@@ -0,0 +1,31 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+/* IMPORTANT: cwchar and cwctype are not supported. See comment in
+ * bionic/libc/include/wchar.h */
diff --git a/libstdc++/include/cwctype_is_not_supported b/libstdc++/include/cwctype_is_not_supported
new file mode 100644
index 0000000..a4f9f42
--- /dev/null
+++ b/libstdc++/include/cwctype_is_not_supported
@@ -0,0 +1,31 @@
+/* -*- c++ -*- */
+/*
+ * Copyright (C) 2009 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.
+ */
+
+/* IMPORTANT: cwchar and cwctype are not supported. See comment in
+ * bionic/libc/include/wchar.h */
diff --git a/libstdc++/include/new b/libstdc++/include/new
index 559308b..19d8185 100644
--- a/libstdc++/include/new
+++ b/libstdc++/include/new
@@ -1,11 +1,10 @@
+/* -*- c++ -*- */
 #ifndef __NEW__
 #define __NEW__
 
-#include <stddef.h>
+#include <cstddef>
 
 namespace std {
-    using ::size_t;
-
     struct nothrow_t {};
     extern const nothrow_t nothrow;
 }
diff --git a/linker/Android.mk b/linker/Android.mk
index 48141be..3d3ad92 100644
--- a/linker/Android.mk
+++ b/linker/Android.mk
@@ -37,7 +37,7 @@
 
 LOCAL_MODULE:= linker
 
-LOCAL_STATIC_LIBRARIES := libcutils libc
+LOCAL_STATIC_LIBRARIES := libcutils libc_nomalloc
 
 #LOCAL_FORCE_STATIC_EXECUTABLE := true # not necessary when not including BUILD_EXECUTABLE
 
diff --git a/linker/README.TXT b/linker/README.TXT
new file mode 100644
index 0000000..4fff14e
--- /dev/null
+++ b/linker/README.TXT
@@ -0,0 +1,114 @@
+Android Dynamic Linker Design Notes
+===================================
+
+Introduction:
+-------------
+
+This document provides several notes related to the design of the Android
+dynamic linker.
+
+
+Prelinking:
+-----------
+
+System libraries in Android are internally prelinked, which means that
+any internal relocations within them are stripped from the corresponding
+shared object, in order to reduce size and speed up loading.
+
+Such libraries can only be loaded at the very specific virtual memory address
+they have been prelinked to (during the build process). The list of prelinked
+system libraries and their corresponding virtual memory address is found in
+the file:
+
+   build/core/prelink-linux-<arch>.map
+
+It should be updated each time a new system library is added to the
+system.
+
+The prelink step happens at build time, and uses the 'soslim' and 'apriori'
+tools:
+
+  - 'apriori' is the real prelink tool which removes relocations from the
+    shared object, however, it must be given a list of symbols to remove
+    from the file.
+
+  - 'soslim' is used to find symbols in an executable ELF file
+    and generate a list that can be passed to 'apriori'.
+
+By default, these tools are only used to remove internal symbols from
+libraries, though they have been designed to allow more aggressive
+optimizations (e.g. 'global' prelinking and symbol stripping, which
+prevent replacing individual system libraries though).
+
+You can disable prelinking at build time by modifying your Android.mk with
+a line like:
+
+    LOCAL_PRELINK_MODULE := false
+
+
+Initialization and Termination functions:
+-----------------------------------------
+
+The Unix Sys V Binary Interface standard states that an
+executable can have the following entries in its .dynamic
+section:
+
+  DT_INIT
+      Points to the address of an initialization function
+      that must be called when the file is loaded.
+
+  DT_INIT_ARRAY
+      Points to an array of function addresses that must be
+      called, in-order, to perform initialization. Some of
+      the entries in the array can be 0 or -1, and should
+      be ignored.
+
+      Note: this is generally stored in a .init_array section
+
+  DT_INIT_ARRAYSZ
+      The size of the DT_INITARRAY, if any
+
+  DT_FINI
+      Points to the address of a finalization function which
+      must be called when the file is unloaded or the process
+      terminated.
+
+  DT_FINI_ARRAY
+      Same as DT_INITARRAY but for finalizers. Note that the
+      functions must be called in reverse-order though
+
+      Note: this is generally stroed in a .fini_array section
+
+  DT_FINI_ARRAYSZ
+      Size of FT_FINIARRAY
+
+  DT_PREINIT_ARRAY
+      An array similar to DT_INIT_ARRAY which must *only* be
+      present in executables, not shared libraries, which contains
+      a list of functions that need to be called before any other
+      initialization function (i.e. DT_INIT and/or DT_INIT_ARRAY)
+
+      Note: this is generally stroed in a .preinit_array section
+
+  DT_PREINIT_ARRAYSZ
+      The size of DT_PREINIT_ARRAY
+
+If both a DT_INIT and DT_INITARRAY entry are present, the DT_INIT
+function must be called before the DT_INITARRAY functions.
+
+Consequently, the DT_FINIARRAY must be parsed in reverse order before
+the DT_FINI function, if both are available.
+
+Note that the implementation of static C++ constructors is very
+much processor dependent, and may use different ELF sections.
+
+On the ARM (see "C++ ABI for ARM" document), the static constructors
+must be called explicitely from the DT_INIT_ARRAY, and each one of them
+shall register a destructor by calling the special __eabi_atexit()
+function (provided by the C library). The DT_FINI_ARRAY is not used
+by static C++ destructors.
+
+On x86, the lists of constructors and destructors are placed in special
+sections named ".ctors" and ".dtors", and the DT_INIT / DT_FINI functions
+are in charge of calling them explicitely.
+
diff --git a/linker/dlfcn.c b/linker/dlfcn.c
index cd73d11..b54674f 100644
--- a/linker/dlfcn.c
+++ b/linker/dlfcn.c
@@ -15,41 +15,49 @@
  */
 #include <dlfcn.h>
 #include <pthread.h>
+#include <stdio.h>
 #include "linker.h"
 
 /* This file hijacks the symbols stubbed out in libdl.so. */
 
 #define DL_SUCCESS                    0
-#define DL_ERR_CANNOT_FIND_LIBRARY    1
+#define DL_ERR_CANNOT_LOAD_LIBRARY    1
 #define DL_ERR_INVALID_LIBRARY_HANDLE 2
 #define DL_ERR_BAD_SYMBOL_NAME        3
 #define DL_ERR_SYMBOL_NOT_FOUND       4
 #define DL_ERR_SYMBOL_NOT_GLOBAL      5
 
+static char dl_err_buf[1024];
+static const char *dl_err_str;
+
 static const char *dl_errors[] = {
-    [DL_SUCCESS] = NULL,
-    [DL_ERR_CANNOT_FIND_LIBRARY] = "Cannot find library",
+    [DL_ERR_CANNOT_LOAD_LIBRARY] = "Cannot load library",
     [DL_ERR_INVALID_LIBRARY_HANDLE] = "Invalid library handle",
     [DL_ERR_BAD_SYMBOL_NAME] = "Invalid symbol name",
     [DL_ERR_SYMBOL_NOT_FOUND] = "Symbol not found",
     [DL_ERR_SYMBOL_NOT_GLOBAL] = "Symbol is not global",
 };
 
-static int dl_last_err = DL_SUCCESS;
-
 #define likely(expr)   __builtin_expect (expr, 1)
 #define unlikely(expr) __builtin_expect (expr, 0)
 
 static pthread_mutex_t dl_lock = PTHREAD_MUTEX_INITIALIZER;
 
-void *dlopen(const char *filename, int flag) 
+static void set_dlerror(int err)
+{
+    snprintf(dl_err_buf, sizeof(dl_err_buf), "%s: %s", dl_errors[err],
+             linker_get_error());
+    dl_err_str = (const char *)&dl_err_buf[0];
+};
+
+void *dlopen(const char *filename, int flag)
 {
     soinfo *ret;
 
     pthread_mutex_lock(&dl_lock);
     ret = find_library(filename);
     if (unlikely(ret == NULL)) {
-        dl_last_err = DL_ERR_CANNOT_FIND_LIBRARY;
+        set_dlerror(DL_ERR_CANNOT_LOAD_LIBRARY);
     } else {
         ret->refcount++;
     }
@@ -59,9 +67,9 @@
 
 const char *dlerror(void)
 {
-    const char *err = dl_errors[dl_last_err];
-    dl_last_err = DL_SUCCESS;
-    return err;
+    const char *tmp = dl_err_str;
+    dl_err_str = NULL;
+    return (const char *)tmp;
 }
 
 void *dlsym(void *handle, const char *symbol)
@@ -71,16 +79,16 @@
     unsigned bind;
 
     pthread_mutex_lock(&dl_lock);
-    
+
     if(unlikely(handle == 0)) { 
-        dl_last_err = DL_ERR_INVALID_LIBRARY_HANDLE;
+        set_dlerror(DL_ERR_INVALID_LIBRARY_HANDLE);
         goto err;
     }
     if(unlikely(symbol == 0)) {
-        dl_last_err = DL_ERR_BAD_SYMBOL_NAME;
+        set_dlerror(DL_ERR_BAD_SYMBOL_NAME);
         goto err;
     }
-    
+
     if(handle == RTLD_DEFAULT) {
         sym = lookup(symbol, &base);
     } else if(handle == RTLD_NEXT) {
@@ -92,16 +100,17 @@
 
     if(likely(sym != 0)) {
         bind = ELF32_ST_BIND(sym->st_info);
-    
+
         if(likely((bind == STB_GLOBAL) && (sym->st_shndx != 0))) {
             unsigned ret = sym->st_value + base;
             pthread_mutex_unlock(&dl_lock);
             return (void*)ret;
         }
 
-        dl_last_err = DL_ERR_SYMBOL_NOT_GLOBAL;
+        set_dlerror(DL_ERR_SYMBOL_NOT_GLOBAL);
     }
-    else dl_last_err = DL_ERR_SYMBOL_NOT_FOUND;
+    else
+        set_dlerror(DL_ERR_SYMBOL_NOT_FOUND);
 
 err:
     pthread_mutex_unlock(&dl_lock);
diff --git a/linker/linker.c b/linker/linker.c
index 300a95c..789a828 100644
--- a/linker/linker.c
+++ b/linker/linker.c
@@ -51,7 +51,11 @@
 
 #include "ba.h"
 
-#define SO_MAX 64
+#define SO_MAX 96
+
+/* Assume average path length of 64 and max 8 paths */
+#define LDPATH_BUFSIZE 512
+#define LDPATH_MAX 8
 
 /* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
  *
@@ -66,18 +70,12 @@
  * - should we do anything special for STB_WEAK symbols?
  * - are we doing everything we should for ARM_COPY relocations?
  * - cleaner error reporting
- * - configuration for paths (LD_LIBRARY_PATH?)
  * - after linking, set as much stuff as possible to READONLY
  *   and NOEXEC
  * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
  *   headers provide versions that are negative...
  * - allocate space for soinfo structs dynamically instead of
  *   having a hard limit (64)
- *
- * features to add someday:
- *
- * - dlopen() and friends
- *
 */
 
 
@@ -89,6 +87,9 @@
 static soinfo *solist = &libdl_info;
 static soinfo *sonext = &libdl_info;
 
+static char ldpaths_buf[LDPATH_BUFSIZE];
+static const char *ldpaths[LDPATH_MAX + 1];
+
 int debug_verbosity;
 static int pid;
 
@@ -104,6 +105,32 @@
 #define PT_ARM_EXIDX    0x70000001      /* .ARM.exidx segment */
 #endif
 
+#define HOODLUM(name, ret, ...)                                               \
+    ret name __VA_ARGS__                                                      \
+    {                                                                         \
+        char errstr[] = "ERROR: " #name " called from the dynamic linker!\n"; \
+        write(2, errstr, sizeof(errstr));                                     \
+        abort();                                                              \
+    }
+HOODLUM(malloc, void *, (size_t size));
+HOODLUM(free, void, (void *ptr));
+HOODLUM(realloc, void *, (void *ptr, size_t size));
+HOODLUM(calloc, void *, (size_t cnt, size_t size));
+
+static char tmp_err_buf[768];
+static char __linker_dl_err_buf[768];
+#define DL_ERR(fmt, x...)                                                     \
+    do {                                                                      \
+        snprintf(__linker_dl_err_buf, sizeof(__linker_dl_err_buf),            \
+                 "%s[%d]: " fmt, __func__, __LINE__, ##x);                    \
+        ERROR(fmt "\n", ##x);                                                      \
+    } while(0)
+
+const char *linker_get_error(void)
+{
+    return (const char *)&__linker_dl_err_buf[0];
+}
+
 /*
  * This function is an empty stub where GDB locates a breakpoint to get notified
  * about linker activity.
@@ -207,7 +234,7 @@
     soinfo *si;
 
     if(strlen(name) >= SOINFO_NAME_LEN) {
-        ERROR("%5d library name %s too long\n", pid, name);
+        DL_ERR("%5d library name %s too long", pid, name);
         return 0;
     }
 
@@ -216,7 +243,7 @@
     */
     if (!freelist) {
         if(socount == SO_MAX) {
-            ERROR("%5d too many libraries when loading %s\n", pid, name);
+            DL_ERR("%5d too many libraries when loading %s", pid, name);
             return NULL;
         }
         freelist = sopool + socount++;
@@ -252,7 +279,7 @@
     }
     if (trav == NULL) {
         /* si was not ni solist */
-        ERROR("%5d name %s is not in solist!\n", pid, si->name);
+        DL_ERR("%5d name %s is not in solist!", pid, si->name);
         return;
     }
 
@@ -477,13 +504,12 @@
     return -1;
 }
 
-/* TODO: Need to add support for initializing the so search path with
- * LD_LIBRARY_PATH env variable for non-setuid programs. */
 static int open_library(const char *name)
 {
     int fd;
     char buf[512];
     const char **path;
+    int n;
 
     TRACE("[ %5d opening %s ]\n", pid, name);
 
@@ -493,8 +519,21 @@
     if ((name[0] == '/') && ((fd = _open_lib(name)) >= 0))
         return fd;
 
+    for (path = ldpaths; *path; path++) {
+        n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
+        if (n < 0 || n >= (int)sizeof(buf)) {
+            WARN("Ignoring very long library path: %s/%s\n", *path, name);
+            continue;
+        }
+        if ((fd = _open_lib(buf)) >= 0)
+            return fd;
+    }
     for (path = sopaths; *path; path++) {
-        snprintf(buf, sizeof(buf), "%s/%s", *path, name);
+        n = snprintf(buf, sizeof(buf), "%s/%s", *path, name);
+        if (n < 0 || n >= (int)sizeof(buf)) {
+            WARN("Ignoring very long library path: %s/%s\n", *path, name);
+            continue;
+        }
         if ((fd = _open_lib(buf)) >= 0)
             return fd;
     }
@@ -521,7 +560,7 @@
 
     sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
     if (sz < 0) {
-        ERROR("lseek() failed!\n");
+        DL_ERR("lseek() failed!");
         return 0;
     }
 
@@ -597,7 +636,7 @@
 
     TRACE("[ %5d Computing extents for '%s'. ]\n", pid, name);
     if (verify_elf_object(_hdr, name) < 0) {
-        ERROR("%5d - %s is not a valid ELF object\n", pid, name);
+        DL_ERR("%5d - %s is not a valid ELF object", pid, name);
         return (unsigned)-1;
     }
 
@@ -625,7 +664,7 @@
     }
 
     if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
-        ERROR("%5d - No loadable segments found in %s.\n", pid, name);
+        DL_ERR("%5d - No loadable segments found in %s.", pid, name);
         return (unsigned)-1;
     }
 
@@ -661,14 +700,14 @@
     void *base = mmap((void *)si->base, si->size, PROT_READ | PROT_EXEC,
                       MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
     if (base == MAP_FAILED) {
-        ERROR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
-              "as requested, will try general pool: %d (%s)\n",
+        DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
+              "as requested, will try general pool: %d (%s)",
               pid, (si->base ? "" : "non-"), si->name, si->base,
               errno, strerror(errno));
         return -1;
     } else if (base != (void *)si->base) {
-        ERROR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
-              "not at 0x%08x\n", pid, (si->base ? "" : "non-"),
+        DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
+              "not at 0x%08x", pid, (si->base ? "" : "non-"),
               si->name, (unsigned)base, si->base);
         munmap(base, si->size);
         return -1;
@@ -705,7 +744,7 @@
     }
 
 err:
-    ERROR("OOPS: %5d cannot map library '%s'. no vspace available.\n",
+    DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
           pid, si->name);
     return -1;
 }
@@ -764,8 +803,8 @@
                          MAP_PRIVATE | MAP_FIXED, fd,
                          phdr->p_offset & (~PAGE_MASK));
             if (pbase == MAP_FAILED) {
-                ERROR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
-                      "p_vaddr=0x%08x p_offset=0x%08x\n", pid, si->name,
+                DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
+                      "p_vaddr=0x%08x p_offset=0x%08x", pid, si->name,
                       (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
                 goto fail;
             }
@@ -820,8 +859,8 @@
                                   MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
                                   -1, 0);
                 if (extra_base == MAP_FAILED) {
-                    ERROR("[ %5d - failed to extend segment from '%s' @ 0x%08x "
-                          "(0x%08x) ]\n", pid, si->name, (unsigned)tmp,
+                    DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
+                           " (0x%08x) ]", pid, si->name, (unsigned)tmp,
                           extra_len);
                     goto fail;
                 }
@@ -873,8 +912,8 @@
 
     /* Sanity check */
     if (total_sz > si->size) {
-        ERROR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
-              "greater than what was allocated (0x%08x). THIS IS BAD!\n",
+        DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
+              "greater than what was allocated (0x%08x). THIS IS BAD!",
               pid, total_sz, si->name, si->size);
         goto fail;
     }
@@ -937,21 +976,24 @@
     int cnt;
     unsigned ext_sz;
     unsigned req_base;
+    const char *bname;
     soinfo *si = NULL;
     Elf32_Ehdr *hdr;
 
-    if(fd == -1)
+    if(fd == -1) {
+        DL_ERR("Library '%s' not found", name);
         return NULL;
+    }
 
     /* We have to read the ELF header to figure out what to do with this image
      */
     if (lseek(fd, 0, SEEK_SET) < 0) {
-        ERROR("lseek() failed!\n");
+        DL_ERR("lseek() failed!");
         goto fail;
     }
 
     if ((cnt = read(fd, &__header[0], PAGE_SIZE)) < 0) {
-        ERROR("read() failed!\n");
+        DL_ERR("read() failed!");
         goto fail;
     }
 
@@ -968,7 +1010,8 @@
      * same thing would happen if we failed during linking. Configuring the
      * soinfo struct here is a lot more convenient.
      */
-    si = alloc_info(name);
+    bname = strrchr(name, '/');
+    si = alloc_info(bname ? bname + 1 : name);
     if (si == NULL)
         goto fail;
 
@@ -1037,13 +1080,15 @@
 soinfo *find_library(const char *name)
 {
     soinfo *si;
+    const char *bname = strrchr(name, '/');
+    bname = bname ? bname + 1 : name;
 
     for(si = solist; si != 0; si = si->next){
-        if(!strcmp(name, si->name)) {
+        if(!strcmp(bname, si->name)) {
             if(si->flags & FLAG_ERROR) return 0;
             if(si->flags & FLAG_LINKED) return si;
-            ERROR("OOPS: %5d recursive link to '%s'\n", pid, si->name);
-            return 0;
+            DL_ERR("OOPS: %5d recursive link to '%s'", pid, si->name);
+            return NULL;
         }
     }
 
@@ -1074,7 +1119,7 @@
                 if(lsi)
                     unload_library(lsi);
                 else
-                    ERROR("%5d could not unload '%s'\n",
+                    DL_ERR("%5d could not unload '%s'",
                           pid, si->strtab + d[1]);
             }
         }
@@ -1121,27 +1166,27 @@
         DEBUG("%5d Processing '%s' relocation at index %d\n", pid,
               si->name, idx);
         if(sym != 0) {
-            s = _do_lookup(si, strtab + symtab[sym].st_name, &base);
+            sym_name = (char *)(strtab + symtab[sym].st_name);
+            s = _do_lookup(si, sym_name, &base);
             if(s == 0) {
-                ERROR("%5d cannot locate '%s'...\n", pid, sym_name);
+                DL_ERR("%5d cannot locate '%s'...", pid, sym_name);
                 return -1;
             }
 #if 0
             if((base == 0) && (si->base != 0)){
                     /* linking from libraries to main image is bad */
-                ERROR("%5d cannot locate '%s'...\n", 
+                DL_ERR("%5d cannot locate '%s'...",
                        pid, strtab + symtab[sym].st_name);
                 return -1;
             }
 #endif
             if ((s->st_shndx == SHN_UNDEF) && (s->st_value != 0)) {
-                ERROR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
-                      "handle this yet\n", pid, si->name, s->st_shndx,
+                DL_ERR("%5d In '%s', shndx=%d && value=0x%08x. We do not "
+                      "handle this yet", pid, si->name, s->st_shndx,
                       s->st_value);
                 return -1;
             }
             sym_addr = (unsigned)(s->st_value + base);
-            sym_name = (char *)(strtab + symtab[sym].st_name);
             COUNT_RELOC(RELOC_SYMBOL);
         } else {
             s = 0;
@@ -1198,7 +1243,7 @@
             COUNT_RELOC(RELOC_RELATIVE);
             MARK(rel->r_offset);
             if(sym){
-                ERROR("%5d odd RELATIVE form...\n", pid);
+                DL_ERR("%5d odd RELATIVE form...", pid);
                 return -1;
             }
             TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", pid,
@@ -1239,7 +1284,7 @@
 #endif /* ANDROID_ARM_LINKER */
 
         default:
-            ERROR("%5d unknown reloc type %d @ %p (%d)\n",
+            DL_ERR("%5d unknown reloc type %d @ %p (%d)",
                   pid, type, rel, (int) (rel - start));
             return -1;
         }
@@ -1248,13 +1293,38 @@
     return 0;
 }
 
-static void call_array(unsigned *ctor, int count)
+
+/* Please read the "Initialization and Termination functions" functions.
+ * of the linker design note in bionic/linker/README.TXT to understand
+ * what the following code is doing.
+ *
+ * The important things to remember are:
+ *
+ *   DT_PREINIT_ARRAY must be called first for executables, and should
+ *   not appear in shared libraries.
+ *
+ *   DT_INIT should be called before DT_INIT_ARRAY if both are present
+ *
+ *   DT_FINI should be called after DT_FINI_ARRAY if both are present
+ *
+ *   DT_FINI_ARRAY must be parsed in reverse order.
+ */
+
+static void call_array(unsigned *ctor, int count, int reverse)
 {
-    int n;
-    for(n = count; n > 0; n--){
-        TRACE("[ %5d Looking at ctor *0x%08x == 0x%08x ]\n", pid,
+    int n, inc = 1;
+
+    if (reverse) {
+        ctor += (count-1);
+        inc   = -1;
+    }
+
+    for(n = count; n > 0; n--) {
+        TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", pid,
+              reverse ? "dtor" : "ctor",
               (unsigned)ctor, (unsigned)*ctor);
-        void (*func)() = (void (*)()) *ctor++;
+        void (*func)() = (void (*)()) *ctor;
+        ctor += inc;
         if(((int) func == 0) || ((int) func == -1)) continue;
         TRACE("[ %5d Calling func @ 0x%08x ]\n", pid, (unsigned)func);
         func();
@@ -1263,31 +1333,20 @@
 
 static void call_constructors(soinfo *si)
 {
-    /* TODO: THE ORIGINAL CODE SEEMED TO CALL THE INIT FUNCS IN THE WRONG ORDER.
-     *       Old order: init, init_array, preinit_array..
-     *       Correct order: preinit_array, init, init_array.
-     *       Verify WHY.
-     */
-
     if (si->flags & FLAG_EXE) {
         TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
               pid, (unsigned)si->preinit_array, si->preinit_array_count,
               si->name);
-        call_array(si->preinit_array, si->preinit_array_count);
+        call_array(si->preinit_array, si->preinit_array_count, 0);
         TRACE("[ %5d Done calling preinit_array for '%s' ]\n", pid, si->name);
     } else {
         if (si->preinit_array) {
-            ERROR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
-                  " This is INVALID.\n", pid, si->name,
-                  (unsigned)si->preinit_array);
+            DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
+                   " This is INVALID.", pid, si->name,
+                   (unsigned)si->preinit_array);
         }
     }
 
-    // If we have an init section, then we should call it now, to make sure
-    // that all the funcs in the .ctors section get run.
-    // Note: For ARM, we shouldn't have a .ctor section (should be empty)
-    // when we have an (pre)init_array section, but let's be compatible with
-    // old (non-eabi) binaries and try the _init (DT_INIT) anyway.
     if (si->init_func) {
         TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", pid,
               (unsigned)si->init_func, si->name);
@@ -1298,25 +1357,21 @@
     if (si->init_array) {
         TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", pid,
               (unsigned)si->init_array, si->init_array_count, si->name);
-        call_array(si->init_array, si->init_array_count);
+        call_array(si->init_array, si->init_array_count, 0);
         TRACE("[ %5d Done calling init_array for '%s' ]\n", pid, si->name);
     }
 }
 
+
 static void call_destructors(soinfo *si)
 {
     if (si->fini_array) {
         TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", pid,
               (unsigned)si->fini_array, si->fini_array_count, si->name);
-        call_array(si->fini_array, si->fini_array_count);
+        call_array(si->fini_array, si->fini_array_count, 1);
         TRACE("[ %5d Done calling fini_array for '%s' ]\n", pid, si->name);
     }
 
-    // If we have an fini section, then we should call it now, to make sure
-    // that all the funcs in the .dtors section get run.
-    // Note: For ARM, we shouldn't have a .dtor section (should be empty)
-    // when we have an fini_array section, but let's be compatible with
-    // old (non-eabi) binaries and try the _fini (DT_FINI) anyway.
     if (si->fini_func) {
         TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", pid,
               (unsigned)si->fini_func, si->name);
@@ -1334,7 +1389,7 @@
 
     dev_null = open("/dev/null", O_RDWR);
     if (dev_null < 0) {
-        ERROR("Cannot open /dev/null.\n");
+        DL_ERR("Cannot open /dev/null.");
         return -1;
     }
     TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", pid, dev_null);
@@ -1360,7 +1415,7 @@
         /* The only error we allow is that the file descriptor does not
            exist, in which case we dup /dev/null to it. */
         if (errno != EBADF) {
-            ERROR("nullify_stdio: unhandled error %s\n", strerror(errno));
+            DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
             return_value = -1;
             continue;
         }
@@ -1371,9 +1426,9 @@
         do {
             status = dup2(dev_null, i);
         } while (status < 0 && errno == EINTR);
-        
+
         if (status < 0) {
-            ERROR("nullify_stdio: dup2 error %s\n", strerror(errno));
+            DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
             return_value = -1;
             continue;
         }
@@ -1382,12 +1437,12 @@
     /* If /dev/null is not one of the stdio file descriptors, close it. */
     if (dev_null > 2) {
         TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", pid, dev_null);
-	do {
+        do {
             status = close(dev_null);
         } while (status < 0 && errno == EINTR);
 
         if (status < 0) {
-            ERROR("nullify_stdio: close error %s\n", strerror(errno));
+            DL_ERR("nullify_stdio: close error %s", strerror(errno));
             return_value = -1;
         }
     }
@@ -1455,8 +1510,8 @@
                 }
             } else if (phdr->p_type == PT_DYNAMIC) {
                 if (si->dynamic != (unsigned *)-1) {
-                    ERROR("%5d multiple PT_DYNAMIC segments found in '%s'. "
-                          "Segment at 0x%08x, previously one found at 0x%08x\n",
+                    DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
+                          "Segment at 0x%08x, previously one found at 0x%08x",
                           pid, si->name, si->base + phdr->p_vaddr,
                           (unsigned)si->dynamic);
                     goto fail;
@@ -1468,7 +1523,7 @@
     }
 
     if (si->dynamic == (unsigned *)-1) {
-        ERROR("%5d missing PT_DYNAMIC?!\n", pid);
+        DL_ERR("%5d missing PT_DYNAMIC?!", pid);
         goto fail;
     }
 
@@ -1492,7 +1547,7 @@
             break;
         case DT_PLTREL:
             if(*d != DT_REL) {
-                ERROR("DT_RELA not supported\n");
+                DL_ERR("DT_RELA not supported");
                 goto fail;
             }
             break;
@@ -1517,7 +1572,7 @@
             *d = (int) &_r_debug;
             break;
         case DT_RELA:
-            ERROR("%5d DT_RELA not supported\n", pid);
+            DL_ERR("%5d DT_RELA not supported", pid);
             goto fail;
         case DT_INIT:
             si->init_func = (void (*)(void))(si->base + *d);
@@ -1569,16 +1624,18 @@
            pid, si->base, si->strtab, si->symtab);
 
     if((si->strtab == 0) || (si->symtab == 0)) {
-        ERROR("%5d missing essential tables\n", pid);
+        DL_ERR("%5d missing essential tables", pid);
         goto fail;
     }
 
     for(d = si->dynamic; *d; d += 2) {
         if(d[0] == DT_NEEDED){
             DEBUG("%5d %s needs %s\n", pid, si->name, si->strtab + d[1]);
-            soinfo *lsi = find_library(si->strtab + d[1]);            
+            soinfo *lsi = find_library(si->strtab + d[1]);
             if(lsi == 0) {
-                ERROR("%5d could not load '%s'\n", pid, si->strtab + d[1]);
+                strlcpy(tmp_err_buf, linker_get_error(), sizeof(tmp_err_buf));
+                DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
+                       pid, si->strtab + d[1], si->name, tmp_err_buf);
                 goto fail;
             }
             lsi->refcount++;
@@ -1643,6 +1700,29 @@
     return -1;
 }
 
+static void parse_library_path(char *path, char *delim)
+{
+    size_t len;
+    char *ldpaths_bufp = ldpaths_buf;
+    int i = 0;
+
+    len = strlcpy(ldpaths_buf, path, sizeof(ldpaths_buf));
+
+    while (i < LDPATH_MAX && (ldpaths[i] = strsep(&ldpaths_bufp, delim))) {
+        if (*ldpaths[i] != '\0')
+            ++i;
+    }
+
+    /* Forget the last path if we had to truncate; this occurs if the 2nd to
+     * last char isn't '\0' (i.e. not originally a delim). */
+    if (i > 0 && len >= sizeof(ldpaths_buf) &&
+            ldpaths_buf[sizeof(ldpaths_buf) - 2] != '\0') {
+        ldpaths[i - 1] = NULL;
+    } else {
+        ldpaths[i] = NULL;
+    }
+}
+
 int main(int argc, char **argv)
 {
     return 0;
@@ -1661,6 +1741,12 @@
     unsigned *vecs = (unsigned*) (argv + argc + 1);
     soinfo *si;
     struct link_map * map;
+    char *ldpath_env = NULL;
+
+    /* Setup a temporary TLS area that is used to get a working
+     * errno for system calls.
+     */
+    __set_tls(__tls_area);
 
     pid = getpid();
 
@@ -1669,8 +1755,15 @@
     gettimeofday(&t0, 0);
 #endif
 
-    __set_tls(__tls_area);
-    ((unsigned *)__get_tls())[TLS_SLOT_THREAD_ID] = gettid();
+    /* NOTE: we store the elfdata pointer on a special location
+     *       of the temporary TLS area in order to pass it to
+     *       the C Library's runtime initializer.
+     *
+     *       The initializer must clear the slot and reset the TLS
+     *       to point to a different location to ensure that no other
+     *       shared library constructor can access it.
+     */
+    __tls_area[TLS_SLOT_BIONIC_PREINIT] = elfdata;
 
     debugger_init();
 
@@ -1678,6 +1771,8 @@
     while(vecs[0] != 0) {
         if(!strncmp((char*) vecs[0], "DEBUG=", 6)) {
             debug_verbosity = atoi(((char*) vecs[0]) + 6);
+        } else if(!strncmp((char*) vecs[0], "LD_LIBRARY_PATH=", 16)) {
+            ldpath_env = (char*) vecs[0] + 16;
         }
         vecs++;
     }
@@ -1737,8 +1832,14 @@
     si->wrprotect_start = 0xffffffff;
     si->wrprotect_end = 0;
 
-    if(link_image(si, 0)){
-        ERROR("CANNOT LINK EXECUTABLE '%s'\n", argv[0]);
+        /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
+    if (ldpath_env && getuid() == geteuid() && getgid() == getegid())
+        parse_library_path(ldpath_env, ":");
+
+    if(link_image(si, 0)) {
+        char errmsg[] = "CANNOT LINK EXECUTABLE\n";
+        write(2, __linker_dl_err_buf, strlen(__linker_dl_err_buf));
+        write(2, errmsg, sizeof(errmsg));
         exit(-1);
     }
 
diff --git a/linker/linker.h b/linker/linker.h
index d80c761..69042c0 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -204,6 +204,7 @@
 unsigned unload_library(soinfo *si);
 Elf32_Sym *lookup_in_library(soinfo *si, const char *name);
 Elf32_Sym *lookup(const char *name, unsigned *base);
+const char *linker_get_error(void);
 
 #ifdef ANDROID_ARM_LINKER 
 typedef long unsigned int *_Unwind_Ptr;
diff --git a/linker/linker_debug.h b/linker/linker_debug.h
index 3cc1343..3f4fc4c 100644
--- a/linker/linker_debug.h
+++ b/linker/linker_debug.h
@@ -55,17 +55,16 @@
 #define TRUE                 1
 #define FALSE                0
 
-
-#define __PRINTVF(v,f,x...)   do {                                        \
-        (debug_verbosity > (v)) && (printf(x), ((f) && fflush(stdout))); \
-    } while (0)
 /* Only use printf() during debugging.  We have seen occasional memory
  * corruption when the linker uses printf().
  */
 #if LINKER_DEBUG
 extern int debug_verbosity;
 #warning "*** LINKER IS USING printf(); DO NOT CHECK THIS IN ***"
-#define _PRINTVF(v,f,x...)    __PRINTVF(v,f,x)
+#define _PRINTVF(v,f,x...)                                                \
+    do {                                                                  \
+        (debug_verbosity > (v)) && (printf(x), ((f) && fflush(stdout)));  \
+    } while (0)
 #else /* !LINKER_DEBUG */
 #define _PRINTVF(v,f,x...)   do {} while(0)
 #endif /* LINKER_DEBUG */
@@ -75,8 +74,9 @@
 #define TRACE(x...)          _PRINTVF(1, TRUE, x)
 #define WARN(fmt,args...)    \
         _PRINTVF(-1, TRUE, "%s:%d| WARNING: " fmt, __FILE__, __LINE__, ## args)
-#define ERROR(fmt,args...)   \
-        __PRINTVF(-1, TRUE, "%s:%d| ERROR: " fmt, __FILE__, __LINE__, ## args)
+#define ERROR(fmt,args...)    \
+        _PRINTVF(-1, TRUE, "%s:%d| ERROR: " fmt, __FILE__, __LINE__, ## args)
+
 
 #if TRACE_DEBUG
 #define DEBUG(x...)          _PRINTVF(2, TRUE, "DEBUG: " x)