am e1baec5d: am 4393aeff: am 947e4e27: am 29b060fa: am aed7823a: resolve merge conflicts of 8e4ac6bd to jb-mr1.1-dev (merge -s ours)

* commit 'e1baec5d7cb208a18b30279554dcc3233b79a78b':
  Bump revision number for all system images
diff --git a/docs/copyright-templates/asm.txt b/docs/copyright-templates/asm.txt
index f33c86d..22f9dd2 100644
--- a/docs/copyright-templates/asm.txt
+++ b/docs/copyright-templates/asm.txt
@@ -1,4 +1,4 @@
-; Copyright (C) 2011 The Android Open Source Project
+; Copyright 2013 The Android Open Source Project
 ;
 ; Licensed under the Apache License, Version 2.0 (the "License");
 ; you may not use this file except in compliance with the License.
diff --git a/docs/copyright-templates/bash.txt b/docs/copyright-templates/bash.txt
index ae90a87..389b21a 100644
--- a/docs/copyright-templates/bash.txt
+++ b/docs/copyright-templates/bash.txt
@@ -1,6 +1,6 @@
 #!/bin/bash
 #
-# Copyright (C) 2011 The Android Open Source Project
+# Copyright 2013 The Android Open Source Project
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
diff --git a/docs/copyright-templates/bsd/c.txt b/docs/copyright-templates/bsd/c.txt
index 39e77f0..55932e7 100644
--- a/docs/copyright-templates/bsd/c.txt
+++ b/docs/copyright-templates/bsd/c.txt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright 2013 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
diff --git a/docs/copyright-templates/c.txt b/docs/copyright-templates/c.txt
index efa50f3..11644d2 100644
--- a/docs/copyright-templates/c.txt
+++ b/docs/copyright-templates/c.txt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright 2013 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
diff --git a/docs/copyright-templates/java.txt b/docs/copyright-templates/java.txt
index efa50f3..11644d2 100644
--- a/docs/copyright-templates/java.txt
+++ b/docs/copyright-templates/java.txt
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011 The Android Open Source Project
+ * Copyright 2013 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
diff --git a/docs/copyright-templates/make.txt b/docs/copyright-templates/make.txt
index 851a7a8..317c4e6 100644
--- a/docs/copyright-templates/make.txt
+++ b/docs/copyright-templates/make.txt
@@ -1,4 +1,4 @@
-# Copyright (C) 2011 The Android Open Source Project
+# Copyright 2013 The Android Open Source Project
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
diff --git a/docs/copyright-templates/plain.txt b/docs/copyright-templates/plain.txt
index 12f1016..5db9282 100644
--- a/docs/copyright-templates/plain.txt
+++ b/docs/copyright-templates/plain.txt
@@ -1,4 +1,4 @@
-Copyright (C) 2011 The Android Open Source Project
+Copyright 2013 The Android Open Source Project
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
diff --git a/docs/copyright-templates/sh.txt b/docs/copyright-templates/sh.txt
index 7a3adb8..7bf532b 100644
--- a/docs/copyright-templates/sh.txt
+++ b/docs/copyright-templates/sh.txt
@@ -1,6 +1,6 @@
 #!/bin/sh
 #
-# Copyright (C) 2011 The Android Open Source Project
+# Copyright 2013 The Android Open Source Project
 #
 # Licensed under the Apache License, Version 2.0 (the "License");
 # you may not use this file except in compliance with the License.
diff --git a/docs/copyright-templates/xml.txt b/docs/copyright-templates/xml.txt
index 1be0191..9d10d88 100644
--- a/docs/copyright-templates/xml.txt
+++ b/docs/copyright-templates/xml.txt
@@ -1,5 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
-<!-- Copyright (C) 2011 The Android Open Source Project
+<!-- Copyright 2013 The Android Open Source Project
 
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
diff --git a/ide/eclipse/.classpath b/ide/eclipse/.classpath
index 9983bc0..bfbd04e 100644
--- a/ide/eclipse/.classpath
+++ b/ide/eclipse/.classpath
@@ -96,6 +96,7 @@
 	<classpathentry kind="src" path="development/samples/Snake/tests/src"/>
 	<classpathentry kind="src" path="libcore/dalvik/src/main/java"/>
 	<classpathentry kind="src" path="libcore/json/src/main/java"/>
+	<classpathentry kind="src" path="libcore/libdvm/src/main/java"/>
 	<classpathentry kind="src" path="libcore/luni/src/main/java"/>
 	<classpathentry kind="src" path="libcore/xml/src/main/java"/>
 	<classpathentry kind="src" path="out/target/common/obj/APPS/ApiDemos_intermediates/src/src"/>
diff --git a/ide/eclipse/android.importorder b/ide/eclipse/android.importorder
index f11daae..70efd62 100644
--- a/ide/eclipse/android.importorder
+++ b/ide/eclipse/android.importorder
@@ -1,7 +1,10 @@
-6=javax
-5=java
-4=org
-3=net
-2=junit
+9=javax
+8=java
+7=org
+6=net
+5=libcore
+4=junit
+3=gov
+2=dalvik
 1=com
 0=android
diff --git a/ndk/platforms/android-18/samples/gles3jni/jni/gl3stub.c b/ndk/platforms/android-18/samples/gles3jni/jni/gl3stub.c
index 19b78e7..67bf70c 100644
--- a/ndk/platforms/android-18/samples/gles3jni/jni/gl3stub.c
+++ b/ndk/platforms/android-18/samples/gles3jni/jni/gl3stub.c
@@ -14,6 +14,7 @@
  * limitations under the License.
  */
 
+#include <EGL/egl.h>
 #include "gl3stub.h"
 
 GLboolean gl3stubInit() {
diff --git a/ndk/platforms/android-3/include/inttypes.h b/ndk/platforms/android-3/include/inttypes.h
index 81d2315..73b22db 100644
--- a/ndk/platforms/android-3/include/inttypes.h
+++ b/ndk/platforms/android-3/include/inttypes.h
@@ -56,7 +56,7 @@
 #define	PRIdFAST64		"lld"		/* int_fast64_t */
 
 #define	PRIdMAX			"jd"		/* intmax_t */
-#define	PRIdPTR			"ld"		/* intptr_t */
+#define	PRIdPTR			"d"		/* intptr_t */
 
 #define	PRIi8			"i"		/* int8_t */
 #define	PRIi16			"i"		/* int16_t */
@@ -74,7 +74,7 @@
 #define	PRIiFAST64		"lli"		/* int_fast64_t */
 
 #define	PRIiMAX			"ji"		/* intmax_t */
-#define	PRIiPTR			"li"		/* intptr_t */
+#define	PRIiPTR			"i"		/* intptr_t */
 
 /* fprintf macros for unsigned integers */
 #define	PRIo8			"o"		/* int8_t */
@@ -93,7 +93,7 @@
 #define	PRIoFAST64		"llo"		/* int_fast64_t */
 
 #define	PRIoMAX			"jo"		/* intmax_t */
-#define	PRIoPTR			"lo"		/* intptr_t */
+#define	PRIoPTR			"o"		/* intptr_t */
 
 #define	PRIu8			"u"		/* uint8_t */
 #define	PRIu16			"u"		/* uint16_t */
@@ -111,7 +111,7 @@
 #define	PRIuFAST64		"llu"		/* uint_fast64_t */
 
 #define	PRIuMAX			"ju"		/* uintmax_t */
-#define	PRIuPTR			"lu"		/* uintptr_t */
+#define	PRIuPTR			"u"		/* uintptr_t */
 
 #define	PRIx8			"x"		/* uint8_t */
 #define	PRIx16			"x"		/* uint16_t */
@@ -129,7 +129,7 @@
 #define	PRIxFAST64		"llx"		/* uint_fast64_t */
 
 #define	PRIxMAX			"jx"		/* uintmax_t */
-#define	PRIxPTR			"lx"		/* uintptr_t */
+#define	PRIxPTR			"x"		/* uintptr_t */
 
 #define	PRIX8			"X"		/* uint8_t */
 #define	PRIX16			"X"		/* uint16_t */
@@ -147,7 +147,7 @@
 #define	PRIXFAST64		"llX"		/* uint_fast64_t */
 
 #define	PRIXMAX			"jX"		/* uintmax_t */
-#define	PRIXPTR			"lX"		/* uintptr_t */
+#define	PRIXPTR			"X"		/* uintptr_t */
 
 /* fscanf macros for signed integers */
 #define	SCNd8			"hhd"		/* int8_t */
@@ -166,7 +166,7 @@
 #define	SCNdFAST64		"lld"		/* int_fast64_t */
 
 #define	SCNdMAX			"jd"		/* intmax_t */
-#define	SCNdPTR			"ld"		/* intptr_t */
+#define	SCNdPTR			"d"		/* intptr_t */
 
 #define	SCNi8			"hhi"		/* int8_t */
 #define	SCNi16			"hi"		/* int16_t */
@@ -184,7 +184,7 @@
 #define	SCNiFAST64		"lli"		/* int_fast64_t */
 
 #define	SCNiMAX			"ji"		/* intmax_t */
-#define	SCNiPTR			"li"		/* intptr_t */
+#define	SCNiPTR			"i"		/* intptr_t */
 
 /* fscanf macros for unsigned integers */
 #define	SCNo8			"hho"		/* uint8_t */
@@ -203,7 +203,7 @@
 #define	SCNoFAST64		"llo"		/* uint_fast64_t */
 
 #define	SCNoMAX			"jo"		/* uintmax_t */
-#define	SCNoPTR			"lo"		/* uintptr_t */
+#define	SCNoPTR			"o"		/* uintptr_t */
 
 #define	SCNu8			"hhu"		/* uint8_t */
 #define	SCNu16			"hu"		/* uint16_t */
@@ -221,7 +221,7 @@
 #define	SCNuFAST64		"llu"		/* uint_fast64_t */
 
 #define	SCNuMAX			"ju"		/* uintmax_t */
-#define	SCNuPTR			"lu"		/* uintptr_t */
+#define	SCNuPTR			"u"		/* uintptr_t */
 
 #define	SCNx8			"hhx"		/* uint8_t */
 #define	SCNx16			"hx"		/* uint16_t */
@@ -239,7 +239,7 @@
 #define	SCNxFAST64		"llx"		/* uint_fast64_t */
 
 #define	SCNxMAX			"jx"		/* uintmax_t */
-#define	SCNxPTR			"lx"		/* uintptr_t */
+#define	SCNxPTR			"x"		/* uintptr_t */
 
 #endif /* __cplusplus || __STDC_FORMAT_MACROS */
 
diff --git a/ndk/platforms/android-3/include/malloc.h b/ndk/platforms/android-3/include/malloc.h
index ec21926..49a10e6 100644
--- a/ndk/platforms/android-3/include/malloc.h
+++ b/ndk/platforms/android-3/include/malloc.h
@@ -33,7 +33,7 @@
 extern void   free(void *);
 
 extern void*  memalign(size_t  alignment, size_t  bytesize);
-extern size_t malloc_usable_size(void*);
+extern size_t malloc_usable_size(const void*);
 
 extern void*  valloc(size_t  bytesize);
 extern void*  pvalloc(size_t bytesize);
diff --git a/ndk/platforms/android-3/include/netinet/tcp.h b/ndk/platforms/android-3/include/netinet/tcp.h
index 9adf904..bc52249 100644
--- a/ndk/platforms/android-3/include/netinet/tcp.h
+++ b/ndk/platforms/android-3/include/netinet/tcp.h
@@ -31,4 +31,22 @@
 #include <endian.h>		/* Include *before* linux/tcp.h */
 #include <linux/tcp.h>
 
+__BEGIN_DECLS
+
+enum {
+  TCP_ESTABLISHED = 1,
+  TCP_SYN_SENT,
+  TCP_SYN_RECV,
+  TCP_FIN_WAIT1,
+  TCP_FIN_WAIT2,
+  TCP_TIME_WAIT,
+  TCP_CLOSE,
+  TCP_CLOSE_WAIT,
+  TCP_LAST_ACK,
+  TCP_LISTEN,
+  TCP_CLOSING
+};
+
+__END_DECLS
+
 #endif /* _NETINET_TCP_H */
diff --git a/ndk/platforms/android-3/include/stdint.h b/ndk/platforms/android-3/include/stdint.h
index c3e29dd..7ae2595 100644
--- a/ndk/platforms/android-3/include/stdint.h
+++ b/ndk/platforms/android-3/include/stdint.h
@@ -66,7 +66,7 @@
 #  define INT_FAST8_MIN    INT8_MIN
 #  define INT_FAST8_MAX    INT8_MAX
 
-#  define UINT8_MAX           (255U)
+#  define UINT8_MAX           (255)
 #  define UINT_LEAST8_MAX     UINT8_MAX
 #  define UINT_FAST8_MAX      UINT8_MAX
 #endif
@@ -76,7 +76,7 @@
 #  define INT_LEAST8_C(c)	 INT8_C(c)
 #  define INT_FAST8_C(c)	INT8_C(c)
 
-#  define UINT8_C(c)	c ## U
+#  define UINT8_C(c)	c
 #  define UINT_LEAST8_C(c)  UINT8_C(c)
 #  define UINT_FAST8_C(c)  UINT8_C(c)
 #endif
@@ -99,7 +99,7 @@
 #  define INT_FAST16_MIN	INT32_MIN
 #  define INT_FAST16_MAX	INT32_MAX
 
-#  define UINT16_MAX	(65535U)
+#  define UINT16_MAX	(65535)
 #  define UINT_LEAST16_MAX UINT16_MAX
 #  define UINT_FAST16_MAX UINT32_MAX
 #endif
@@ -109,7 +109,7 @@
 #  define INT_LEAST16_C(c) INT16_C(c)
 #  define INT_FAST16_C(c)	 INT32_C(c)
 
-#  define UINT16_C(c)	c ## U
+#  define UINT16_C(c)	c
 #  define UINT_LEAST16_C(c) UINT16_C(c)
 #  define UINT_FAST16_C(c) UINT32_C(c)
 #endif
@@ -191,8 +191,13 @@
  * intptr_t & uintptr_t
  */
 
+#ifdef __LP64__
+typedef long          intptr_t;
+typedef unsigned long uintptr_t;
+#else
 typedef int           intptr_t;
 typedef unsigned int  uintptr_t;
+#endif
 
 #ifdef __STDINT_LIMITS
 #  define INTPTR_MIN    INT32_MIN
@@ -226,6 +231,29 @@
 #  define UINTMAX_C(c)	UINT64_C(c)
 #endif
 
+/* Limits of sig_atomic_t. */
+#ifdef __STDINT_LIMITS
+#  define SIG_ATOMIC_MIN  INT32_MIN
+#  define SIG_ATOMIC_MAX  INT32_MAX
+#endif
+
+/* Limits of wchar_t. */
+#ifdef __STDINT_LIMITS
+#include <sys/_wchar_limits.h>
+#endif
+
+/* Limits of wint_t. */
+#ifdef __STDINT_LIMITS
+#  define WINT_MIN        INT32_MIN
+#  define WINT_MAX        INT32_MAX
+#endif
+
+/* size_t is defined by the GCC-specific <stddef.h> */
+#ifndef _SSIZE_T_DEFINED_
+#define _SSIZE_T_DEFINED_
+typedef long int  ssize_t;
+#endif
+
 #define _BITSIZE 32
 
 /* Keep the kernel from trying to define these types... */
diff --git a/ndk/platforms/android-3/include/sys/_wchar_limits.h b/ndk/platforms/android-3/include/sys/_wchar_limits.h
new file mode 100644
index 0000000..644792f
--- /dev/null
+++ b/ndk/platforms/android-3/include/sys/_wchar_limits.h
@@ -0,0 +1,108 @@
+/*
+ * Copyright (C) 2013 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 _SYS__WCHAR_LIMITS_H
+#define _SYS__WCHAR_LIMITS_H
+
+#include <android/api-level.h>
+
+/* WCHAR_MIN / WCHAR_MAX can be defined by <stdint.h> or <wchar.h>.
+ * Due to historical reasons, their definition is a bit complex.
+ *
+ * - In NDK r8e and older, all definitions of WCHAR_MIN and WCHAR_MAX
+ *   where 32-bit signed values (with one exception described below),
+ *   despite the fact that wchar_t is 'unsigned' on ARM.
+ *   See http://b.android.com/57749
+ *
+ *   This is no longer the case, unless you define _WCHAR_IS_ALWAYS_SIGNED
+ *   at compile time to restore the old (broken) behaviour. This doesn't
+ *   affect other CPU ABIs.
+ *
+ * - Before API level 9, on ARM, wchar_t was typedef to 'char' when
+ *   compiling C (not C++). Also, the definitions of WCHAR_MIN and
+ *   WCHAR_MAX differed between <stdint.h> and <wchar.h>:
+ *
+ *     <stdint.h> conditionally defined them to INT32_MIN / INT32_MAX.
+ *     <wchar.h> conditionally defined them to 0 and 255 instead.
+ *
+ *   <stdint.h> would only define WCHAR_MIN and WCHAR_MAX when:
+ *    - Compiling C sources.
+ *    - Compiling C++ sources with __STDC_LIMIT_MACROS being defined.
+ *
+ *   <wchar.h> always ends up including <stdint.h> indirectly. This
+ *   means that:
+ *
+ *     - When compiling C sources, WCHAR_MIN / WCHAR_MAX were always
+ *       defined as INT32_MIN / INT32_MAX.
+ *
+ *     - When compiling C++ sources with __STDC_LIMIT_MACROS defined,
+ *       they were always defined to INT32_MIN / INT32_MAX
+ *
+ *     - When compiling C++ sources without __STDC_LIMIT_MACROS defined,
+ *       they were defined by <wchar.h> as 0 and 255, respectively.
+ *
+ *    Keep in mind that this was ARM-specific, only for API level < 9.
+ *
+ *    If _WCHAR_IS_8BIT is defined, the same broken behaviour will
+ *    be restored. See http://b.android.com/57267
+ */ 
+#if !defined(WCHAR_MIN)
+
+#  if defined(_WCHAR_IS_8BIT) && defined(__arm__) && __ANDROID_API__ < 9
+#    if defined(__cplusplus) && !defined(__STDC_LIMIT_MACROS)
+#      define WCHAR_MIN  0
+#      define WCHAR_MAX  255
+#    else
+#      define WCHAR_MIN   (-2147483647 - 1)
+#      define WCHAR_MAX   (2147483647)
+#    endif
+#  elif defined(_WCHAR_IS_ALWAYS_SIGNED)
+#    define WCHAR_MIN   (-2147483647 - 1)
+#    define WCHAR_MAX   (2147483647)
+#  else
+  /* Otherwise, the value is derived from the toolchain configuration.
+   * to avoid putting explicit CPU checks in this header. */
+#    ifndef __WCHAR_MAX__
+#      error "__WCHAR_MAX__ is not defined. Check your toolchain!"
+#    endif
+  /* Clang does define __WCHAR_MAX__, but not __WCHAR_MIN__ */
+#    ifndef __WCHAR_MIN__
+#      if __WCHAR_MAX__ == 4294967295
+#        define __WCHAR_MIN__  (0U)
+#      elif __WCHAR_MAX__ == 2147483647
+#        define __WCHAR_MIN__  (-2147483647 - 1)
+#      else
+#        error "Invalid __WCHAR_MAX__ value. Check your toolchain!"
+#      endif
+#    endif /* !__WCHAR_MIN__ */
+#    define WCHAR_MIN    __WCHAR_MIN__
+#    define WCHAR_MAX    __WCHAR_MAX__
+#  endif /* !_WCHAR_IS_ALWAYS_SIGNED */
+
+#endif /* !WCHAR_MIN */
+
+#endif  /* _SYS__WCHAR_LIMITS_H */
diff --git a/ndk/platforms/android-3/include/sys/cdefs.h b/ndk/platforms/android-3/include/sys/cdefs.h
index 27c575c..88ce720 100644
--- a/ndk/platforms/android-3/include/sys/cdefs.h
+++ b/ndk/platforms/android-3/include/sys/cdefs.h
@@ -37,11 +37,36 @@
 #ifndef	_SYS_CDEFS_H_
 #define	_SYS_CDEFS_H_
 
-
-/* our implementation of wchar_t is only 8-bit - die die non-portable code */
+/* In previous NDK releases, wchar_t was defined as 'unsigned char'
+ * when targetting API level < 9 (i.e. Froyo or older).
+ *
+ * This is no longer the case, but you can define _WCHAR_IS_8BIT
+ * at compile time to restore the old behaviour.
+ *
+ * The reason for this redefine is purely historical. Until Android 2.3,
+ * i.e. API level 9, there was absolutely no official support for wchar_t
+ * in the C library, but compiling GCC and the GNU libstdc++ required a
+ * working <wchar.h>.
+ *
+ * To allow this while keeping the C library small, wchar_t was redefined
+ * explicitely as an 8-bit unsigned integer (which is perfectly allowed
+ * by the standard) and a very small set of wcs-xxx functions provided
+ * as wrappers around the corresponding str-xxx ones.
+ *
+ * Starting with API level 9, wchar_t is properly defined as a 32-bit
+ * type (as mandated by the compiler itself), and the lines below
+ * were removed (see $NDK/platforms/android-9/include/sys/cdefs.h).
+ *
+ * Note that this only affects C source compilation. For C++, wchar_t
+ * is a compiler keyboard that cannot be redefined and is always 32-bit.
+ *
+ * On the other hand, _WCHAR_IS_8BIT also affects the definition of
+ * WCHAR_MIN, WCHAR_MAX and WEOF (see <wchar.h> comments).
+ */
+#ifdef _WCHAR_IS_8BIT
 #undef  __WCHAR_TYPE__
 #define __WCHAR_TYPE__  unsigned char
-
+#endif
 
 /*
  * Macro to test if we're using a GNU C compiler of a specific vintage
diff --git a/ndk/platforms/android-3/include/sys/un.h b/ndk/platforms/android-3/include/sys/un.h
index 973861f..f89ead3 100644
--- a/ndk/platforms/android-3/include/sys/un.h
+++ b/ndk/platforms/android-3/include/sys/un.h
@@ -28,6 +28,9 @@
 #ifndef _SYS_UN_H_
 #define _SYS_UN_H_
 
+#include <sys/_types.h>
+typedef __sa_family_t sa_family_t;
+
 #include <linux/un.h>
 
 #endif /* _SYS_UN_H_ */
diff --git a/ndk/platforms/android-3/include/wchar.h b/ndk/platforms/android-3/include/wchar.h
index 9a6ce1d..575da4d 100644
--- a/ndk/platforms/android-3/include/wchar.h
+++ b/ndk/platforms/android-3/include/wchar.h
@@ -40,6 +40,7 @@
 #include <malloc.h>
 
 #include <stddef.h>
+#include <sys/_wchar_limits.h>
 
 /* IMPORTANT: Any code that relies on wide character support is essentially
  *            non-portable and/or broken. the only reason this header exist
@@ -70,9 +71,15 @@
     WC_TYPE_MAX
 } wctype_t;
 
-#define  WCHAR_MAX   255
-#define  WCHAR_MIN   0
+/* WEOF used to be defined as simply -1, which is
+ * invalid (the standard mandates that the expression must have wint_t
+ * type). Revert to the old broken behaviour is _WCHAR_IS_8BIT is defined.
+ * See http://b.android.com/57267 */
+#ifdef _WCHAR_IS_8BIT
 #define  WEOF        (-1)
+#else
+#define  WEOF        ((wint_t)-1)
+#endif
 
 extern wint_t            btowc(int);
 extern int               fwprintf(FILE *, const wchar_t *, ...);
diff --git a/ndk/platforms/android-8/include/wchar.h b/ndk/platforms/android-8/include/wchar.h
index b9c7b0b..453b6d5 100644
--- a/ndk/platforms/android-8/include/wchar.h
+++ b/ndk/platforms/android-8/include/wchar.h
@@ -40,6 +40,7 @@
 #include <malloc.h>
 
 #include <stddef.h>
+#include <sys/_wchar_limits.h>
 
 /* IMPORTANT: Any code that relies on wide character support is essentially
  *            non-portable and/or broken. the only reason this header exist
@@ -70,9 +71,20 @@
     WC_TYPE_MAX
 } wctype_t;
 
-#define  WCHAR_MAX   255
-#define  WCHAR_MIN   0
+/* WEOF used to be defined as simply -1, which is
+ * invalid (the standard mandates that the expression must have wint_t
+ * type). Revert to the old broken behaviour is _WCHAR_IS_8BIT is defined.
+ * See http://b.android.com/57267 */
+#ifdef _WCHAR_IS_8BIT
 #define  WEOF        (-1)
+#else
+#define  WEOF        ((wint_t)-1)
+#endif
+#ifdef _WCHAR_IS_8BIT
+#define  WEOF        (-1)
+#else
+#define  WEOF        ((wint_t)-1)
+#endif
 
 extern wint_t            btowc(int);
 extern int               fwprintf(FILE *, const wchar_t *, ...);
diff --git a/ndk/platforms/android-9/arch-mips/src/__dso_handle.S b/ndk/platforms/android-9/arch-mips/src/__dso_handle.S
deleted file mode 100644
index 77a5d7f..0000000
--- a/ndk/platforms/android-9/arch-mips/src/__dso_handle.S
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2010 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.
- */
-
-# The __dso_handle global variable is used by static
-# C++ constructors and destructors in the binary.
-# See http://www.codesourcery.com/public/cxx-abi/abi.html#dso-dtor
-#
-	.data
-        .align 4
-	.hidden __dso_handle
-        .globl __dso_handle
-__dso_handle:
-        .long __dso_handle
diff --git a/ndk/platforms/android-9/arch-mips/src/atexit.S b/ndk/platforms/android-9/arch-mips/src/atexit.h
similarity index 81%
rename from ndk/platforms/android-9/arch-mips/src/atexit.S
rename to ndk/platforms/android-9/arch-mips/src/atexit.h
index 7f0c820..759008c 100644
--- a/ndk/platforms/android-9/arch-mips/src/atexit.S
+++ b/ndk/platforms/android-9/arch-mips/src/atexit.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2013 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -25,19 +25,12 @@
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-	.text
-	.globl	atexit
-	.hidden	atexit
-	.type	atexit, @function
-	.align  4
-	.ent	atexit
-atexit:
-	.set	noreorder
-	.cpload	$t9
-	.set	reorder
-	la	$t9, __cxa_atexit
-	move	$a1, $0
-	la      $a2, __dso_handle
-	j	$t9
-	.size	atexit, .-atexit
-	.end	atexit
+
+extern void *__dso_handle;
+extern int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
+
+__attribute__ ((visibility ("hidden")))
+int atexit(void (*func)(void))
+{
+  return (__cxa_atexit((void (*)(void *))func, (void *)0, &__dso_handle));
+}
diff --git a/ndk/platforms/android-9/arch-mips/src/crtbegin.c b/ndk/platforms/android-9/arch-mips/src/crtbegin.c
new file mode 100644
index 0000000..618e020
--- /dev/null
+++ b/ndk/platforms/android-9/arch-mips/src/crtbegin.c
@@ -0,0 +1,112 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+#include <stddef.h>
+#include <stdint.h>
+#include <sys/cdefs.h>
+
+extern int main(int argc, char** argv, char** env);
+
+typedef struct
+{
+    void (**preinit_array)(void);
+    void (**init_array)(void);
+    void (**fini_array)(void);
+    void (**ctor_list)(void);
+    void (**dtor_list)(void);
+} structors_array_t;
+
+__attribute__ ((section (".preinit_array")))
+void (*__PREINIT_ARRAY__)(void) = (void (*)(void)) -1;
+
+__attribute__ ((section (".init_array")))
+void (*__INIT_ARRAY__)(void) = (void (*)(void)) -1;
+
+__attribute__ ((section (".fini_array")))
+void (*__FINI_ARRAY__)(void) = (void (*)(void)) -1;
+
+__attribute__ ((section (".ctors")))
+void (*__CTOR_LIST__)(void) = (void (*)(void)) -1;
+
+__attribute__ ((section (".dtors")))
+void (*__DTOR_LIST__)(void) = (void (*)(void)) -1;
+
+__LIBC_HIDDEN__  void do_mips_start(void *raw_args) {
+  structors_array_t array;
+  array.preinit_array = &__PREINIT_ARRAY__;
+  array.init_array = &__INIT_ARRAY__;
+  array.fini_array = &__FINI_ARRAY__;
+  array.ctor_list = &__CTOR_LIST__;
+  array.dtor_list = &__DTOR_LIST__;
+
+  __libc_init(raw_args, NULL, &main, &array);
+}
+
+/*
+ * This function prepares the return address with a branch-and-link
+ * instruction (bal) and then uses a .cpload to compute the Global
+ * Offset Table (GOT) pointer ($gp). The $gp is then used to load
+ * the address of _do_start() into $t9 just before calling it.
+ * Terminating the stack with a NULL return address.
+ */
+__asm__ (
+"       .set push                   \n"
+"                                   \n"
+"       .text                       \n"
+"       .align  4                   \n"
+"       .type __start,@function     \n"
+"       .globl __start              \n"
+"       .globl  _start              \n"
+"                                   \n"
+"       .ent    __start             \n"
+"__start:                           \n"
+" _start:                           \n"
+"       .frame   $sp,32,$ra         \n"
+"       .mask   0x80000000,-4       \n"
+"                                   \n"
+"       .set noreorder              \n"
+"       bal     1f                  \n"
+"       nop                         \n"
+"1:                                 \n"
+"       .cpload $ra                 \n"
+"       .set reorder                \n"
+"                                   \n"
+"       move    $a0, $sp            \n"
+"       addiu   $sp, $sp, (-32)     \n"
+"       sw      $0, 28($sp)         \n"
+"       la      $t9, do_mips_start  \n"
+"       jalr    $t9                 \n"
+"                                   \n"
+"2:     b       2b                  \n"
+"       .end    __start             \n"
+"                                   \n"
+"       .set pop                    \n"
+);
+
+#include "__dso_handle.h"
+#include "atexit.h"
diff --git a/ndk/platforms/android-9/arch-mips/src/crtbegin_dynamic.S b/ndk/platforms/android-9/arch-mips/src/crtbegin_dynamic.S
deleted file mode 100644
index be42fb2..0000000
--- a/ndk/platforms/android-9/arch-mips/src/crtbegin_dynamic.S
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-	.text
-	.align 4
-	.type __start,@function
-	.globl __start
-	.globl _start
-
-# this is the small startup code that is first run when
-# any executable that is dynamically-linked with Bionic
-# runs.
-#
-# it's purpose is to call __libc_init with appropriate
-# arguments, which are:
-#
-#    - the address of the raw data block setup by the Linux
-#      kernel ELF loader
-#
-#    - address of an "onexit" function, not used on any
-#      platform supported by Bionic
-#
-#    - address of the "main" function of the program.
-#
-#    - address of the constructor list
-#
-
-	.ent	__start
-__start:	
-_start:
-	bal	1f
-1:
-	.set	noreorder
-	.cpload	$ra
-	.set	reorder
-
-	move	$a0, $sp
-	move	$a1, $0
-	la	$a2, main
-	la	$a3, 1f
-	subu	$sp, 32
-	la	$t9, __libc_init
-# Use jalr intead of jr so stack unwinding past __libc_init can terminate at _start
-	jalr	$t9
-	move	$t9, $0
-	j	$t9
-	.end	__start
-
-1:	.long	__PREINIT_ARRAY__
-	.long	__INIT_ARRAY__
-	.long	__FINI_ARRAY__
-	.long	__CTOR_LIST__
-	.long	__DTOR_LIST__
-
-	.section .preinit_array, "aw"
-	.type __PREINIT_ARRAY__, @object
-	.globl __PREINIT_ARRAY__
-__PREINIT_ARRAY__:
-	.long -1
-
-	.section .init_array, "aw"
-	.type __INIT_ARRAY__, @object
-	.globl __INIT_ARRAY__
-__INIT_ARRAY__:
-	.long -1
-
-	.section .fini_array, "aw"
-	.type __FINI_ARRAY__, @object
-	.globl __FINI_ARRAY__
-__FINI_ARRAY__:
-	.long -1
-	.long __do_global_dtors_aux
-
-	.section .ctors, "aw"
-	.type __CTOR_LIST__, @object
-	.globl __CTOR_LIST__
-__CTOR_LIST__:
-	.long -1
-
-	.section .dtors, "aw"
-	.type __DTOR_LIST__, @object
-	.globl __DTOR_LIST__
-__DTOR_LIST__:
-	.long -1
-
-	.abicalls
-	.section	.eh_frame,"a",@progbits
-	.align	2
-	.type	__EH_FRAME_BEGIN__, @object
-	.size	__EH_FRAME_BEGIN__, 0
-__EH_FRAME_BEGIN__:
-	.text
-	.align	2
-	.set	nomips16
-	.ent	__do_global_dtors_aux
-	.type	__do_global_dtors_aux, @function
-__do_global_dtors_aux:
-	.frame	$sp,32,$31		# vars= 0, regs= 1/0, args= 16, gp= 8
-	.mask	0x80000000,-4
-	.fmask	0x00000000,0
-	.set	noreorder
-	.cpload	$25
-	.set	nomacro
-	addiu	$sp,$sp,-32
-	sw	$31,28($sp)
-	.cprestore	16
-	lw	$2,%got(completed.1269)($28)
-	lbu	$2,%lo(completed.1269)($2)
-	bne	$2,$0,$L8
-	nop
-
-$L4:
-	lw	$2,%got(__cxa_finalize)($28)
-	beq	$2,$0,$L6
-	nop
-
-	lw	$2,%got(__dso_handle)($28)
-	lw	$4,0($2)
-	lw	$25,%call16(__cxa_finalize)($28)
-	.reloc	1f,R_MIPS_JALR,__cxa_finalize
-1:	jalr	$25
-	nop
-
-	lw	$28,16($sp)
-$L6:
-	lw	$2,%got(completed.1269)($28)
-	li	$3,1			# 0x1
-	sb	$3,%lo(completed.1269)($2)
-$L8:
-	lw	$31,28($sp)
-	addiu	$sp,$sp,32
-	j	$31
-	nop
-
-	.set	macro
-	.set	reorder
-	.end	__do_global_dtors_aux
-	.size	__do_global_dtors_aux, .-__do_global_dtors_aux
-	.local	completed.1269
-	.comm	completed.1269,1,1
-	.local	object.1265
-	.comm	object.1265,24,4
-	.weak	__cxa_finalize
-
-.include "__dso_handle.S"
-.include "atexit.S"
-	
diff --git a/ndk/platforms/android-9/arch-mips/src/crtbegin_so.S b/ndk/platforms/android-9/arch-mips/src/crtbegin_so.S
deleted file mode 100644
index 68dddfe..0000000
--- a/ndk/platforms/android-9/arch-mips/src/crtbegin_so.S
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-	.section .init_array, "aw"
-	.type __INIT_ARRAY__, @object
-	.globl __INIT_ARRAY__
-__INIT_ARRAY__:
-	.long -1
-
-	.section .fini_array, "aw"
-	.type __FINI_ARRAY__, @object
-	.globl __FINI_ARRAY__
-__FINI_ARRAY__:
-	.long -1
-	.long __do_global_dtors_aux
-
-	.abicalls
-	.text
-	.align	2
-	.set	nomips16
-	.ent	__do_global_dtors_aux
-	.type	__do_global_dtors_aux, @function
-__do_global_dtors_aux:
-	.frame	$sp,32,$31		# vars= 0, regs= 1/0, args= 16, gp= 8
-	.mask	0x80000000,-4
-	.fmask	0x00000000,0
-	.set	noreorder
-	.cpload	$25
-	.set	nomacro
-	addiu	$sp,$sp,-32
-	sw	$31,28($sp)
-	.cprestore	16
-	lw	$2,%got(completed.1269)($28)
-	lbu	$2,%lo(completed.1269)($2)
-	bne	$2,$0,$L8
-	nop
-
-$L4:
-	lw	$2,%got(__cxa_finalize)($28)
-	beq	$2,$0,$L6
-	nop
-
-	lw	$2,%got(__dso_handle)($28)
-	lw	$4,0($2)
-	lw	$25,%call16(__cxa_finalize)($28)
-	.reloc	1f,R_MIPS_JALR,__cxa_finalize
-1:	jalr	$25
-	nop
-
-	lw	$28,16($sp)
-$L6:
-	lw	$2,%got(completed.1269)($28)
-	li	$3,1			# 0x1
-	sb	$3,%lo(completed.1269)($2)
-$L8:
-	lw	$31,28($sp)
-	addiu	$sp,$sp,32
-	j	$31
-	nop
-
-	.set	macro
-	.set	reorder
-	.end	__do_global_dtors_aux
-	.size	__do_global_dtors_aux, .-__do_global_dtors_aux
-	.local	completed.1269
-	.comm	completed.1269,1,1
-	.weak	__cxa_finalize
-
-.include "__dso_handle.S"
-.include "atexit.S"
diff --git a/ndk/platforms/android-9/arch-mips/src/atexit.S b/ndk/platforms/android-9/arch-mips/src/crtbegin_so.c
similarity index 81%
copy from ndk/platforms/android-9/arch-mips/src/atexit.S
copy to ndk/platforms/android-9/arch-mips/src/crtbegin_so.c
index 7f0c820..925dc8c 100644
--- a/ndk/platforms/android-9/arch-mips/src/atexit.S
+++ b/ndk/platforms/android-9/arch-mips/src/crtbegin_so.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2013 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -25,19 +25,14 @@
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-	.text
-	.globl	atexit
-	.hidden	atexit
-	.type	atexit, @function
-	.align  4
-	.ent	atexit
-atexit:
-	.set	noreorder
-	.cpload	$t9
-	.set	reorder
-	la	$t9, __cxa_atexit
-	move	$a1, $0
-	la      $a2, __dso_handle
-	j	$t9
-	.size	atexit, .-atexit
-	.end	atexit
+
+extern void __cxa_finalize(void *);
+extern void *__dso_handle;
+
+__attribute__((visibility("hidden"),destructor))
+void __on_dlclose() {
+  __cxa_finalize(&__dso_handle);
+}
+
+#include "__dso_handle_so.h"
+#include "atexit.h"
diff --git a/ndk/platforms/android-9/arch-mips/src/crtbegin_static.S b/ndk/platforms/android-9/arch-mips/src/crtbegin_static.S
deleted file mode 100644
index 58bab82..0000000
--- a/ndk/platforms/android-9/arch-mips/src/crtbegin_static.S
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-	.text
-	.align 4
-	.type __start,@function
-	.globl __start
-	.globl _start
-
-# this is the small startup code that is first run when
-# any executable that is statically-linked with Bionic
-# runs.
-#
-# it's purpose is to call __libc_init with appropriate
-# arguments, which are:
-#
-#    - the address of the raw data block setup by the Linux
-#      kernel ELF loader
-#
-#    - address of an "onexit" function, not used on any
-#      platform supported by Bionic
-#
-#    - address of the "main" function of the program.
-#
-#    - address of the constructor list
-#
-
-	.ent	__start
-__start:	
-_start:
-	bal	1f
-1:
-	.set	noreorder
-	.cpload	$ra
-	.set	reorder
-
-	move	$a0, $sp
-	move	$a1, $0
-	la	$a2, main
-	la	$a3, 1f
-	subu	$sp, 32
-	la	$t9, __libc_init
-# Use jalr intead of jr so stack unwinding past __libc_init can terminate at _start
-	jalr	$t9
-	move	$t9, $0
-	j	$t9
-	.end	__start
-
-1:	.long	__PREINIT_ARRAY__
-	.long	__INIT_ARRAY__
-	.long	__FINI_ARRAY__
-	.long	__CTOR_LIST__
-	.long	__DTOR_LIST__
-
-	.section .preinit_array, "aw"
-	.type __PREINIT_ARRAY__, @object
-	.globl __PREINIT_ARRAY__
-__PREINIT_ARRAY__:
-	.long -1
-
-	.section .init_array, "aw"
-	.type __INIT_ARRAY__, @object
-	.globl __INIT_ARRAY__
-__INIT_ARRAY__:
-	.long -1
-	.long frame_dummy
-
-	.section .fini_array, "aw"
-	.type __FINI_ARRAY__, @object
-	.globl __FINI_ARRAY__
-__FINI_ARRAY__:
-	.long -1
-	.long __do_global_dtors_aux
-
-	.section .ctors, "aw"
-	.type __CTOR_LIST__, @object
-	.globl __CTOR_LIST__
-__CTOR_LIST__:
-	.long -1
-
-	.section .dtors, "aw"
-	.type __DTOR_LIST__, @object
-	.globl __DTOR_LIST__
-__DTOR_LIST__:
-	.long -1
-
-	.abicalls
-	.section	.eh_frame,"a",@progbits
-	.align	2
-	.type	__EH_FRAME_BEGIN__, @object
-	.size	__EH_FRAME_BEGIN__, 0
-__EH_FRAME_BEGIN__:
-	.text
-	.align	2
-	.set	nomips16
-	.ent	frame_dummy
-	.type	frame_dummy, @function
-frame_dummy:
-	.frame	$sp,32,$31		# vars= 0, regs= 1/0, args= 16, gp= 8
-	.mask	0x80000000,-4
-	.fmask	0x00000000,0
-	.set	noreorder
-	.cpload	$25
-	.set	nomacro
-	addiu	$sp,$sp,-32
-	sw	$31,28($sp)
-	.cprestore	16
-	lw	$2,%got(__register_frame_info)($28)
-	beq	$2,$0,$L1
-	nop
-
-	lw	$2,%got(__EH_FRAME_BEGIN__)($28)
-	addiu	$4,$2,%lo(__EH_FRAME_BEGIN__)
-	lw	$2,%got(object.1265)($28)
-	addiu	$5,$2,%lo(object.1265)
-	lw	$2,%call16(__register_frame_info)($28)
-	move	$25,$2
-	.reloc	1f,R_MIPS_JALR,__register_frame_info
-1:	jalr	$25
-	nop
-
-	lw	$28,16($sp)
-$L1:
-	lw	$31,28($sp)
-	addiu	$sp,$sp,32
-	j	$31
-	nop
-
-	.text
-	.set	macro
-	.set	reorder
-	.end	frame_dummy
-	.size	frame_dummy, .-frame_dummy
-	.align	2
-	.set	nomips16
-	.ent	__do_global_dtors_aux
-	.type	__do_global_dtors_aux, @function
-__do_global_dtors_aux:
-	.frame	$sp,32,$31		# vars= 0, regs= 1/0, args= 16, gp= 8
-	.mask	0x80000000,-4
-	.fmask	0x00000000,0
-	.set	noreorder
-	.cpload	$25
-	.set	nomacro
-	addiu	$sp,$sp,-32
-	sw	$31,28($sp)
-	.cprestore	16
-	lw	$2,%got(completed.1269)($28)
-	lbu	$2,%lo(completed.1269)($2)
-	bne	$2,$0,$L8
-	nop
-
-$L4:
-	lw	$2,%got(__cxa_finalize)($28)
-	beq	$2,$0,$L6
-	nop
-
-	lw	$2,%got(__dso_handle)($28)
-	lw	$2,0($2)
-	move	$4,$2
-	lw	$2,%call16(__cxa_finalize)($28)
-	move	$25,$2
-	.reloc	1f,R_MIPS_JALR,__cxa_finalize
-1:	jalr	$25
-	nop
-
-	lw	$28,16($sp)
-$L6:
-	lw	$2,%got(__deregister_frame_info)($28)
-	beq	$2,$0,$L7
-	nop
-
-	lw	$2,%got(__EH_FRAME_BEGIN__)($28)
-	addiu	$4,$2,%lo(__EH_FRAME_BEGIN__)
-	lw	$2,%call16(__deregister_frame_info)($28)
-	move	$25,$2
-	.reloc	1f,R_MIPS_JALR,__deregister_frame_info
-1:	jalr	$25
-	nop
-
-	lw	$28,16($sp)
-$L7:
-	lw	$2,%got(completed.1269)($28)
-	li	$3,1			# 0x1
-	sb	$3,%lo(completed.1269)($2)
-	b	$L3
-	nop
-
-$L8:
-	nop
-$L3:
-	lw	$31,28($sp)
-	addiu	$sp,$sp,32
-	j	$31
-	nop
-
-	.set	macro
-	.set	reorder
-	.end	__do_global_dtors_aux
-	.size	__do_global_dtors_aux, .-__do_global_dtors_aux
-	.local	completed.1269
-	.comm	completed.1269,1,1
-	.local	object.1265
-	.comm	object.1265,24,4
-	.weak	__deregister_frame_info
-	.weak	__cxa_finalize
-	.weak	__register_frame_info
-
-.include "__dso_handle.S"
-.include "atexit.S"
diff --git a/ndk/platforms/android-9/arch-x86/include/machine/endian.h b/ndk/platforms/android-9/arch-x86/include/machine/endian.h
index e7ad257..e1506b1 100644
--- a/ndk/platforms/android-9/arch-x86/include/machine/endian.h
+++ b/ndk/platforms/android-9/arch-x86/include/machine/endian.h
@@ -1,4 +1,4 @@
-/*	$OpenBSD: endian.h,v 1.14 2005/12/13 00:35:23 millert Exp $	*/
+/*	$OpenBSD: endian.h,v 1.17 2011/03/12 04:03:04 guenther Exp $	*/
 
 /*-
  * Copyright (c) 1997 Niklas Hallqvist.  All rights reserved.
@@ -24,38 +24,28 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef _I386_ENDIAN_H_
-#define _I386_ENDIAN_H_
+#ifndef _MACHINE_ENDIAN_H_
+#define _MACHINE_ENDIAN_H_
 
 #ifdef __GNUC__
 
-#if defined(_KERNEL) && !defined(I386_CPU)
-#define	__swap32md(x) ({						\
+#define	__swap32md(x) __statement({					\
 	uint32_t __swap32md_x = (x);					\
 									\
-	__asm ("bswap %1" : "+r" (__swap32md_x));			\
+	__asm ("bswap %0" : "+r" (__swap32md_x));			\
 	__swap32md_x;							\
 })
-#else
-#define	__swap32md(x) ({						\
-	uint32_t __swap32md_x = (x);					\
-									\
-	__asm ("rorw $8, %w1; rorl $16, %1; rorw $8, %w1" :		\
-	    "+r" (__swap32md_x));					\
-	__swap32md_x;							\
-})
-#endif	/* _KERNEL && !I386_CPU */
 
-#define	__swap64md(x) ({						\
+#define	__swap64md(x) __statement({					\
 	uint64_t __swap64md_x = (x);					\
 									\
 	(uint64_t)__swap32md(__swap64md_x >> 32) |			\
 	    (uint64_t)__swap32md(__swap64md_x & 0xffffffff) << 32;	\
 })
-#define	__swap16md(x) ({						\
+#define	__swap16md(x) __statement({					\
 	uint16_t __swap16md_x = (x);					\
 									\
-	__asm ("rorw $8, %w1" : "+r" (__swap16md_x));			\
+	__asm ("rorw $8, %w0" : "+r" (__swap16md_x));			\
 	__swap16md_x;							\
 })
 
@@ -68,4 +58,4 @@
 #include <sys/types.h>
 #include <sys/endian.h>
 
-#endif /* _I386_ENDIAN_H_ */
+#endif /* _MACHINE_ENDIAN_H_ */
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/crtbegin_dynamic.o b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/crtbegin_dynamic.o
new file mode 100644
index 0000000..d6c7afe
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/crtbegin_dynamic.o
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/crtend_android.o b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/crtend_android.o
new file mode 100644
index 0000000..173dad3
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/crtend_android.o
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/libc.so b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/libc.so
new file mode 100755
index 0000000..869c6df
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/libc.so
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/libdl.so b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/libdl.so
new file mode 100755
index 0000000..e8b639e
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib/libdl.so
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/crtbegin_dynamic.o b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/crtbegin_dynamic.o
new file mode 100644
index 0000000..86dfbd3
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/crtbegin_dynamic.o
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/crtend_android.o b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/crtend_android.o
new file mode 100644
index 0000000..8ee26ad
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/crtend_android.o
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/libc.so b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/libc.so
new file mode 100755
index 0000000..1698691
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/libc.so
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/libdl.so b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/libdl.so
new file mode 100755
index 0000000..ac53821
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/lib64/libdl.so
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/crtbegin_dynamic.o b/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/crtbegin_dynamic.o
new file mode 100644
index 0000000..e648904
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/crtbegin_dynamic.o
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/crtend_android.o b/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/crtend_android.o
new file mode 100644
index 0000000..7224f96
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/crtend_android.o
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/libc.so b/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/libc.so
new file mode 100755
index 0000000..6deba15
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/libc.so
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/libdl.so b/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/libdl.so
new file mode 100755
index 0000000..cd139c5
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/lib-bootstrap/libx32/libdl.so
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/lib/libc.a b/ndk/platforms/android-9/arch-x86/lib/libc.a
index 29b1726..788b92e 100644
--- a/ndk/platforms/android-9/arch-x86/lib/libc.a
+++ b/ndk/platforms/android-9/arch-x86/lib/libc.a
Binary files differ
diff --git a/ndk/platforms/android-9/arch-x86/src/__stack_chk_fail_local.S b/ndk/platforms/android-9/arch-x86/src/__stack_chk_fail_local.S
deleted file mode 100644
index 59fe86e..0000000
--- a/ndk/platforms/android-9/arch-x86/src/__stack_chk_fail_local.S
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-/*
- * Contributed by: Intel Corporation
- */
-
-	.text
-	.p2align 4,,15
-	.globl	__stack_chk_fail_local
-	.hidden	__stack_chk_fail_local
-	.type	__stack_chk_fail_local, @function
-
-__stack_chk_fail_local:
-#ifdef __PIC__
-	pushl	%ebx
-	call	__x86.get_pc_thunk.bx
-	addl	$_GLOBAL_OFFSET_TABLE_, %ebx
-	call	__stack_chk_fail@PLT
-#else /* PIC */
-	jmp   __stack_chk_fail
-#endif /* not PIC */
-
-	.size	__stack_chk_fail_local, .-__stack_chk_fail_local
diff --git a/ndk/platforms/android-9/arch-x86/src/__stack_chk_fail_local.h b/ndk/platforms/android-9/arch-x86/src/__stack_chk_fail_local.h
new file mode 100644
index 0000000..4f3699a
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/src/__stack_chk_fail_local.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+
+/*
+   __stack_chk_fail routine is runtime part of stack protector compiler
+   feature. It's implemented in libc and represents die routine when stack
+   corruption is detected.
+
+   Calls are generated by compiler and injected into user functions when
+   -fstack-protector* options are used.
+
+   __stack_chk_fail_local is wrapper for __stack_chk_fail. Compiler generates
+   wrapper calls instead for PIC code only and only on IA32 for optimization
+   purpose (see gcc/config/i386/i386.c). Wrapper body is always included into
+   executable or library. This is the idea of optimization.
+
+   Glibc is doing this via libc_nonshared.a which is linked automatically
+   everytime with libc.so. In bionic we have to bring it within crtfiles
+   because libc.so is real library and not a link script like libc.so at glibc.
+
+   For x86_64 or non-PIC code compiler always generates __stack_chk_fail calls.
+*/
+
+#ifdef __i386__
+#ifdef __PIC__
+extern void __stack_chk_fail();
+
+__attribute__ ((visibility ("hidden")))
+void __stack_chk_fail_local()
+{
+  __stack_chk_fail();
+}
+#endif
+#endif
diff --git a/ndk/platforms/android-9/arch-x86/src/atexit.S b/ndk/platforms/android-9/arch-x86/src/atexit.S
deleted file mode 100644
index b28f40b..0000000
--- a/ndk/platforms/android-9/arch-x86/src/atexit.S
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-	.text
-	.p2align 4,,15
-	.globl	atexit
-	.hidden	atexit
-	.type	atexit, @function
-atexit:
-	pushl	%ebp
-	movl	%esp, %ebp
-	pushl	%ebx
-	call	__x86.get_pc_thunk.bx
-	addl	$_GLOBAL_OFFSET_TABLE_, %ebx
-	subl	$20, %esp
-	movl	$0, 4(%esp)
-	movl	__dso_handle@GOTOFF(%ebx), %eax
-	movl	%eax, 8(%esp)
-	movl	8(%ebp), %eax
-	movl	%eax, (%esp)
-	call	__cxa_atexit@PLT
-	addl	$20, %esp
-	popl	%ebx
-	popl	%ebp
-	ret
-	.size	atexit, .-atexit
-
-	.section	.text.__x86.get_pc_thunk.bx,"axG",@progbits,__x86.get_pc_thunk.bx,comdat
-	.globl	__x86.get_pc_thunk.bx
-	.hidden	__x86.get_pc_thunk.bx
-	.type	__x86.get_pc_thunk.bx, @function
-__x86.get_pc_thunk.bx:
-	nop
-	nop
-	nop
-	nop
-	nop
-	nop
-	nop
-	nop
-	movl	(%esp), %ebx
-	ret
diff --git a/ndk/platforms/android-9/arch-mips/src/atexit.S b/ndk/platforms/android-9/arch-x86/src/atexit.h
similarity index 81%
copy from ndk/platforms/android-9/arch-mips/src/atexit.S
copy to ndk/platforms/android-9/arch-x86/src/atexit.h
index 7f0c820..bc776a8 100644
--- a/ndk/platforms/android-9/arch-mips/src/atexit.S
+++ b/ndk/platforms/android-9/arch-x86/src/atexit.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -25,19 +25,11 @@
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-	.text
-	.globl	atexit
-	.hidden	atexit
-	.type	atexit, @function
-	.align  4
-	.ent	atexit
-atexit:
-	.set	noreorder
-	.cpload	$t9
-	.set	reorder
-	la	$t9, __cxa_atexit
-	move	$a1, $0
-	la      $a2, __dso_handle
-	j	$t9
-	.size	atexit, .-atexit
-	.end	atexit
+
+extern void *__dso_handle;
+
+__attribute__ ((visibility ("hidden")))
+int atexit(void (*func)(void))
+{
+  return (__cxa_atexit((void (*)(void *))func, (void *)0, &__dso_handle));
+}
diff --git a/ndk/platforms/android-9/arch-mips/src/atexit.S b/ndk/platforms/android-9/arch-x86/src/crtbegin.c
similarity index 60%
copy from ndk/platforms/android-9/arch-mips/src/atexit.S
copy to ndk/platforms/android-9/arch-x86/src/crtbegin.c
index 7f0c820..43e9306 100644
--- a/ndk/platforms/android-9/arch-mips/src/atexit.S
+++ b/ndk/platforms/android-9/arch-x86/src/crtbegin.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2008 The Android Open Source Project
+ * Copyright (C) 2012 The Android Open Source Project
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
@@ -25,19 +25,32 @@
  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  * SUCH DAMAGE.
  */
-	.text
-	.globl	atexit
-	.hidden	atexit
-	.type	atexit, @function
-	.align  4
-	.ent	atexit
-atexit:
-	.set	noreorder
-	.cpload	$t9
-	.set	reorder
-	la	$t9, __cxa_atexit
-	move	$a1, $0
-	la      $a2, __dso_handle
-	j	$t9
-	.size	atexit, .-atexit
-	.end	atexit
+
+#include "../../bionic/libc_init_common.h"
+#include <stddef.h>
+#include <stdint.h>
+
+__attribute__ ((section (".preinit_array")))
+void (*__PREINIT_ARRAY__)(void) = (void (*)(void)) -1;
+
+__attribute__ ((section (".init_array")))
+void (*__INIT_ARRAY__)(void) = (void (*)(void)) -1;
+
+__attribute__ ((section (".fini_array")))
+void (*__FINI_ARRAY__)(void) = (void (*)(void)) -1;
+
+__LIBC_HIDDEN__
+__attribute__((force_align_arg_pointer))
+void _start() {
+  structors_array_t array;
+  array.preinit_array = &__PREINIT_ARRAY__;
+  array.init_array = &__INIT_ARRAY__;
+  array.fini_array = &__FINI_ARRAY__;
+
+  void* raw_args = (void*) ((uintptr_t) __builtin_frame_address(0) + sizeof(void*));
+  __libc_init(raw_args, NULL, &main, &array);
+}
+
+#include "__dso_handle.h"
+#include "atexit.h"
+#include "__stack_chk_fail_local.h"
diff --git a/ndk/platforms/android-9/arch-x86/src/crtbegin_dynamic.S b/ndk/platforms/android-9/arch-x86/src/crtbegin_dynamic.S
deleted file mode 100644
index 0ccad70..0000000
--- a/ndk/platforms/android-9/arch-x86/src/crtbegin_dynamic.S
+++ /dev/null
@@ -1,138 +0,0 @@
-# bionic/arch-x86/bionic/crtbegin_dynamic.S
-#
-# Copyright 2006, The Android Open Source Project
-#
-# 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.
-#     * Neither the name of Google Inc. nor the names of its contributors may
-#       be used to endorse or promote products derived from this software
-#       without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY Google Inc. ``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 Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
-# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
-# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
-# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-	.text
-	.align 4
-	.type _start, @function
-	.globl _start
-
-# this is the small startup code that is first run when
-# any executable that is dynamically-linked with Bionic
-# runs.
-#
-# it's purpose is to call __libc_init with appropriate
-# arguments, which are:
-#
-#    - the address of the raw data block setup by the Linux
-#      kernel ELF loader
-#
-#    - address of an "onexit" function, not used on any
-#      platform supported by Bionic
-#
-#    - address of the "main" function of the program. We
-#      can't hard-code it in the adr pseudo instruction
-#      so we use a tiny trampoline that will get relocated
-#      by the dynamic linker before this code runs
-#
-#    - address of the constructor list
-#
-_start:	
-        mov     %esp, %eax
-        # before push arguments, align the stack to a 16 byte boundary
-        andl    $~15, %esp
-        mov     $1f, %edx
-        pushl   %edx
-        mov     $0f, %edx
-        pushl   %edx
-        mov     $0, %edx
-        pushl   %edx
-        pushl   %eax
-        call    __libc_init
-
-0:  jmp   main
-
-1:  .long   __PREINIT_ARRAY__
-    .long   __INIT_ARRAY__
-    .long   __FINI_ARRAY__
-
-	.section .preinit_array, "aw"
-	.globl __PREINIT_ARRAY__
-__PREINIT_ARRAY__:
-	.long -1
-
-	.section .init_array, "aw"
-	.globl __INIT_ARRAY__
-__INIT_ARRAY__:
-	.long -1
-	.long	frame_dummy
-
-	.section .fini_array, "aw"
-	.globl __FINI_ARRAY__
-__FINI_ARRAY__:
-	.long -1
-	.long	__do_global_dtors_aux
-
-	.section	.eh_frame,"a",@progbits
-	.align 4
-	.type	__EH_FRAME_BEGIN__, @object
-__EH_FRAME_BEGIN__:
-	.text
-	.p2align 4,,15
-	.type	__do_global_dtors_aux, @function
-__do_global_dtors_aux:
-	pushl	%ebp
-	movl	%esp, %ebp
-	subl	$24, %esp
-	cmpb	$0, completed.4454
-	jne	.L4
-	movl	$__deregister_frame_info_bases, %eax
-	testl	%eax, %eax
-	je	.L3
-	movl	$__EH_FRAME_BEGIN__, (%esp)
-	call	__deregister_frame_info_bases
-.L3:
-	movb	$1, completed.4454
-.L4:
-	leave
-	ret
-	.text
-	.p2align 4,,15
-	.type	frame_dummy, @function
-frame_dummy:
-	pushl	%ebp
-	movl	$__register_frame_info_bases, %eax
-	movl	%esp, %ebp
-	subl	$24, %esp
-	testl	%eax, %eax
-	je	.L7
-	movl	%ebx, 12(%esp)
-	movl	$0, 8(%esp)
-	movl	$object.4466, 4(%esp)
-	movl	$__EH_FRAME_BEGIN__, (%esp)
-	call	__register_frame_info_bases
-.L7:
-	leave
-	ret
-	.local	completed.4454
-	.comm	completed.4454,1,1
-	.local	object.4466
-	.comm	object.4466,24,4
-	.weak	__register_frame_info_bases
-	.weak	__deregister_frame_info_bases
-
-#include "__dso_handle.S"
-#include "atexit.S"
-#include "__stack_chk_fail_local.S"
diff --git a/ndk/platforms/android-9/arch-x86/src/crtbegin_so.S b/ndk/platforms/android-9/arch-x86/src/crtbegin_so.S
deleted file mode 100644
index 99662fe..0000000
--- a/ndk/platforms/android-9/arch-x86/src/crtbegin_so.S
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *  * Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- *  * Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in
- *    the documentation and/or other materials provided with the
- *    distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-.section .init_array, "aw"
-.align 4
-.type __INIT_ARRAY__, @object
-.globl __INIT_ARRAY__
-__INIT_ARRAY__:
-    .long -1
-    .long frame_dummy
-
-.section .fini_array, "aw"
-.align 4
-.type __FINI_ARRAY__, @object
-.globl __FINI_ARRAY__
-__FINI_ARRAY__:
-    .long -1
-    .long __do_global_dtors_aux
-
-	.section	.eh_frame,"a",@progbits
-	.align 4
-	.type	__EH_FRAME_BEGIN__, @object
-__EH_FRAME_BEGIN__:
-	.text
-	.p2align 4,,15
-	.type	__do_global_dtors_aux, @function
-__do_global_dtors_aux:
-	pushl	%ebp
-	movl	%esp, %ebp
-	pushl	%ebx
-	call	__x86.get_pc_thunk.bx
-	addl	$_GLOBAL_OFFSET_TABLE_, %ebx
-	subl	$20, %esp
-	cmpb	$0, completed.4454@GOTOFF(%ebx)
-	jne	.L5
-	movl	__dso_handle@GOTOFF(%ebx), %eax
-	movl	%eax, (%esp)
-	call	__cxa_finalize@PLT
-	movl	__deregister_frame_info_bases@GOT(%ebx), %eax
-	testl	%eax, %eax
-	je	.L4
-	leal	__EH_FRAME_BEGIN__@GOTOFF(%ebx), %eax
-	movl	%eax, (%esp)
-	call	__deregister_frame_info_bases@PLT
-.L4:
-	movb	$1, completed.4454@GOTOFF(%ebx)
-.L5:
-	addl	$20, %esp
-	popl	%ebx
-	popl	%ebp
-	ret
-	.text
-	.p2align 4,,15
-	.type	frame_dummy, @function
-frame_dummy:
-	pushl	%ebp
-	movl	%esp, %ebp
-	pushl	%ebx
-	call	__x86.get_pc_thunk.bx
-	addl	$_GLOBAL_OFFSET_TABLE_, %ebx
-	subl	$20, %esp
-	movl	__register_frame_info_bases@GOT(%ebx), %eax
-	testl	%eax, %eax
-	je	.L8
-	leal	object.4469@GOTOFF(%ebx), %eax
-	movl	%eax, 4(%esp)
-	leal	__EH_FRAME_BEGIN__@GOTOFF(%ebx), %eax
-	movl	%ebx, 12(%esp)
-	movl	$0, 8(%esp)
-	movl	%eax, (%esp)
-	call	__register_frame_info_bases@PLT
-.L8:
-	addl	$20, %esp
-	popl	%ebx
-	popl	%ebp
-	ret
-	.local	completed.4454
-	.comm	completed.4454,1,1
-	.local	object.4469
-	.comm	object.4469,24,4
-	.weak	__register_frame_info_bases
-	.weak	__deregister_frame_info_bases
-
-#include "__dso_handle_so.S"
-#include "atexit.S"
-#include "__stack_chk_fail_local.S"
diff --git a/ndk/platforms/android-9/arch-x86/src/crtbegin_so.c b/ndk/platforms/android-9/arch-x86/src/crtbegin_so.c
new file mode 100644
index 0000000..30de6af
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86/src/crtbegin_so.c
@@ -0,0 +1,59 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *  * Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *  * Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in
+ *    the documentation and/or other materials provided with the
+ *    distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+extern void __cxa_finalize(void *);
+extern void *__dso_handle;
+
+__attribute__((visibility("hidden"),destructor))
+void __on_dlclose() {
+  __cxa_finalize(&__dso_handle);
+}
+
+/* CRT_LEGACY_WORKAROUND should only be defined when building
+ * this file as part of the platform's C library.
+ *
+ * The C library already defines a function named 'atexit()'
+ * for backwards compatibility with older NDK-generated binaries.
+ *
+ * For newer ones, 'atexit' is actually embedded in the C
+ * runtime objects that are linked into the final ELF
+ * binary (shared library or executable), and will call
+ * __cxa_atexit() in order to un-register any atexit()
+ * handler when a library is unloaded.
+ *
+ * This function must be global *and* hidden. Only the
+ * code inside the same ELF binary should be able to access it.
+ */
+
+#ifdef CRT_LEGACY_WORKAROUND
+#include "__dso_handle.h"
+#else
+#include "__dso_handle_so.h"
+#include "atexit.h"
+#include "__stack_chk_fail_local.h"
+#endif
diff --git a/ndk/platforms/android-9/arch-x86/src/crtbegin_static.S b/ndk/platforms/android-9/arch-x86/src/crtbegin_static.S
deleted file mode 100644
index 4fffecd..0000000
--- a/ndk/platforms/android-9/arch-x86/src/crtbegin_static.S
+++ /dev/null
@@ -1,138 +0,0 @@
-# bionic/arch-x86/bionic/crtbegin_static.S
-#
-# Copyright 2006, The Android Open Source Project
-#
-# 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.
-#     * Neither the name of Google Inc. nor the names of its contributors may
-#       be used to endorse or promote products derived from this software
-#       without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY Google Inc. ``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 Google Inc. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
-# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 
-# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
-# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
-# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
-# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-	.text
-	.align 4
-	.type _start, @function
-	.globl _start
-
-# this is the small startup code that is first run when
-# any executable that is statically-linked with Bionic
-# runs.
-#
-# it's purpose is to call __libc_init with appropriate
-# arguments, which are:
-#
-#    - the address of the raw data block setup by the Linux
-#      kernel ELF loader
-#
-#    - address of an "onexit" function, not used on any
-#      platform supported by Bionic
-#
-#    - address of the "main" function of the program. We
-#      can't hard-code it in the adr pseudo instruction
-#      so we use a tiny trampoline that will get relocated
-#      by the dynamic linker before this code runs
-#
-#    - address of the constructor list
-#
-_start:	
-        mov     %esp, %eax
-        # before push arguments, align the stack to a 16 byte boundary
-        andl    $~15, %esp
-        mov     $1f, %edx
-        pushl   %edx
-        mov     $0f, %edx
-        pushl   %edx
-        mov     $0, %edx
-        pushl   %edx
-        pushl   %eax
-        call    __libc_init
-
-0:  jmp   main
-
-1:  .long   __PREINIT_ARRAY__
-    .long   __INIT_ARRAY__
-    .long   __FINI_ARRAY__
-
-	.section .preinit_array, "aw"
-	.globl __PREINIT_ARRAY__
-__PREINIT_ARRAY__:
-	.long -1
-
-	.section .init_array, "aw"
-	.globl __INIT_ARRAY__
-__INIT_ARRAY__:
-	.long -1
-	.long	frame_dummy
-
-	.section .fini_array, "aw"
-	.globl __FINI_ARRAY__
-__FINI_ARRAY__:
-	.long -1
-	.long	__do_global_dtors_aux
-
-	.section	.eh_frame,"a",@progbits
-	.align 4
-	.type	__EH_FRAME_BEGIN__, @object
-__EH_FRAME_BEGIN__:
-	.text
-	.p2align 4,,15
-	.type	__do_global_dtors_aux, @function
-__do_global_dtors_aux:
-	pushl	%ebp
-	movl	%esp, %ebp
-	subl	$24, %esp
-	cmpb	$0, completed.4454
-	jne	.L4
-	movl	$__deregister_frame_info_bases, %eax
-	testl	%eax, %eax
-	je	.L3
-	movl	$__EH_FRAME_BEGIN__, (%esp)
-	call	__deregister_frame_info_bases
-.L3:
-	movb	$1, completed.4454
-.L4:
-	leave
-	ret
-	.text
-	.p2align 4,,15
-	.type	frame_dummy, @function
-frame_dummy:
-	pushl	%ebp
-	movl	$__register_frame_info_bases, %eax
-	movl	%esp, %ebp
-	subl	$24, %esp
-	testl	%eax, %eax
-	je	.L7
-	movl	%ebx, 12(%esp)
-	movl	$0, 8(%esp)
-	movl	$object.4466, 4(%esp)
-	movl	$__EH_FRAME_BEGIN__, (%esp)
-	call	__register_frame_info_bases
-.L7:
-	leave
-	ret
-	.local	completed.4454
-	.comm	completed.4454,1,1
-	.local	object.4466
-	.comm	object.4466,24,4
-	.weak	__register_frame_info_bases
-	.weak	__deregister_frame_info_bases
-
-#include "__dso_handle.S"
-#include "atexit.S"
-#include "__stack_chk_fail_local.S"
diff --git a/ndk/platforms/android-9/arch-x86/symbols/libc.so.functions.txt b/ndk/platforms/android-9/arch-x86/symbols/libc.so.functions.txt
index 2c7a608..2a77c44 100644
--- a/ndk/platforms/android-9/arch-x86/symbols/libc.so.functions.txt
+++ b/ndk/platforms/android-9/arch-x86/symbols/libc.so.functions.txt
@@ -264,6 +264,7 @@
 clock_gettime
 clock_nanosleep
 clock_settime
+clone
 close
 closedir
 closelog
diff --git a/ndk/platforms/android-9/arch-x86_64 b/ndk/platforms/android-9/arch-x86_64
new file mode 120000
index 0000000..fb7033c
--- /dev/null
+++ b/ndk/platforms/android-9/arch-x86_64
@@ -0,0 +1 @@
+arch-x86
\ No newline at end of file
diff --git a/ndk/platforms/android-9/include/android/input.h b/ndk/platforms/android-9/include/android/input.h
index 9449574..b9dffad 100644
--- a/ndk/platforms/android-9/include/android/input.h
+++ b/ndk/platforms/android-9/include/android/input.h
@@ -535,7 +535,7 @@
 
 /* Get the time that a historical movement occurred between this event and
  * the previous event, in the java.lang.System.nanoTime() time base. */
-int64_t AMotionEvent_getHistoricalEventTime(AInputEvent* motion_event,
+int64_t AMotionEvent_getHistoricalEventTime(const AInputEvent* motion_event,
         size_t history_index);
 
 /* Get the historical raw X coordinate of this event for the given pointer index that
@@ -562,14 +562,14 @@
  * occurred between this event and the previous motion event.
  * Whole numbers are pixels; the value may have a fraction for input devices
  * that are sub-pixel precise. */
-float AMotionEvent_getHistoricalX(AInputEvent* motion_event, size_t pointer_index,
+float AMotionEvent_getHistoricalX(const AInputEvent* motion_event, size_t pointer_index,
         size_t history_index);
 
 /* Get the historical Y coordinate of this event for the given pointer index that
  * occurred between this event and the previous motion event.
  * Whole numbers are pixels; the value may have a fraction for input devices
  * that are sub-pixel precise. */
-float AMotionEvent_getHistoricalY(AInputEvent* motion_event, size_t pointer_index,
+float AMotionEvent_getHistoricalY(const AInputEvent* motion_event, size_t pointer_index,
         size_t history_index);
 
 /* Get the historical pressure of this event for the given pointer index that
@@ -577,7 +577,7 @@
  * The pressure generally ranges from 0 (no pressure at all) to 1 (normal pressure),
  * although values higher than 1 may be generated depending on the calibration of
  * the input device. */
-float AMotionEvent_getHistoricalPressure(AInputEvent* motion_event, size_t pointer_index,
+float AMotionEvent_getHistoricalPressure(const AInputEvent* motion_event, size_t pointer_index,
         size_t history_index);
 
 /* Get the current scaled value of the approximate size for the given pointer index that
@@ -587,7 +587,7 @@
  * touch is normalized with the device specific range of values
  * and scaled to a value between 0 and 1.  The value of size can be used to
  * determine fat touch events. */
-float AMotionEvent_getHistoricalSize(AInputEvent* motion_event, size_t pointer_index,
+float AMotionEvent_getHistoricalSize(const AInputEvent* motion_event, size_t pointer_index,
         size_t history_index);
 
 /* Get the historical length of the major axis of an ellipse that describes the touch area
diff --git a/ndk/platforms/android-9/include/wchar.h b/ndk/platforms/android-9/include/wchar.h
index fea648c..806e3d1 100644
--- a/ndk/platforms/android-9/include/wchar.h
+++ b/ndk/platforms/android-9/include/wchar.h
@@ -41,13 +41,7 @@
 #include <malloc.h>
 
 #include <stddef.h>
-
-/* IMPORTANT: Any code that relies on wide character support is essentially
- *            non-portable and/or broken. the only reason this header exist
- *            is because I'm really a nice guy. However, I'm not nice enough
- *            to provide you with a real implementation. instead wchar_t == char
- *            and all wc functions are stubs to their "normal" equivalent...
- */
+#include <sys/_wchar_limits.h>
 
 __BEGIN_DECLS
 
@@ -71,8 +65,6 @@
     WC_TYPE_MAX
 } wctype_t;
 
-#define  WCHAR_MAX   INT_MAX
-#define  WCHAR_MIN   INT_MIN
 #define  WEOF        ((wint_t)(-1))
 
 extern wint_t            btowc(int);
diff --git a/ndk/sources/android/libportable/Android.mk b/ndk/sources/android/libportable/Android.mk
index 63428e5..dde8e19 100644
--- a/ndk/sources/android/libportable/Android.mk
+++ b/ndk/sources/android/libportable/Android.mk
@@ -57,7 +57,8 @@
 			arch-mips/timer.c \
 			arch-mips/timerfd.c \
 			arch-mips/waitpid.c \
-			arch-mips/fenv.c
+			arch-mips/fenv.c \
+			arch-mips/md_swap.c
 
 libportable_arch_src_files += \
 			arch-mips/_setjmp.S \
@@ -69,7 +70,8 @@
 ifeq ($(TARGET_ARCH),arm)
 libportable_arch_src_files += \
 			arch-arm/unwind.c \
-			arch-arm/fenv.c
+			arch-arm/fenv.c \
+			arch-arm/md_swap.c
 endif
 
 ifeq ($(TARGET_ARCH),x86)
@@ -79,7 +81,8 @@
 			arch-x86/ioctl.c \
 			arch-x86/open.c \
 			arch-x86/stat.c \
-			arch-x86/fenv.c
+			arch-x86/fenv.c \
+			arch-x86/md_swap.c
 endif
 
 LOCAL_SRC_FILES := \
diff --git a/ndk/sources/android/libportable/arch-arm/md_swap.c b/ndk/sources/android/libportable/arch-arm/md_swap.c
new file mode 100644
index 0000000..47652e6
--- /dev/null
+++ b/ndk/sources/android/libportable/arch-arm/md_swap.c
@@ -0,0 +1,40 @@
+/*
+ * Copyright 2013, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <portability.h>
+#include <sys/types.h>
+
+/*
+ * REV and REV16 weren't available on ARM5 or ARM4.
+ */
+#if !defined __ARM_ARCH_5__ && !defined __ARM_ARCH_5T__ && \
+    !defined __ARM_ARCH_5TE__ && !defined __ARM_ARCH_5TEJ__ && \
+    !defined __ARM_ARCH_4T__ && !defined __ARM_ARCH_4__
+
+uint16_t WRAP(__swap16md)(uint16_t x) {
+    register uint16_t _x = (x);
+    __asm volatile ("rev16 %0, %0" : "+l" (_x));
+    return _x;
+}
+
+uint32_t WRAP(__swap32md)(uint32_t x) {
+    register uint32_t _x = (x);
+    __asm volatile ("rev %0, %0" : "+l" (_x));
+    return _x;
+}
+
+#endif
+
diff --git a/ndk/sources/android/libportable/arch-mips/md_swap.c b/ndk/sources/android/libportable/arch-mips/md_swap.c
new file mode 100644
index 0000000..59e4224
--- /dev/null
+++ b/ndk/sources/android/libportable/arch-mips/md_swap.c
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2013, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <portability.h>
+#include <sys/types.h>
+#include <endian.h>
+
+#if defined(__mips_isa_rev) && (__mips_isa_rev >= 2)
+
+uint16_t WRAP(__swap16md)(uint16_t x) {
+    register uint16_t _x = x;
+    register uint16_t _r;
+    __asm volatile ("wsbh %0, %1" : "=r" (_r) : "r" (_x));
+    return _r;
+}
+
+uint32_t WRAP(__swap32md)(uint32_t x) {
+    register uint32_t _x = x;
+    register uint32_t _r;
+    __asm volatile ("wsbh %0, %1; rotr %0, %0, 16" : "=r" (_r) : "r" (_x));
+    return _r;
+}
+
+#endif
+
diff --git a/ndk/sources/android/libportable/arch-mips/pthread.c b/ndk/sources/android/libportable/arch-mips/pthread.c
index 41d9478..5b75623 100644
--- a/ndk/sources/android/libportable/arch-mips/pthread.c
+++ b/ndk/sources/android/libportable/arch-mips/pthread.c
@@ -288,13 +288,14 @@
 int WRAP(pthread_sigmask)(int portable_how, const sigset_portable_t *portable_sigset,
                              sigset_portable_t *portable_oldset)
 {
+    extern int REAL(pthread_sigmask)(int how, const sigset_t *set, sigset_t *oset);
     int portable_ret, ret;
 
     ALOGV(" ");
     ALOGV("%s(portable_how:%d portable_sigset:%p, portable_oldset:%p)", __func__,
               portable_how,   portable_sigset,    portable_oldset);
 
-    ret = do_sigmask(portable_how, portable_sigset, portable_oldset, pthread_sigmask, NULL);
+    ret = do_sigmask(portable_how, portable_sigset, portable_oldset, REAL(pthread_sigmask), NULL);
 
     portable_ret = errno_ntop(ret);
 
diff --git a/ndk/sources/android/libportable/arch-mips/signal.c b/ndk/sources/android/libportable/arch-mips/signal.c
index 4d2d258..a06eff7 100644
--- a/ndk/sources/android/libportable/arch-mips/signal.c
+++ b/ndk/sources/android/libportable/arch-mips/signal.c
@@ -63,6 +63,7 @@
     char *name;
 
     switch(portable_signum) {
+    case 0:                     name = "SIG_0_PORTABLE:0";              break;
     case SIGHUP_PORTABLE:       name = "SIGHUP_PORTABLE:1";             break;
     case SIGINT_PORTABLE:       name = "SIGINT_PORTABLE:2";             break;
     case SIGQUIT_PORTABLE:      name = "SIGQUIT_PORTABLE:3";            break;
@@ -140,6 +141,7 @@
     char *name;
 
     switch(mips_signum) {
+    case 0:             name = "SIG_0:0";       break;
     case SIGHUP:        name = "SIGHUP:1";      break;
     case SIGINT:        name = "SIGINT:2";      break;
     case SIGQUIT:       name = "SIGQUIT:3";     break;
@@ -223,6 +225,10 @@
     int mips_signum = -1;
 
     switch(portable_signum) {
+
+    case 0:                             /* 0 */
+        return 0;
+
     case SIGHUP_PORTABLE:               /* 1 */
         return SIGHUP;
 
@@ -340,8 +346,8 @@
         } else if (portable_signum > NSIG_PORTABLE) {
             mips_signum = (portable_signum - NSIG_PORTABLE) +  NSIG;
         } else {
-            ALOGE("%s: 0 <= portable_signum:%d <= NSIG_PORTABLE:%d; Not supported, return(0);",
-                  __func__, portable_signum,      NSIG_PORTABLE);
+            ALOGE("%s: 0 < portable_signum:%d <= NSIG_PORTABLE:%d; Not supported, return(0);",
+                 __func__, portable_signum,      NSIG_PORTABLE);
 
             mips_signum = 0;
         }
@@ -362,6 +368,9 @@
     int portable_ssignum = -1;
 
     switch(mips_signum) {
+    case 0:                             /* 0 */
+        return 0;
+
     case SIGHUP:                        /* 1 */
         return SIGHUP_PORTABLE;
 
@@ -696,9 +705,10 @@
 
     mips_signum = signum_pton(portable_signum);
 
-    if ((portable_signum != 0) && ((mips_signum <= 0) || (mips_signum > NSIG))) {
+    if ((mips_signum <= 0) || (mips_signum > NSIG)) {
         /*
-         * Invalid request; Let the kernel generate the proper return value and set errno.
+         * Invalid signal number, perhaps zero. Let the kernel generate the
+         * proper return value and set errno.
          */
         mips_handler = sighandler_pton(portable_handler, 0);
         rv = mips_signal_fn(mips_signum, mips_handler);
@@ -735,6 +745,7 @@
  */
 sighandler_portable_t WRAP(signal)(int portable_signum, sighandler_portable_t handler)
 {
+    extern __sighandler_t REAL(bsd_signal)(int, __sighandler_t);
     sighandler_portable_t rv;
 
     ALOGV(" ");
@@ -742,7 +753,7 @@
               portable_signum,    handler);
 
     /* bsd does a SA_RESTART */
-    rv = do_signal_portable(portable_signum, handler, bsd_signal);
+    rv = do_signal_portable(portable_signum, handler, REAL(bsd_signal));
 
     ALOGV("%s: return(ret:%p); }", __func__, rv);
     return rv;
@@ -751,6 +762,7 @@
 
 sighandler_portable_t WRAP(sysv_signal)(int portable_signum, sighandler_portable_t handler)
 {
+    extern __sighandler_t REAL(sysv_signal)(int, __sighandler_t);
     sighandler_portable_t rv;
 
     ALOGV(" ");
@@ -758,7 +770,7 @@
               portable_signum,    handler);
 
     /* sysv does a SA_RESETHAND */
-    rv = do_signal_portable(portable_signum, handler, sysv_signal);
+    rv = do_signal_portable(portable_signum, handler, REAL(sysv_signal));
 
     ALOGV("%s: return(ret:%p); }", __func__, rv);
     return rv;
@@ -775,6 +787,7 @@
 
 sighandler_portable_t WRAP(bsd_signal)(int portable_signum, sighandler_portable_t handler)
 {
+    extern __sighandler_t REAL(bsd_signal)(int, __sighandler_t);
     sighandler_portable_t rv;
 
     ALOGV(" ");
@@ -782,7 +795,7 @@
               portable_signum,    handler);
 
     /* bsd does a SA_RESTART */
-    rv = do_signal_portable(portable_signum, handler, bsd_signal);
+    rv = do_signal_portable(portable_signum, handler, REAL(bsd_signal));
 
     ALOGV("%s: return(ret:%p); }", __func__, rv);
     return rv;
@@ -801,6 +814,11 @@
 
     mips_signum = signum_pton(portable_signum);
 
+    /*
+     * SIG_0 gets passed down to the kernel to test for the existence of a process.
+     * If a non-zero portable_signum has been mapped to 0,
+     * it's unsupported and will be ignored.
+     */
     if ((portable_signum != 0) && (mips_signum == 0)) {
         rv = 0;
     } else {
@@ -876,6 +894,10 @@
 
     mips_signum = signum_pton(portable_signum);
 
+    /*
+     * If a non-zero portable_signum has been mapped to 0,
+     * it is unsupported and will be ignored.
+     */
     if ((portable_signum != 0) && (mips_signum == 0))
         rv = 0;
     else
@@ -895,6 +917,11 @@
 
     ALOGV("%s(portable_signum:%d:'%s') {", __func__, portable_signum, portable_signame);
 
+    /*
+     * SIG_0 gets passed down to the kernel to test for the existence of a process.
+     * If a non-zero portable_signum has been mapped to 0,
+     * it's unsupported and will be ignored.
+     */
     if ((portable_signum != 0) && (mips_signum == 0))
         rv = 0;
     else
@@ -1098,8 +1125,11 @@
     mips_signum = signum_pton(portable_signum);
     mips_signame = map_mips_signum_to_name(mips_signum);
 
+    /*
+     * If a non-zero portable_signum has been mapped to 0,
+     * it's unsupported and will be ignored.
+     */
     if ((portable_signum != 0) && (mips_signum == 0)) {
-        /* We got a portable signum that we can't map; Ignore the request */
         rv = 0;
         goto done;
     }
@@ -1407,9 +1437,11 @@
 
     mips_signum = signum_pton(portable_signum);
 
+    /*
+     * If a non-zero portable_signum has been mapped to 0,
+     * it's unsupported and will be ignored.
+     */
     if ((portable_signum != 0) && (mips_signum == 0)) {
-        ALOGE("%s: Unsupported portable_signum:%d; Ignoring.", __func__,
-                               portable_signum);
         rv = 0;
     } else {
         rv = REAL(siginterrupt)(mips_signum, flag);
@@ -1663,6 +1695,15 @@
 
     native_sig = signum_pton(portable_sig);
 
+    /*
+     * If a non-zero portable_signum has been mapped to 0,
+     * it's unsupported and will be ignored.
+     */
+    if ((portable_sig != 0) && (native_sig == 0)) {
+        rv = 0;
+        goto done;
+    }
+
     if (portable_sip != NULL) {
         native_sip = &native_siginfo;
         siginfo_pton(portable_sip, native_sip);
@@ -1671,6 +1712,7 @@
     }
     rv = syscall(__NR_rt_sigqueueinfo, pid, native_sig, native_sip);
 
+done:
     ALOGV("%s: return(rv:%d); }", __func__, rv);
     return rv;
 }
@@ -1694,6 +1736,14 @@
 
     native_sig = signum_pton(portable_sig);
 
+    /*
+     * If a non-zero portable_signum has been mapped to 0,
+     * it's unsupported and will be ignored.
+     */
+    if ((portable_sig != 0) && (native_sig == 0)) {
+        rv = 0;
+        goto done;
+    }
     if (portable_sip != NULL) {
         native_sip = &native_siginfo;
         siginfo_pton(portable_sip, native_sip);
@@ -1702,6 +1752,7 @@
     }
     rv = syscall(__NR_rt_tgsigqueueinfo, pid, native_sig, native_sip);
 
+done:
     ALOGV("%s: return(rv:%d); }", __func__, rv);
     return rv;
 }
diff --git a/ndk/sources/android/libportable/arch-mips/waitpid.c b/ndk/sources/android/libportable/arch-mips/waitpid.c
index 77e6283..f1d2bcf 100644
--- a/ndk/sources/android/libportable/arch-mips/waitpid.c
+++ b/ndk/sources/android/libportable/arch-mips/waitpid.c
@@ -25,21 +25,102 @@
 #define PORTABLE_TAG            "waitpid_portable"
 #include <log_portable.h>
 
+/*
+ * Converts native status information at *status to portable.
+ */
+static void status_ntop(int *status)
+{
+    int portable_status;
+
+    ALOGV("%s(status:%p) {", __func__,
+              status);
+
+    ASSERT(status != NULL);
+
+    /*
+     * The interpretation of status is documented in the wait(2) manual page
+     * and the implementation is in bionic/libc/include/sys/wait.h
+     */
+    if (WIFSIGNALED(*status))
+        portable_status = (*status & ~0x7f) | signum_ntop(WTERMSIG(*status));
+    else if (WIFSTOPPED(*status))
+        portable_status = (*status & ~0xff00) | (signum_ntop(WSTOPSIG(*status)) << 8);
+    else
+        portable_status = *status;
+
+    ALOGV("%s: (*status):0x%08x = portable_status:0x%08x", __func__,
+               *status,           portable_status);
+
+    *status = portable_status;
+
+    ALOGV("%s: return; }", __func__);
+}
+
+
 pid_t WRAP(waitpid)(pid_t pid, int *status, int options)
 {
-    pid_t ret;
+    pid_t rv;
 
-    ret = REAL(waitpid)(pid, status, options);
-    if (status && ret > 0) {
-        /*
-         * Status layout is identical, so just the signal
-         * number needs to be changed.
-         */
-        if (WIFSIGNALED(*status))
-            *status = (*status & ~0x7f) | signum_ntop(WTERMSIG(*status));
-        else if (WIFSTOPPED(*status))
-            *status = (*status & ~0xff00) | (signum_ntop(WSTOPSIG(*status)) << 8);
-    }
+    ALOGV("%s(pid:%d, status:%p, options:0x%x) {", __func__,
+              pid,    status,    options);
 
-    return ret;
+    rv = REAL(waitpid)(pid, status, options);
+    if (rv > 0 && status)
+        status_ntop(status);
+
+    ALOGV("%s: return rv:%d; }", __func__, rv);
+    return rv;
+}
+
+
+pid_t WRAP(wait)(int *status)
+{
+    pid_t rv;
+
+    ALOGV("%s(status:%p) {", __func__,
+              status);
+
+    rv = REAL(wait)(status);
+    if (rv > 0 && status)
+        status_ntop(status);
+
+    ALOGV("%s: return rv:%d; }", __func__, rv);
+    return rv;
+}
+
+
+pid_t WRAP(wait3)(int *status, int options, struct rusage *rusage)
+{
+    pid_t rv;
+
+    ALOGV("%s(status:%p, options:0x%x, rusage:%p) {", __func__,
+              status,    options,      rusage);
+
+    rv = REAL(wait3)(status, options, rusage);
+    if (rv > 0 && status)
+        status_ntop(status);
+
+    ALOGV("%s: return rv:%d; }", __func__, rv);
+    return rv;
+}
+
+// FIXME: WORKAROUND after Android wait4 has been implemented
+pid_t REAL(wait4)(pid_t p, int *s, int o, struct rusage *r) {
+  extern pid_t  __wait4(pid_t, int *, int, struct rusage *);
+  return __wait4(p,s,o,r);
+}
+
+pid_t WRAP(wait4)(pid_t pid, int *status, int options, struct rusage *rusage)
+{
+    pid_t rv;
+
+    ALOGV("%s(pid:%d, status:%p, options:0x%x, rusage:%p) {", __func__,
+              pid,    status,    options,      rusage);
+
+    rv = REAL(wait4)(pid, status, options, rusage);
+    if (rv > 0 && status)
+        status_ntop(status);
+
+    ALOGV("%s: return rv:%d; }", __func__, rv);
+    return rv;
 }
diff --git a/ndk/sources/android/libportable/arch-x86/md_swap.c b/ndk/sources/android/libportable/arch-x86/md_swap.c
new file mode 100644
index 0000000..60851d0
--- /dev/null
+++ b/ndk/sources/android/libportable/arch-x86/md_swap.c
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2013, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <portability.h>
+#include <sys/types.h>
+
+uint16_t WRAP(__swap16md)(uint16_t x) {
+    register uint16_t _x = (x);
+    __asm volatile ("rorw $8, %w0" : "+r" (_x));
+    return _x;
+}
+
+uint32_t WRAP(__swap32md)(uint32_t x) {
+    register uint32_t _x = (x);
+    __asm volatile ("bswap %0" : "+r" (_x));
+    return _x;
+}
+
diff --git a/ndk/tools/headers-diff-bionic-vs-ndk.py b/ndk/tools/headers-diff-bionic-vs-ndk.py
new file mode 100755
index 0000000..1f8a9e3
--- /dev/null
+++ b/ndk/tools/headers-diff-bionic-vs-ndk.py
@@ -0,0 +1,248 @@
+#!/usr/bin/python
+#
+# This tool is used to compare headers between Bionic and NDK
+# script should be in development/ndk/tools for correct roots autodetection
+#
+
+import sys, os, os.path
+import subprocess
+import argparse, textwrap
+
+class FileCollector:
+    """Collect headers from Bionic and sysroot
+
+    sysincludes data format:
+    sysincludes                     -- dict with arch as key
+    sysincludes[arch]               -- dict with includes root as key
+    sysincludes[arch][root]         -- dict with header name as key
+    sysincludes[arch][root][header] -- list [last_platform, ..., first_platform]
+    """
+
+    def __init__(self, platforms_root, archs):
+        """Init platform roots and structures before collecting"""
+        self.platforms = []
+        self.archs = archs
+        self.sysincludes = {}
+        for arch in self.archs:
+            self.sysincludes[arch] = {}
+
+        ## scaning available platforms ##
+        for dirname in os.listdir(platforms_root):
+            path = os.path.join(platforms_root, dirname)
+            if os.path.isdir(path) and ('android' in dirname):
+                self.platforms.append(dirname)
+        try:
+            self.platforms.sort(key = lambda s: int(s.split('-')[1]))
+            self.root = platforms_root
+        except Exception:
+            print 'Wrong platforms list \n{0}'.format(str(self.platforms))
+
+    def scan_dir(self, root):
+        """Non-recursive file scan in directory"""
+        files = []
+        for filename in os.listdir(root):
+            if os.path.isfile(os.path.join(root, filename)):
+                files.append(filename)
+        return files
+
+    def scan_includes(self, root):
+        """Recursive includes scan in given root"""
+        includes = []
+        includes_root = os.path.join(root, 'include')
+        if not os.path.isdir(includes_root):
+            return includes
+
+        ## recursive scanning ##
+        includes.append(('', self.scan_dir(includes_root)))
+        for dirname, dirnames, filenames in os.walk(includes_root):
+            for subdirname in dirnames:
+                path = os.path.join(dirname, subdirname)
+                relpath = os.path.relpath(path, includes_root)
+                includes.append((relpath, self.scan_dir(path)))
+
+        return includes
+
+    def scan_archs_includes(self, root):
+        """Scan includes for all defined archs in given root"""
+        includes = {}
+        includes['common'] = self.scan_includes(root)
+
+        for arch in [a for a in self.archs if a != 'common']:
+            arch_root = os.path.join(root, arch)
+            includes[arch] = self.scan_includes(arch_root)
+
+        return includes
+
+    def scan_platform_includes(self, platform):
+        """Scan all platform includes of one layer"""
+        platform_root = os.path.join(self.root, platform)
+        return self.scan_archs_includes(platform_root)
+
+    def scan_bionic_includes(self, bionic_root):
+        """Scan Bionic's libc includes"""
+        self.bionic_root = bionic_root
+        self.bionic_includes = self.scan_archs_includes(bionic_root)
+
+    def append_sysincludes(self, arch, root, headers, platform):
+        """Merge new platform includes layer with current sysincludes"""
+        if not (root in self.sysincludes[arch]):
+            self.sysincludes[arch][root] = {}
+
+        for include in headers:
+            if include in self.sysincludes[arch][root]:
+                last_platform = self.sysincludes[arch][root][include][0]
+                if platform != last_platform:
+                    self.sysincludes[arch][root][include].insert(0, platform)
+            else:
+                self.sysincludes[arch][root][include] = [platform]
+
+    def update_to_platform(self, platform):
+        """Update sysincludes state by applying new platform layer"""
+        new_includes = self.scan_platform_includes(platform)
+        for arch in self.archs:
+            for pack in new_includes[arch]:
+                self.append_sysincludes(arch, pack[0], pack[1], platform)
+
+    def scan_sysincludes(self, target_platform):
+        """Fully automated sysincludes collector upto specified platform"""
+        version = int(target_platform.split('-')[1])
+        layers = filter(lambda s: int(s.split('-')[1]) <= version, self.platforms)
+        for platform in layers:
+            self.update_to_platform(platform)
+
+
+class BionicSysincludes:
+    def set_roots(self):
+        """Automated roots initialization (AOSP oriented)"""
+        script_root = os.path.dirname(os.path.realpath(__file__))
+        self.aosp_root      = os.path.normpath(os.path.join(script_root, '../../..'))
+        self.platforms_root = os.path.join(self.aosp_root, 'development/ndk/platforms')
+        self.bionic_root    = os.path.join(self.aosp_root, 'bionic/libc')
+
+    def scan_includes(self):
+        """Scan all required includes"""
+        self.collector = FileCollector(self.platforms_root, self.archs)
+        ## detecting latest platform ##
+        self.platforms = self.collector.platforms
+        latest_platform = self.platforms[-1:][0]
+        ## scanning both includes repositories ##
+        self.collector.scan_sysincludes(latest_platform)
+        self.collector.scan_bionic_includes(self.bionic_root)
+        ## scan results ##
+        self.sysincludes     = self.collector.sysincludes
+        self.bionic_includes = self.collector.bionic_includes
+
+    def git_diff(self, file_origin, file_probe):
+        """Difference routine based on git diff"""
+        try:
+            subprocess.check_output(['git', 'diff', '--no-index', file_origin, file_probe])
+        except subprocess.CalledProcessError as error:
+            return error.output
+        return None
+
+    def match_with_bionic_includes(self):
+        """Compare headers between Bionic and sysroot"""
+        self.diffs = {}
+        ## for every arch ##
+        for arch in self.archs:
+            arch_root = (lambda s: s if s != 'common' else '')(arch)
+            ## for every includes directory ##
+            for pack in self.bionic_includes[arch]:
+                root = pack[0]
+                path_bionic = os.path.join(self.bionic_root, arch_root, 'include', root)
+                ## for every header that both in Bionic and sysroot ##
+                for include in pack[1]:
+                    if include in self.sysincludes[arch][root]:
+                        ## completing paths ##
+                        platform = self.sysincludes[arch][root][include][0]
+                        file_origin = os.path.join(path_bionic, include)
+                        file_probe  = os.path.join(self.platforms_root, platform, arch_root, 'include', root, include)
+                        ## comparison by git diff ##
+                        output = self.git_diff(file_origin, file_probe)
+                        if output is not None:
+                            if arch not in self.diffs:
+                                self.diffs[arch] = {}
+                            if root not in self.diffs[arch]:
+                                self.diffs[arch][root] = {}
+                            ## storing git diff ##
+                            self.diffs[arch][root][include] = output
+
+    def print_history(self, arch, root, header):
+        """Print human-readable list header updates across platforms"""
+        history = self.sysincludes[arch][root][header]
+        for platform in self.platforms:
+            entry = (lambda s: s.split('-')[1] if s in history else '-')(platform)
+            print '{0:3}'.format(entry),
+        print ''
+
+    def show_and_store_results(self):
+        """Print summary list of headers and write diff-report to file"""
+        try:
+            diff_fd = open(self.diff_file, 'w')
+            for arch in self.archs:
+                if arch not in self.diffs:
+                    continue
+                print '{0}/'.format(arch)
+                roots = self.diffs[arch].keys()
+                roots.sort()
+                for root in roots:
+                    print '    {0}/'.format((lambda s: s if s != '' else '../include')(root))
+                    includes = self.diffs[arch][root].keys()
+                    includes.sort()
+                    for include in includes:
+                        print '        {0:32}'.format(include),
+                        self.print_history(arch, root, include)
+                        diff = self.diffs[arch][root][include]
+                        diff_fd.write(diff)
+                        diff_fd.write('\n\n')
+                    print ''
+                print ''
+
+        finally:
+            diff_fd.close()
+
+    def main(self):
+        self.set_roots()
+        self.scan_includes()
+        self.match_with_bionic_includes()
+        self.show_and_store_results()
+
+if __name__ == '__main__':
+    ## configuring command line parser ##
+    parser = argparse.ArgumentParser(formatter_class = argparse.RawTextHelpFormatter,
+                                     description = 'Headers comparison tool between bionic and NDK platforms')
+    parser.epilog = textwrap.dedent('''
+    output format:
+    {architecture}/
+        {directory}/
+            {header name}.h  {platforms history}
+
+    platforms history format:
+        number X means header has been changed in android-X
+        `-\' means it is the same
+
+    diff-report format:
+        git diff output for all headers
+        use --diff option to specify filename
+    ''')
+
+    parser.add_argument('--archs', metavar = 'A', nargs = '+',
+                        default = ['common', 'arm', 'x86', 'mips'],
+                        help = 'list of architectures\n(default: common arm x86 mips)')
+    parser.add_argument('--diff', metavar = 'FILE', nargs = 1,
+                        default = ['headers-diff-bionic-vs-ndk.diff'],
+                        help = 'diff-report filename\n(default: `bionic-vs-sysincludes_report.diff\')')
+
+    ## parsing arguments ##
+    args = parser.parse_args()
+
+    ## doing work ##
+    app = BionicSysincludes()
+    app.archs = map((lambda s: 'arch-{0}'.format(s) if s != 'common' else s), args.archs)
+    app.diff_file = args.diff[0]
+    app.main()
+
+    print 'Headers listed above are DIFFERENT in Bionic and NDK platforms'
+    print 'See `{0}\' for details'.format(app.diff_file)
+    print 'See --help for format description.'
+    print ''
diff --git a/samples/ApiDemos/res/layout/date_widgets_example_1.xml b/samples/ApiDemos/res/layout/date_widgets_example_1.xml
index b9db6a0..9313cdf 100644
--- a/samples/ApiDemos/res/layout/date_widgets_example_1.xml
+++ b/samples/ApiDemos/res/layout/date_widgets_example_1.xml
@@ -32,9 +32,14 @@
             android:layout_height="wrap_content"
             android:text="@string/date_widgets_example_pickDate_text"/>
 
-    <Button android:id="@+id/pickTime"
+    <Button android:id="@+id/pickTime12"
             android:layout_width="wrap_content"
             android:layout_height="wrap_content"
-            android:text="@string/date_widgets_example_pickTime_text"/>
+            android:text="@string/date_widgets_example_pickTime12_text"/>
+
+    <Button android:id="@+id/pickTime24"
+            android:layout_width="wrap_content"
+            android:layout_height="wrap_content"
+            android:text="@string/date_widgets_example_pickTime24_text"/>
 
 </LinearLayout>
diff --git a/samples/ApiDemos/res/values/strings.xml b/samples/ApiDemos/res/values/strings.xml
index 5a1df82..9329cdd 100644
--- a/samples/ApiDemos/res/values/strings.xml
+++ b/samples/ApiDemos/res/values/strings.xml
@@ -1342,7 +1342,8 @@
     <string name="text_switcher_1_next_text">Next</string>
 
     <string name="date_widgets_example_dateDisplay_text"></string>
-    <string name="date_widgets_example_pickTime_text">change the time</string>
+    <string name="date_widgets_example_pickTime12_text">change the time (12 hour)</string>
+    <string name="date_widgets_example_pickTime24_text">change the time (24 hour)</string>
     <string name="date_widgets_example_pickDate_text">change the date</string>
 
     <string name="buttons_1_normal">Normal</string>
diff --git a/samples/ApiDemos/src/com/example/android/apis/view/DateWidgets1.java b/samples/ApiDemos/src/com/example/android/apis/view/DateWidgets1.java
index f0b1d22..537bda8 100644
--- a/samples/ApiDemos/src/com/example/android/apis/view/DateWidgets1.java
+++ b/samples/ApiDemos/src/com/example/android/apis/view/DateWidgets1.java
@@ -51,8 +51,9 @@
     private int mHour;
     private int mMinute;
 
-    static final int TIME_DIALOG_ID = 0;
-    static final int DATE_DIALOG_ID = 1;
+    static final int TIME_12_DIALOG_ID = 0;
+    static final int TIME_24_DIALOG_ID = 1;
+    static final int DATE_DIALOG_ID = 2;
 
     @Override
     protected void onCreate(Bundle savedInstanceState) {
@@ -62,21 +63,9 @@
 
         mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
 
-        Button pickDate = (Button) findViewById(R.id.pickDate);
-        pickDate.setOnClickListener(new View.OnClickListener() {
-
-            public void onClick(View v) {
-                showDialog(DATE_DIALOG_ID);
-            }
-        });
-
-        Button pickTime = (Button) findViewById(R.id.pickTime);
-        pickTime.setOnClickListener(new View.OnClickListener() {
-
-            public void onClick(View v) {
-                showDialog(TIME_DIALOG_ID);
-            }
-        });
+        setDialogOnClickListener(R.id.pickDate, DATE_DIALOG_ID);
+        setDialogOnClickListener(R.id.pickTime12, TIME_12_DIALOG_ID);
+        setDialogOnClickListener(R.id.pickTime24, TIME_24_DIALOG_ID);
 
         final Calendar c = Calendar.getInstance();
         mYear = c.get(Calendar.YEAR);
@@ -88,12 +77,22 @@
         updateDisplay();
     }
 
+    private void setDialogOnClickListener(int buttonId, final int dialogId) {
+        Button b = (Button) findViewById(buttonId);
+        b.setOnClickListener(new View.OnClickListener() {
+            public void onClick(View v) {
+                showDialog(dialogId);
+            }
+        });
+    }
+
     @Override
     protected Dialog onCreateDialog(int id) {
         switch (id) {
-            case TIME_DIALOG_ID:
+            case TIME_12_DIALOG_ID:
+            case TIME_24_DIALOG_ID:
                 return new TimePickerDialog(this,
-                        mTimeSetListener, mHour, mMinute, false);
+                        mTimeSetListener, mHour, mMinute, id == TIME_24_DIALOG_ID);
             case DATE_DIALOG_ID:
                 return new DatePickerDialog(this,
                             mDateSetListener,
@@ -105,7 +104,8 @@
     @Override
     protected void onPrepareDialog(int id, Dialog dialog) {
         switch (id) {
-            case TIME_DIALOG_ID:
+            case TIME_12_DIALOG_ID:
+            case TIME_24_DIALOG_ID:
                 ((TimePickerDialog) dialog).updateTime(mHour, mMinute);
                 break;
             case DATE_DIALOG_ID:
diff --git a/tools/jdwpspy/Android.mk b/tools/jdwpspy/Android.mk
deleted file mode 100644
index 2201aab..0000000
--- a/tools/jdwpspy/Android.mk
+++ /dev/null
@@ -1,17 +0,0 @@
-# Copyright 2006 The Android Open Source Project
-
-LOCAL_PATH:= $(call my-dir)
-include $(CLEAR_VARS)
-
-LOCAL_SRC_FILES:= \
-	Main.cpp \
-	Net.cpp \
-	find_JdwpConstants.cpp
-
-LOCAL_C_INCLUDES += \
-	dalvik/vm
-
-LOCAL_MODULE := jdwpspy
-
-include $(BUILD_HOST_EXECUTABLE)
-
diff --git a/tools/jdwpspy/Common.h b/tools/jdwpspy/Common.h
deleted file mode 100644
index ddaba9c..0000000
--- a/tools/jdwpspy/Common.h
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright 2006 The Android Open Source Project
- *
- * jdwpspy common stuff.
- */
-#ifndef _JDWPSPY_COMMON
-#define _JDWPSPY_COMMON
-
-#include <stdio.h>
-#include <sys/types.h>
-
-typedef unsigned char u1;
-typedef unsigned short u2;
-typedef unsigned int u4;
-typedef unsigned long long u8;
-
-#define NELEM(x) (sizeof(x) / sizeof((x)[0]))
-
-#ifndef _JDWP_MISC_INLINE
-# define INLINE extern inline
-#else
-# define INLINE
-#endif
-
-/*
- * Get 1 byte.  (Included to make the code more legible.)
- */
-INLINE u1 get1(unsigned const char* pSrc)
-{
-    return *pSrc;
-}
-
-/*
- * Get 2 big-endian bytes.
- */
-INLINE u2 get2BE(unsigned char const* pSrc)
-{
-    u2 result;
-
-    result = *pSrc++ << 8;
-    result |= *pSrc++;
-
-    return result;
-}
-
-/*
- * Get 4 big-endian bytes.
- */
-INLINE u4 get4BE(unsigned char const* pSrc)
-{
-    u4 result;
-
-    result = *pSrc++ << 24;
-    result |= *pSrc++ << 16;
-    result |= *pSrc++ << 8;
-    result |= *pSrc++;
-
-    return result;
-}
-
-/*
- * Get 8 big-endian bytes.
- */
-INLINE u8 get8BE(unsigned char const* pSrc)
-{
-    u8 result;
-
-    result = (u8) *pSrc++ << 56;
-    result |= (u8) *pSrc++ << 48;
-    result |= (u8) *pSrc++ << 40;
-    result |= (u8) *pSrc++ << 32;
-    result |= (u8) *pSrc++ << 24;
-    result |= (u8) *pSrc++ << 16;
-    result |= (u8) *pSrc++ << 8;
-    result |= (u8) *pSrc++;
-
-    return result;
-}
-
-
-/*
- * Start here.
- */
-int run(const char* connectHost, int connectPort, int listenPort);
-
-/*
- * Print a hex dump to the specified file pointer.
- *
- * "local" mode prints a hex dump starting from offset 0 (roughly equivalent
- * to "xxd -g1").
- *
- * "mem" mode shows the actual memory address, and will offset the start
- * so that the low nibble of the address is always zero.
- */
-typedef enum { kHexDumpLocal, kHexDumpMem } HexDumpMode;
-void printHexDump(const void* vaddr, size_t length);
-void printHexDump2(const void* vaddr, size_t length, const char* prefix);
-void printHexDumpEx(FILE* fp, const void* vaddr, size_t length,
-    HexDumpMode mode, const char* prefix);
-
-#endif /*_JDWPSPY_COMMON*/
diff --git a/tools/jdwpspy/Main.cpp b/tools/jdwpspy/Main.cpp
deleted file mode 100644
index b53f99b..0000000
--- a/tools/jdwpspy/Main.cpp
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright 2006 The Android Open Source Project
- *
- * JDWP spy.
- */
-#define _JDWP_MISC_INLINE
-#include "Common.h"
-#include <stdlib.h>
-#include <stdio.h>
-#include <stdint.h>
-#include <string.h>
-#include <assert.h>
-#include <ctype.h>
-
-static const char gHexDigit[] = "0123456789abcdef";
-
-/*
- * Print a hex dump.  Just hands control off to the fancy version.
- */
-void printHexDump(const void* vaddr, size_t length)
-{
-    printHexDumpEx(stdout, vaddr, length, kHexDumpLocal, "");
-}
-void printHexDump2(const void* vaddr, size_t length, const char* prefix)
-{
-    printHexDumpEx(stdout, vaddr, length, kHexDumpLocal, prefix);
-}
-
-/*
- * Print a hex dump in this format:
- *
-01234567: 00 11 22 33 44 55 66 77 88 99 aa bb cc dd ee ff  0123456789abcdef\n
- */
-void printHexDumpEx(FILE* fp, const void* vaddr, size_t length,
-    HexDumpMode mode, const char* prefix)
-{
-    const unsigned char* addr = reinterpret_cast<const unsigned char*>(vaddr);
-    char out[77];       /* exact fit */
-    uintptr_t offset;   /* offset to show while printing */
-    char* hex;
-    char* asc;
-    int gap;
-
-    if (mode == kHexDumpLocal)
-        offset = 0;
-    else
-        offset = (uintptr_t) addr;
-
-    memset(out, ' ', sizeof(out)-1);
-    out[8] = ':';
-    out[sizeof(out)-2] = '\n';
-    out[sizeof(out)-1] = '\0';
-
-    gap = (int) offset & 0x0f;
-    while (length) {
-        unsigned int lineOffset = offset & ~0x0f;
-        char* hex = out;
-        char* asc = out + 59;
-
-        for (int i = 0; i < 8; i++) {
-            *hex++ = gHexDigit[lineOffset >> 28];
-            lineOffset <<= 4;
-        }
-        hex++;
-        hex++;
-
-        int count = ((int)length > 16-gap) ? 16-gap : (int) length; /* cap length */
-        assert(count != 0);
-        assert(count+gap <= 16);
-
-        if (gap) {
-            /* only on first line */
-            hex += gap * 3;
-            asc += gap;
-        }
-
-        int i;
-        for (i = gap ; i < count+gap; i++) {
-            *hex++ = gHexDigit[*addr >> 4];
-            *hex++ = gHexDigit[*addr & 0x0f];
-            hex++;
-            if (isprint(*addr))
-                *asc++ = *addr;
-            else
-                *asc++ = '.';
-            addr++;
-        }
-        for ( ; i < 16; i++) {
-            /* erase extra stuff; only happens on last line */
-            *hex++ = ' ';
-            *hex++ = ' ';
-            hex++;
-            *asc++ = ' ';
-        }
-
-        fprintf(fp, "%s%s", prefix, out);
-
-        gap = 0;
-        length -= count;
-        offset += count;
-    }
-}
-
-
-/*
- * Explain it.
- */
-static void usage(const char* progName)
-{
-    fprintf(stderr, "Usage: %s VM-port [debugger-listen-port]\n\n", progName);
-    fprintf(stderr,
-"When a debugger connects to the debugger-listen-port, jdwpspy will connect\n");
-    fprintf(stderr, "to the VM on the VM-port.\n");
-}
-
-/*
- * Parse args.
- */
-int main(int argc, char* argv[])
-{
-    if (argc < 2 || argc > 3) {
-        usage("jdwpspy");
-        return 2;
-    }
-
-    setvbuf(stdout, NULL, _IONBF, 0);
-
-    /* may want this to be host:port */
-    int connectPort = atoi(argv[1]);
-
-    int listenPort;
-    if (argc > 2)
-        listenPort = atoi(argv[2]);
-    else
-        listenPort = connectPort + 1;
-
-    int cc = run("localhost", connectPort, listenPort);
-
-    return (cc != 0);
-}
diff --git a/tools/jdwpspy/Net.cpp b/tools/jdwpspy/Net.cpp
deleted file mode 100644
index b923006..0000000
--- a/tools/jdwpspy/Net.cpp
+++ /dev/null
@@ -1,748 +0,0 @@
-/*
- * Copyright 2006 The Android Open Source Project
- *
- * JDWP spy.  This is a rearranged version of the JDWP code from the VM.
- */
-#include "Common.h"
-#include "jdwp/JdwpConstants.h"
-
-#include <stdlib.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <netinet/in.h>
-#include <netinet/tcp.h>
-#include <arpa/inet.h>
-#include <netdb.h>
-#include <time.h>
-#include <errno.h>
-#include <assert.h>
-
-#define kInputBufferSize    (256*1024)
-
-#define kMagicHandshakeLen  14      /* "JDWP-Handshake" */
-#define kJDWPHeaderLen      11
-#define kJDWPFlagReply      0x80
-
-
-/*
- * Information about the remote end.
- */
-typedef struct Peer {
-    char    label[2];           /* 'D' or 'V' */
-
-    int     sock;
-    unsigned char   inputBuffer[kInputBufferSize];
-    int     inputCount;
-
-    bool    awaitingHandshake;  /* waiting for "JDWP-Handshake" */
-} Peer;
-
-
-/*
- * Network state.
- */
-typedef struct NetState {
-    /* listen here for connection from debugger */
-    int     listenSock;
-
-    /* connect here to contact VM */
-    struct in_addr vmAddr;
-    short   vmPort;
-
-    Peer    dbg;
-    Peer    vm;
-} NetState;
-
-/*
- * Function names.
- */
-typedef struct {
-    u1  cmdSet;
-    u1  cmd;
-    const char* descr;
-} JdwpHandlerMap;
-
-/*
- * Map commands to names.
- *
- * Command sets 0-63 are incoming requests, 64-127 are outbound requests,
- * and 128-256 are vendor-defined.
- */
-static const JdwpHandlerMap gHandlerMap[] = {
-    /* VirtualMachine command set (1) */
-    { 1,    1,  "VirtualMachine.Version" },
-    { 1,    2,  "VirtualMachine.ClassesBySignature" },
-    { 1,    3,  "VirtualMachine.AllClasses" },
-    { 1,    4,  "VirtualMachine.AllThreads" },
-    { 1,    5,  "VirtualMachine.TopLevelThreadGroups" },
-    { 1,    6,  "VirtualMachine.Dispose" },
-    { 1,    7,  "VirtualMachine.IDSizes" },
-    { 1,    8,  "VirtualMachine.Suspend" },
-    { 1,    9,  "VirtualMachine.Resume" },
-    { 1,    10, "VirtualMachine.Exit" },
-    { 1,    11, "VirtualMachine.CreateString" },
-    { 1,    12, "VirtualMachine.Capabilities" },
-    { 1,    13, "VirtualMachine.ClassPaths" },
-    { 1,    14, "VirtualMachine.DisposeObjects" },
-    { 1,    15, "VirtualMachine.HoldEvents" },
-    { 1,    16, "VirtualMachine.ReleaseEvents" },
-    { 1,    17, "VirtualMachine.CapabilitiesNew" },
-    { 1,    18, "VirtualMachine.RedefineClasses" },
-    { 1,    19, "VirtualMachine.SetDefaultStratum" },
-    { 1,    20, "VirtualMachine.AllClassesWithGeneric"},
-    { 1,    21, "VirtualMachine.InstanceCounts"},
-
-    /* ReferenceType command set (2) */
-    { 2,    1,  "ReferenceType.Signature" },
-    { 2,    2,  "ReferenceType.ClassLoader" },
-    { 2,    3,  "ReferenceType.Modifiers" },
-    { 2,    4,  "ReferenceType.Fields" },
-    { 2,    5,  "ReferenceType.Methods" },
-    { 2,    6,  "ReferenceType.GetValues" },
-    { 2,    7,  "ReferenceType.SourceFile" },
-    { 2,    8,  "ReferenceType.NestedTypes" },
-    { 2,    9,  "ReferenceType.Status" },
-    { 2,    10, "ReferenceType.Interfaces" },
-    { 2,    11, "ReferenceType.ClassObject" },
-    { 2,    12, "ReferenceType.SourceDebugExtension" },
-    { 2,    13, "ReferenceType.SignatureWithGeneric" },
-    { 2,    14, "ReferenceType.FieldsWithGeneric" },
-    { 2,    15, "ReferenceType.MethodsWithGeneric" },
-    { 2,    16, "ReferenceType.Instances" },
-    { 2,    17, "ReferenceType.ClassFileVersion" },
-    { 2,    18, "ReferenceType.ConstantPool" },
-
-    /* ClassType command set (3) */
-    { 3,    1,  "ClassType.Superclass" },
-    { 3,    2,  "ClassType.SetValues" },
-    { 3,    3,  "ClassType.InvokeMethod" },
-    { 3,    4,  "ClassType.NewInstance" },
-
-    /* ArrayType command set (4) */
-    { 4,    1,  "ArrayType.NewInstance" },
-
-    /* InterfaceType command set (5) */
-
-    /* Method command set (6) */
-    { 6,    1,  "Method.LineTable" },
-    { 6,    2,  "Method.VariableTable" },
-    { 6,    3,  "Method.Bytecodes" },
-    { 6,    4,  "Method.IsObsolete" },
-    { 6,    5,  "Method.VariableTableWithGeneric" },
-
-    /* Field command set (8) */
-
-    /* ObjectReference command set (9) */
-    { 9,    1,  "ObjectReference.ReferenceType" },
-    { 9,    2,  "ObjectReference.GetValues" },
-    { 9,    3,  "ObjectReference.SetValues" },
-    { 9,    4,  "ObjectReference.UNUSED" },
-    { 9,    5,  "ObjectReference.MonitorInfo" },
-    { 9,    6,  "ObjectReference.InvokeMethod" },
-    { 9,    7,  "ObjectReference.DisableCollection" },
-    { 9,    8,  "ObjectReference.EnableCollection" },
-    { 9,    9,  "ObjectReference.IsCollected" },
-    { 9,    10, "ObjectReference.ReferringObjects" },
-
-    /* StringReference command set (10) */
-    { 10,   1,  "StringReference.Value" },
-
-    /* ThreadReference command set (11) */
-    { 11,   1,  "ThreadReference.Name" },
-    { 11,   2,  "ThreadReference.Suspend" },
-    { 11,   3,  "ThreadReference.Resume" },
-    { 11,   4,  "ThreadReference.Status" },
-    { 11,   5,  "ThreadReference.ThreadGroup" },
-    { 11,   6,  "ThreadReference.Frames" },
-    { 11,   7,  "ThreadReference.FrameCount" },
-    { 11,   8,  "ThreadReference.OwnedMonitors" },
-    { 11,   9,  "ThreadReference.CurrentContendedMonitor" },
-    { 11,   10, "ThreadReference.Stop" },
-    { 11,   11, "ThreadReference.Interrupt" },
-    { 11,   12, "ThreadReference.SuspendCount" },
-    { 11,   13, "ThreadReference.OwnedMonitorsStackDepthInfo" },
-    { 11,   14, "ThreadReference.ForceEarlyReturn" },
-
-    /* ThreadGroupReference command set (12) */
-    { 12,   1,  "ThreadGroupReference.Name" },
-    { 12,   2,  "ThreadGroupReference.Parent" },
-    { 12,   3,  "ThreadGroupReference.Children" },
-
-    /* ArrayReference command set (13) */
-    { 13,   1,  "ArrayReference.Length" },
-    { 13,   2,  "ArrayReference.GetValues" },
-    { 13,   3,  "ArrayReference.SetValues" },
-
-    /* ClassLoaderReference command set (14) */
-    { 14,   1,  "ArrayReference.VisibleClasses" },
-
-    /* EventRequest command set (15) */
-    { 15,   1,  "EventRequest.Set" },
-    { 15,   2,  "EventRequest.Clear" },
-    { 15,   3,  "EventRequest.ClearAllBreakpoints" },
-
-    /* StackFrame command set (16) */
-    { 16,   1,  "StackFrame.GetValues" },
-    { 16,   2,  "StackFrame.SetValues" },
-    { 16,   3,  "StackFrame.ThisObject" },
-    { 16,   4,  "StackFrame.PopFrames" },
-
-    /* ClassObjectReference command set (17) */
-    { 17,   1,  "ClassObjectReference.ReflectedType" },
-
-    /* Event command set (64) */
-    { 64,  100, "Event.Composite" },
-
-    /* DDMS */
-    { 199,  1,  "DDMS.Chunk" },
-};
-
-/*
- * Look up a command's name.
- */
-static const char* getCommandName(int cmdSet, int cmd)
-{
-    for (int i = 0; i < (int) NELEM(gHandlerMap); i++) {
-        if (gHandlerMap[i].cmdSet == cmdSet &&
-            gHandlerMap[i].cmd == cmd)
-        {
-            return gHandlerMap[i].descr;
-        }
-    }
-
-    return "?UNKNOWN?";
-}
-
-
-void jdwpNetFree(NetState* netState);       /* fwd */
-
-/*
- * Allocate state structure and bind to the listen port.
- *
- * Returns 0 on success.
- */
-NetState* jdwpNetStartup(unsigned short listenPort, const char* connectHost,
-    unsigned short connectPort)
-{
-    NetState* netState = (NetState*) malloc(sizeof(*netState));
-    memset(netState, 0, sizeof(*netState));
-    netState->listenSock = -1;
-    netState->dbg.sock = netState->vm.sock = -1;
-
-    strcpy(netState->dbg.label, "D");
-    strcpy(netState->vm.label, "V");
-
-    /*
-     * Set up a socket to listen for connections from the debugger.
-     */
-
-    netState->listenSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
-    if (netState->listenSock < 0) {
-        fprintf(stderr, "Socket create failed: %s\n", strerror(errno));
-        goto fail;
-    }
-
-    /* allow immediate re-use if we die */
-    {
-        int one = 1;
-        if (setsockopt(netState->listenSock, SOL_SOCKET, SO_REUSEADDR, &one,
-                sizeof(one)) < 0)
-        {
-            fprintf(stderr, "setsockopt(SO_REUSEADDR) failed: %s\n",
-                strerror(errno));
-            goto fail;
-        }
-    }
-
-    struct sockaddr_in addr;
-    addr.sin_family = AF_INET;
-    addr.sin_port = htons(listenPort);
-    addr.sin_addr.s_addr = INADDR_ANY;
-
-    if (bind(netState->listenSock, (struct sockaddr*) &addr, sizeof(addr)) != 0)
-    {
-        fprintf(stderr, "attempt to bind to port %u failed: %s\n",
-            listenPort, strerror(errno));
-        goto fail;
-    }
-
-    fprintf(stderr, "+++ bound to port %u\n", listenPort);
-
-    if (listen(netState->listenSock, 5) != 0) {
-        fprintf(stderr, "Listen failed: %s\n", strerror(errno));
-        goto fail;
-    }
-
-    /*
-     * Do the hostname lookup for the VM.
-     */
-    struct hostent* pHost;
-
-    pHost = gethostbyname(connectHost);
-    if (pHost == NULL) {
-        fprintf(stderr, "Name lookup of '%s' failed: %s\n",
-            connectHost, strerror(h_errno));
-        goto fail;
-    }
-
-    netState->vmAddr = *((struct in_addr*) pHost->h_addr_list[0]);
-    netState->vmPort = connectPort;
-
-    fprintf(stderr, "+++ connect host resolved to %s\n",
-        inet_ntoa(netState->vmAddr));
-
-    return netState;
-
-fail:
-    jdwpNetFree(netState);
-    return NULL;
-}
-
-/*
- * Shut down JDWP listener.  Don't free state.
- *
- * Note that "netState" may be partially initialized if "startup" failed.
- */
-void jdwpNetShutdown(NetState* netState)
-{
-    int listenSock = netState->listenSock;
-    int dbgSock = netState->dbg.sock;
-    int vmSock = netState->vm.sock;
-
-    /* clear these out so it doesn't wake up and try to reuse them */
-    /* (important when multi-threaded) */
-    netState->listenSock = netState->dbg.sock = netState->vm.sock = -1;
-
-    if (listenSock >= 0) {
-        shutdown(listenSock, SHUT_RDWR);
-        close(listenSock);
-    }
-    if (dbgSock >= 0) {
-        shutdown(dbgSock, SHUT_RDWR);
-        close(dbgSock);
-    }
-    if (vmSock >= 0) {
-        shutdown(vmSock, SHUT_RDWR);
-        close(vmSock);
-    }
-}
-
-/*
- * Shut down JDWP listener and free its state.
- */
-void jdwpNetFree(NetState* netState)
-{
-    if (netState == NULL)
-        return;
-
-    jdwpNetShutdown(netState);
-    free(netState);
-}
-
-/*
- * Disable the TCP Nagle algorithm, which delays transmission of outbound
- * packets until the previous transmissions have been acked.  JDWP does a
- * lot of back-and-forth with small packets, so this may help.
- */
-static int setNoDelay(int fd)
-{
-    int cc, on = 1;
-
-    cc = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on));
-    assert(cc == 0);
-    return cc;
-}
-
-/*
- * Accept a connection.  This will block waiting for somebody to show up.
- */
-bool jdwpAcceptConnection(NetState* netState)
-{
-    struct sockaddr_in addr;
-    socklen_t addrlen;
-    int sock;
-
-    if (netState->listenSock < 0)
-        return false;       /* you're not listening! */
-
-    assert(netState->dbg.sock < 0);     /* must not already be talking */
-
-    addrlen = sizeof(addr);
-    do {
-        sock = accept(netState->listenSock, (struct sockaddr*) &addr, &addrlen);
-        if (sock < 0 && errno != EINTR) {
-            fprintf(stderr, "accept failed: %s\n", strerror(errno));
-            return false;
-        }
-    } while (sock < 0);
-
-    fprintf(stderr, "+++ accepted connection from %s:%u\n",
-        inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
-
-    netState->dbg.sock = sock;
-    netState->dbg.awaitingHandshake = true;
-    netState->dbg.inputCount = 0;
-
-    setNoDelay(sock);
-
-    return true;
-}
-
-/*
- * Close the connections to the debugger and VM.
- *
- * Reset the state so we're ready to receive a new connection.
- */
-void jdwpCloseConnection(NetState* netState)
-{
-    if (netState->dbg.sock >= 0) {
-        fprintf(stderr, "+++ closing connection to debugger\n");
-        close(netState->dbg.sock);
-        netState->dbg.sock = -1;
-    }
-    if (netState->vm.sock >= 0) {
-        fprintf(stderr, "+++ closing connection to vm\n");
-        close(netState->vm.sock);
-        netState->vm.sock = -1;
-    }
-}
-
-/*
- * Figure out if we have a full packet in the buffer.
- */
-static bool haveFullPacket(Peer* pPeer)
-{
-    long length;
-
-    if (pPeer->awaitingHandshake)
-        return (pPeer->inputCount >= kMagicHandshakeLen);
-
-    if (pPeer->inputCount < 4)
-        return false;
-
-    length = get4BE(pPeer->inputBuffer);
-    return (pPeer->inputCount >= length);
-}
-
-/*
- * Consume bytes from the buffer.
- *
- * This would be more efficient with a circular buffer.  However, we're
- * usually only going to find one packet, which is trivial to handle.
- */
-static void consumeBytes(Peer* pPeer, int count)
-{
-    assert(count > 0);
-    assert(count <= pPeer->inputCount);
-
-    if (count == pPeer->inputCount) {
-        pPeer->inputCount = 0;
-        return;
-    }
-
-    memmove(pPeer->inputBuffer, pPeer->inputBuffer + count,
-        pPeer->inputCount - count);
-    pPeer->inputCount -= count;
-}
-
-/*
- * Get the current time.
- */
-static void getCurrentTime(int* pMin, int* pSec)
-{
-    time_t now;
-    struct tm* ptm;
-
-    now = time(NULL);
-    ptm = localtime(&now);
-    *pMin = ptm->tm_min;
-    *pSec = ptm->tm_sec;
-}
-
-/*
- * Dump the contents of a packet to stdout.
- */
-static void dumpPacket(const unsigned char* packetBuf, const char* srcName,
-    const char* dstName)
-{
-    const unsigned char* buf = packetBuf;
-    char prefix[3];
-    u4 length, id;
-    u1 flags, cmdSet=0, cmd=0;
-    JdwpError error = ERR_NONE;
-    bool reply;
-    int dataLen;
-
-    length = get4BE(buf+0);
-    id = get4BE(buf+4);
-    flags = get1(buf+8);
-    if ((flags & kJDWPFlagReply) != 0) {
-        reply = true;
-        error = static_cast<JdwpError>(get2BE(buf+9));
-    } else {
-        reply = false;
-        cmdSet = get1(buf+9);
-        cmd = get1(buf+10);
-    }
-
-    buf += kJDWPHeaderLen;
-    dataLen = length - (buf - packetBuf);
-
-    if (!reply) {
-        prefix[0] = srcName[0];
-        prefix[1] = '>';
-    } else {
-        prefix[0] = dstName[0];
-        prefix[1] = '<';
-    }
-    prefix[2] = '\0';
-
-    int min, sec;
-    getCurrentTime(&min, &sec);
-
-    if (!reply) {
-        printf("%s REQUEST dataLen=%-5u id=0x%08x flags=0x%02x cmd=%d/%d [%02d:%02d]\n",
-            prefix, dataLen, id, flags, cmdSet, cmd, min, sec);
-        printf("%s   --> %s\n", prefix, getCommandName(cmdSet, cmd));
-    } else {
-        printf("%s REPLY   dataLen=%-5u id=0x%08x flags=0x%02x err=%d (%s) [%02d:%02d]\n",
-            prefix, dataLen, id, flags, error, dvmJdwpErrorStr(error), min,sec);
-    }
-    if (dataLen > 0)
-        printHexDump2(buf, dataLen, prefix);
-    printf("%s ----------\n", prefix);
-}
-
-/*
- * Handle a packet.  Returns "false" if we encounter a connection-fatal error.
- */
-static bool handlePacket(Peer* pDst, Peer* pSrc)
-{
-    const unsigned char* buf = pSrc->inputBuffer;
-    u4 length;
-    u1 flags;
-    int cc;
-
-    length = get4BE(buf+0);
-    flags = get1(buf+9);
-
-    assert((int) length <= pSrc->inputCount);
-
-    dumpPacket(buf, pSrc->label, pDst->label);
-
-    cc = write(pDst->sock, buf, length);
-    if (cc != (int) length) {
-        fprintf(stderr, "Failed sending packet: %s\n", strerror(errno));
-        return false;
-    }
-    /*printf("*** wrote %d bytes from %c to %c\n",
-        cc, pSrc->label[0], pDst->label[0]);*/
-
-    consumeBytes(pSrc, length);
-    return true;
-}
-
-/*
- * Handle incoming data.  If we have a full packet in the buffer, process it.
- */
-static bool handleIncoming(Peer* pWritePeer, Peer* pReadPeer)
-{
-    if (haveFullPacket(pReadPeer)) {
-        if (pReadPeer->awaitingHandshake) {
-            printf("Handshake [%c]: %.14s\n",
-                pReadPeer->label[0], pReadPeer->inputBuffer);
-            if (write(pWritePeer->sock, pReadPeer->inputBuffer,
-                    kMagicHandshakeLen) != kMagicHandshakeLen)
-            {
-                fprintf(stderr,
-                    "+++ [%c] handshake write failed\n", pReadPeer->label[0]);
-                goto fail;
-            }
-            consumeBytes(pReadPeer, kMagicHandshakeLen);
-            pReadPeer->awaitingHandshake = false;
-        } else {
-            if (!handlePacket(pWritePeer, pReadPeer))
-                goto fail;
-        }
-    } else {
-        /*printf("*** %c not full yet\n", pReadPeer->label[0]);*/
-    }
-
-    return true;
-
-fail:
-    return false;
-}
-
-/*
- * Process incoming data.  If no data is available, this will block until
- * some arrives.
- *
- * Returns "false" on error (indicating that the connection has been severed).
- */
-bool jdwpProcessIncoming(NetState* netState)
-{
-    int cc;
-
-    assert(netState->dbg.sock >= 0);
-    assert(netState->vm.sock >= 0);
-
-    while (!haveFullPacket(&netState->dbg) && !haveFullPacket(&netState->vm)) {
-        /* read some more */
-        int highFd;
-        fd_set readfds;
-
-        highFd = (netState->dbg.sock > netState->vm.sock) ?
-            netState->dbg.sock+1 : netState->vm.sock+1;
-        FD_ZERO(&readfds);
-        FD_SET(netState->dbg.sock, &readfds);
-        FD_SET(netState->vm.sock, &readfds);
-
-        errno = 0;
-        cc = select(highFd, &readfds, NULL, NULL, NULL);
-        if (cc < 0) {
-            if (errno == EINTR) {
-                fprintf(stderr, "+++ EINTR on select\n");
-                continue;
-            }
-            fprintf(stderr, "+++ select failed: %s\n", strerror(errno));
-            goto fail;
-        }
-
-        if (FD_ISSET(netState->dbg.sock, &readfds)) {
-            cc = read(netState->dbg.sock,
-                netState->dbg.inputBuffer + netState->dbg.inputCount,
-                sizeof(netState->dbg.inputBuffer) - netState->dbg.inputCount);
-            if (cc < 0) {
-                if (errno == EINTR) {
-                    fprintf(stderr, "+++ EINTR on read\n");
-                    continue;
-                }
-                fprintf(stderr, "+++ dbg read failed: %s\n", strerror(errno));
-                goto fail;
-            }
-            if (cc == 0) {
-                if (sizeof(netState->dbg.inputBuffer) ==
-                        netState->dbg.inputCount)
-                    fprintf(stderr, "+++ debugger sent huge message\n");
-                else
-                    fprintf(stderr, "+++ debugger disconnected\n");
-                goto fail;
-            }
-
-            /*printf("*** %d bytes from dbg\n", cc);*/
-            netState->dbg.inputCount += cc;
-        }
-
-        if (FD_ISSET(netState->vm.sock, &readfds)) {
-            cc = read(netState->vm.sock,
-                netState->vm.inputBuffer + netState->vm.inputCount,
-                sizeof(netState->vm.inputBuffer) - netState->vm.inputCount);
-            if (cc < 0) {
-                if (errno == EINTR) {
-                    fprintf(stderr, "+++ EINTR on read\n");
-                    continue;
-                }
-                fprintf(stderr, "+++ vm read failed: %s\n", strerror(errno));
-                goto fail;
-            }
-            if (cc == 0) {
-                if (sizeof(netState->vm.inputBuffer) ==
-                        netState->vm.inputCount)
-                    fprintf(stderr, "+++ vm sent huge message\n");
-                else
-                    fprintf(stderr, "+++ vm disconnected\n");
-                goto fail;
-            }
-
-            /*printf("*** %d bytes from vm\n", cc);*/
-            netState->vm.inputCount += cc;
-        }
-    }
-
-    if (!handleIncoming(&netState->dbg, &netState->vm))
-        goto fail;
-    if (!handleIncoming(&netState->vm, &netState->dbg))
-        goto fail;
-
-    return true;
-
-fail:
-    jdwpCloseConnection(netState);
-    return false;
-}
-
-/*
- * Connect to the VM.
- */
-bool jdwpConnectToVm(NetState* netState)
-{
-    struct sockaddr_in addr;
-    int sock = -1;
-
-    sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
-    if (sock < 0) {
-        fprintf(stderr, "Socket create failed: %s\n", strerror(errno));
-        goto fail;
-    }
-
-    addr.sin_family = AF_INET;
-    addr.sin_addr = netState->vmAddr;
-    addr.sin_port = htons(netState->vmPort);
-    if (connect(sock, (struct sockaddr*) &addr, sizeof(addr)) != 0) {
-        fprintf(stderr, "Connection to %s:%u failed: %s\n",
-            inet_ntoa(addr.sin_addr), ntohs(addr.sin_port), strerror(errno));
-        goto fail;
-    }
-    fprintf(stderr, "+++ connected to VM %s:%u\n",
-        inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
-
-    netState->vm.sock = sock;
-    netState->vm.awaitingHandshake = true;
-    netState->vm.inputCount = 0;
-
-    setNoDelay(netState->vm.sock);
-    return true;
-
-fail:
-    if (sock >= 0)
-        close(sock);
-    return false;
-}
-
-/*
- * Establish network connections and start things running.
- *
- * We wait for a new connection from the debugger.  When one arrives we
- * open a connection to the VM.  If one side or the other goes away, we
- * drop both ends and go back to listening.
- */
-int run(const char* connectHost, int connectPort, int listenPort)
-{
-    NetState* state;
-
-    state = jdwpNetStartup(listenPort, connectHost, connectPort);
-    if (state == NULL)
-        return -1;
-
-    while (true) {
-        if (!jdwpAcceptConnection(state))
-            break;
-
-        if (jdwpConnectToVm(state)) {
-            while (true) {
-                if (!jdwpProcessIncoming(state))
-                    break;
-            }
-        }
-
-        jdwpCloseConnection(state);
-    }
-
-    jdwpNetFree(state);
-
-    return 0;
-}
diff --git a/tools/jdwpspy/find_JdwpConstants.cpp b/tools/jdwpspy/find_JdwpConstants.cpp
deleted file mode 100644
index 57b7dbb..0000000
--- a/tools/jdwpspy/find_JdwpConstants.cpp
+++ /dev/null
@@ -1 +0,0 @@
-#include "jdwp/JdwpConstants.cpp"
diff --git a/tutorials/MoarRam/Android.mk b/tutorials/MoarRam/Android.mk
new file mode 100644
index 0000000..c3bace9
--- /dev/null
+++ b/tutorials/MoarRam/Android.mk
@@ -0,0 +1,31 @@
+# Copyright (C) 2013 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+
+# We only want this apk build for tests.
+LOCAL_MODULE_TAGS := optional
+
+# Include all test java files.
+LOCAL_SRC_FILES := $(call all-java-files-under, src)
+
+LOCAL_PACKAGE_NAME := MoarRam
+
+include $(BUILD_PACKAGE)
+
+include $(CLEAR_VARS)
+
+include $(call all-makefiles-under,$(LOCAL_PATH))
diff --git a/tutorials/MoarRam/AndroidManifest.xml b/tutorials/MoarRam/AndroidManifest.xml
new file mode 100644
index 0000000..ae48ace
--- /dev/null
+++ b/tutorials/MoarRam/AndroidManifest.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+    package="com.android.benchmark.moarram"
+    android:versionCode="1"
+    android:versionName="1.0" >
+
+    <application
+        android:allowBackup="true"
+        android:icon="@drawable/ic_launcher"
+        android:label="@string/app_name"
+        android:theme="@style/AppTheme" >
+        <activity
+            android:name="com.android.benchmark.moarram.MainActivity"
+            android:label="@string/app_name" >
+            <intent-filter>
+                <action android:name="android.intent.action.MAIN" />
+
+                <category android:name="android.intent.category.LAUNCHER" />
+            </intent-filter>
+        </activity>
+    </application>
+
+</manifest>
diff --git a/tutorials/MoarRam/README.txt b/tutorials/MoarRam/README.txt
new file mode 100644
index 0000000..028389b
--- /dev/null
+++ b/tutorials/MoarRam/README.txt
@@ -0,0 +1,14 @@
+This is a simple app that can be used as a tutorial or reference benchmark
+for the development of the DDMS native heap tracker feature. It contains 3
+unique paths to allocate heap chunks:
+
+1) Java_com_android_benchmark_moarram_MainActivity_add32ByteBlocksNative in
+   foo.c (libmoarram-foo.so). Each invocation will allocate 32 bytes.
+2) Java_com_android_benchmark_moarram_MainActivity_add2MByteBlocksNative in
+   bar.c (libmoarram-bar.so). Each invocation will allocate 2M bytes.
+3) Java_com_android_benchmark_moarram_MainActivity_addVariableSizedBlocksNative
+   in baz.c (libmoarram-baz.so). Each invocation will allocate 17 or 71 bytes,
+   depending on the active button in a radio group.
+
+Each allocation can be freed by clicking the corresponding free button in the
+UI.
diff --git a/tutorials/MoarRam/jni/Android.mk b/tutorials/MoarRam/jni/Android.mk
new file mode 100644
index 0000000..933cbdf
--- /dev/null
+++ b/tutorials/MoarRam/jni/Android.mk
@@ -0,0 +1,43 @@
+# Copyright (C) 2013 The Android Open Source Project
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+LOCAL_PATH:= $(call my-dir)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE    := libmoarram-32
+LOCAL_SRC_FILES := foo.c
+LOCAL_SHARED_LIBRARIES += liblog
+
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE    := libmoarram-2M
+LOCAL_SRC_FILES := bar.c
+LOCAL_SHARED_LIBRARIES += liblog
+
+include $(BUILD_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE_TAGS := optional
+LOCAL_MODULE    := libmoarram-17_71
+LOCAL_SRC_FILES := baz.c
+LOCAL_SHARED_LIBRARIES += liblog
+
+include $(BUILD_SHARED_LIBRARY)
diff --git a/tutorials/MoarRam/jni/bar.c b/tutorials/MoarRam/jni/bar.c
new file mode 100644
index 0000000..7b00e62
--- /dev/null
+++ b/tutorials/MoarRam/jni/bar.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <jni.h>
+#include <cutils/log.h>
+
+#if defined(LOG_TAG)
+#undef LOG_TAG
+#define LOG_TAG "MOARRAM"
+#endif
+
+char *gPtr2;
+static int num2MByteBlocks;
+
+void
+Java_com_android_benchmark_moarram_MainActivity_add2MByteBlocksNative(
+    JNIEnv*  env,
+    jobject  this)
+{
+    char **ptr = malloc(2*1024*1024);
+    *ptr = gPtr2;
+    gPtr2 = (char *) ptr;
+    num2MByteBlocks++;
+    ALOGW("%d 2M-byte blocks allocated so far (just allocated %p)",
+          num2MByteBlocks, gPtr2);
+}
+
+void
+Java_com_android_benchmark_moarram_MainActivity_free2MByteBlocksNative(
+    JNIEnv*  env,
+    jobject  this)
+{
+    if (gPtr2 == NULL) {
+        ALOGW("All 2M-byte blocks are freed");
+        return;
+    }
+
+    char **ptr = (char **) gPtr2;
+    gPtr2 = *ptr;
+    free(ptr);
+    num2MByteBlocks--;
+    ALOGW("%d 2M-byte blocks allocated so far (just freed %p)",
+          num2MByteBlocks, ptr);
+}
diff --git a/tutorials/MoarRam/jni/baz.c b/tutorials/MoarRam/jni/baz.c
new file mode 100644
index 0000000..1262e40
--- /dev/null
+++ b/tutorials/MoarRam/jni/baz.c
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <jni.h>
+#include <cutils/log.h>
+
+#if defined(LOG_TAG)
+#undef LOG_TAG
+#define LOG_TAG "MOARRAM"
+#endif
+
+char *gPtr17;
+char *gPtr71;
+static int num17ByteBlocks;
+static int num71ByteBlocks;
+
+void
+Java_com_android_benchmark_moarram_MainActivity_addVariableSizedBlocksNative(
+    JNIEnv*  env,
+    jobject  this,
+    jint id)
+{
+    int size;
+    char **gPtr;
+    char **ptr;
+    if (id == 0) {
+        size = 17;
+        gPtr = &gPtr17;
+    } else {
+        size = 71;
+        gPtr = &gPtr71;
+    }
+    ptr = malloc(size);
+    *ptr = *gPtr;
+    *gPtr = (char *) ptr;
+    ALOGW("%d %d-byte blocks allocated so far (just allocated %p)",
+          id == 0 ? ++num17ByteBlocks : ++num71ByteBlocks,
+          size, ptr);
+}
+
+void
+Java_com_android_benchmark_moarram_MainActivity_freeVariableSizedBlocksNative(
+    JNIEnv*  env,
+    jobject  this,
+    jint id)
+{
+    int size;
+    char **ptr;
+    char **gPtr;
+    if (id == 0) {
+        size = 17;
+        gPtr = &gPtr17;
+    } else {
+        size = 71;
+        gPtr = &gPtr71;
+    }
+    if (*gPtr == NULL) {
+        ALOGW("All %d-byte blocks are freed", size);
+        return;
+    }
+    ptr = (char **) *gPtr;
+    *gPtr = *ptr;
+    free(ptr);
+    ALOGW("%d %d-byte blocks allocated so far (just freed %p)",
+          id == 0 ? --num17ByteBlocks : --num71ByteBlocks,
+          size, ptr);
+}
diff --git a/tutorials/MoarRam/jni/foo.c b/tutorials/MoarRam/jni/foo.c
new file mode 100644
index 0000000..a318c74
--- /dev/null
+++ b/tutorials/MoarRam/jni/foo.c
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2013 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+#include <jni.h>
+#include <cutils/log.h>
+
+#if defined(LOG_TAG)
+#undef LOG_TAG
+#define LOG_TAG "MOARRAM"
+#endif
+
+char *gPtr;
+static int num32ByteBlocks;
+
+void
+Java_com_android_benchmark_moarram_MainActivity_add32ByteBlocksNative(
+    JNIEnv*  env,
+    jobject  this)
+{
+    char **ptr = malloc(32);
+    *ptr = gPtr;
+    gPtr = (char *) ptr;
+    num32ByteBlocks++;
+    ALOGW("%d 32-byte blocks allocated so far (just allocated %p)",
+          num32ByteBlocks, gPtr);
+}
+
+void
+Java_com_android_benchmark_moarram_MainActivity_free32ByteBlocksNative(
+    JNIEnv*  env,
+    jobject  this)
+{
+    if (gPtr == NULL) {
+        ALOGW("All 32-byte blocks are freed");
+        return;
+    }
+
+    char **ptr = (char **) gPtr;
+    gPtr = *ptr;
+    free(ptr);
+    num32ByteBlocks--;
+    ALOGW("%d 32-byte blocks allocated so far (just freed %p)",
+          num32ByteBlocks, ptr);
+}
diff --git a/tutorials/MoarRam/res/drawable-hdpi/ic_launcher.png b/tutorials/MoarRam/res/drawable-hdpi/ic_launcher.png
new file mode 100644
index 0000000..288b665
--- /dev/null
+++ b/tutorials/MoarRam/res/drawable-hdpi/ic_launcher.png
Binary files differ
diff --git a/tutorials/MoarRam/res/drawable-mdpi/ic_launcher.png b/tutorials/MoarRam/res/drawable-mdpi/ic_launcher.png
new file mode 100644
index 0000000..6ae570b
--- /dev/null
+++ b/tutorials/MoarRam/res/drawable-mdpi/ic_launcher.png
Binary files differ
diff --git a/tutorials/MoarRam/res/drawable-xhdpi/ic_launcher.png b/tutorials/MoarRam/res/drawable-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..d4fb7cd
--- /dev/null
+++ b/tutorials/MoarRam/res/drawable-xhdpi/ic_launcher.png
Binary files differ
diff --git a/tutorials/MoarRam/res/drawable-xxhdpi/ic_launcher.png b/tutorials/MoarRam/res/drawable-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..85a6081
--- /dev/null
+++ b/tutorials/MoarRam/res/drawable-xxhdpi/ic_launcher.png
Binary files differ
diff --git a/tutorials/MoarRam/res/layout/activity_main.xml b/tutorials/MoarRam/res/layout/activity_main.xml
new file mode 100644
index 0000000..8319bd7
--- /dev/null
+++ b/tutorials/MoarRam/res/layout/activity_main.xml
@@ -0,0 +1,104 @@
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    xmlns:tools="http://schemas.android.com/tools"
+    android:layout_width="match_parent"
+    android:layout_height="fill_parent"
+    android:paddingBottom="@dimen/activity_vertical_margin"
+    android:paddingLeft="@dimen/activity_horizontal_margin"
+    android:paddingRight="@dimen/activity_horizontal_margin"
+    android:paddingTop="@dimen/activity_vertical_margin"
+    android:orientation="vertical"
+    tools:context=".MainActivity" >
+
+    <LinearLayout
+    android:layout_width="fill_parent"
+    android:layout_height="wrap_content"
+    android:layout_weight="1"
+    android:orientation="horizontal">
+
+    <Button
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent"
+        android:text="@string/add_32"
+        android:layout_weight="1"
+        android:onClick="add32ByteBlocks" />
+
+    <Button
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent"
+        android:text="@string/free_32"
+        android:layout_weight="1"
+        android:onClick="free32ByteBlocks" />
+    </LinearLayout>
+
+    <LinearLayout
+    android:layout_width="fill_parent"
+    android:layout_height="wrap_content"
+    android:layout_weight="1"
+    android:orientation="horizontal">
+
+    <Button
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent"
+        android:text="@string/add_2m"
+        android:layout_weight="1"
+        android:onClick="add2MByteBlocks" />
+
+    <Button
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent"
+        android:text="@string/free_2m"
+        android:layout_weight="1"
+        android:onClick="free2MByteBlocks" />
+    </LinearLayout>
+
+    <LinearLayout
+    android:id="@+id/linearLayout2"
+    android:layout_width="fill_parent"
+    android:layout_height="wrap_content"
+    android:layout_weight="1"
+    android:orientation="horizontal">
+
+    <RadioGroup
+        android:id="@+id/blockSize"
+        android:layout_width="fill_parent"
+        android:layout_height="wrap_content"
+        android:layout_gravity="center"
+        android:orientation="horizontal"
+        android:gravity="center" >
+
+        <RadioButton
+        android:id="@+id/radio17"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/_17byte"
+        android:checked="true" />
+
+        <RadioButton
+        android:id="@+id/radio71"
+        android:layout_width="wrap_content"
+        android:layout_height="wrap_content"
+        android:text="@string/_71byte" />
+    </RadioGroup>
+    </LinearLayout>
+
+    <LinearLayout
+    android:layout_width="fill_parent"
+    android:layout_height="wrap_content"
+    android:layout_weight="1"
+    android:orientation="horizontal">
+
+    <Button
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent"
+        android:text="@string/add_variable"
+        android:layout_weight="1"
+        android:onClick="addVariableSizedBlocks" />
+
+    <Button
+        android:layout_width="fill_parent"
+        android:layout_height="fill_parent"
+        android:text="@string/free_variable"
+        android:layout_weight="1"
+        android:onClick="freeVariableSizedBlocks" />
+    </LinearLayout>
+</LinearLayout>
diff --git a/tutorials/MoarRam/res/menu/main.xml b/tutorials/MoarRam/res/menu/main.xml
new file mode 100644
index 0000000..d227c49
--- /dev/null
+++ b/tutorials/MoarRam/res/menu/main.xml
@@ -0,0 +1,9 @@
+<menu xmlns:android="http://schemas.android.com/apk/res/android" >
+
+    <item
+        android:id="@+id/action_settings"
+        android:orderInCategory="100"
+        android:showAsAction="never"
+        android:title="@string/action_settings"/>
+
+</menu>
\ No newline at end of file
diff --git a/tutorials/MoarRam/res/values-sw600dp/dimens.xml b/tutorials/MoarRam/res/values-sw600dp/dimens.xml
new file mode 100644
index 0000000..1ba777d
--- /dev/null
+++ b/tutorials/MoarRam/res/values-sw600dp/dimens.xml
@@ -0,0 +1,8 @@
+<resources>
+
+    <!--
+         Customize dimensions originally defined in res/values/dimens.xml (such as
+         screen margins) for sw600dp devices (e.g. 7" tablets) here.
+    -->
+
+</resources>
\ No newline at end of file
diff --git a/tutorials/MoarRam/res/values-sw720dp-land/dimens.xml b/tutorials/MoarRam/res/values-sw720dp-land/dimens.xml
new file mode 100644
index 0000000..eee741a
--- /dev/null
+++ b/tutorials/MoarRam/res/values-sw720dp-land/dimens.xml
@@ -0,0 +1,9 @@
+<resources>
+
+    <!--
+         Customize dimensions originally defined in res/values/dimens.xml (such as
+         screen margins) for sw720dp devices (e.g. 10" tablets) in landscape here.
+    -->
+    <dimen name="activity_horizontal_margin">128dp</dimen>
+
+</resources>
\ No newline at end of file
diff --git a/tutorials/MoarRam/res/values-v11/styles.xml b/tutorials/MoarRam/res/values-v11/styles.xml
new file mode 100644
index 0000000..541752f
--- /dev/null
+++ b/tutorials/MoarRam/res/values-v11/styles.xml
@@ -0,0 +1,11 @@
+<resources>
+
+    <!--
+        Base application theme for API 11+. This theme completely replaces
+        AppBaseTheme from res/values/styles.xml on API 11+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light">
+        <!-- API 11 theme customizations can go here. -->
+    </style>
+
+</resources>
\ No newline at end of file
diff --git a/tutorials/MoarRam/res/values-v14/styles.xml b/tutorials/MoarRam/res/values-v14/styles.xml
new file mode 100644
index 0000000..f20e015
--- /dev/null
+++ b/tutorials/MoarRam/res/values-v14/styles.xml
@@ -0,0 +1,12 @@
+<resources>
+
+    <!--
+        Base application theme for API 14+. This theme completely replaces
+        AppBaseTheme from BOTH res/values/styles.xml and
+        res/values-v11/styles.xml on API 14+ devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+        <!-- API 14 theme customizations can go here. -->
+    </style>
+
+</resources>
\ No newline at end of file
diff --git a/tutorials/MoarRam/res/values/dimens.xml b/tutorials/MoarRam/res/values/dimens.xml
new file mode 100644
index 0000000..a6dd140
--- /dev/null
+++ b/tutorials/MoarRam/res/values/dimens.xml
@@ -0,0 +1,7 @@
+<resources>
+
+    <!-- Default screen margins, per the Android Design guidelines. -->
+    <dimen name="activity_horizontal_margin">16dp</dimen>
+    <dimen name="activity_vertical_margin">16dp</dimen>
+
+</resources>
\ No newline at end of file
diff --git a/tutorials/MoarRam/res/values/strings.xml b/tutorials/MoarRam/res/values/strings.xml
new file mode 100644
index 0000000..0c0031d
--- /dev/null
+++ b/tutorials/MoarRam/res/values/strings.xml
@@ -0,0 +1,16 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+
+    <string name="app_name">MoarRam</string>
+    <string name="action_settings">Settings</string>
+    <string name="hello_world">Hello world!</string>
+    <string name="enter_num">Enter a number</string>
+    <string name="add_32">Add 32 bytes</string>
+    <string name="free_32">Free 32 bytes</string>
+    <string name="add_2m">Add 2M bytes</string>
+    <string name="free_2m">Free 2M bytes</string>
+    <string name="add_variable">Add 17 or 71 bytes</string>
+    <string name="free_variable">Free 17 or 71 bytes</string>
+    <string name="_17byte">17 bytes</string>
+    <string name="_71byte">71 bytes</string>
+</resources>
diff --git a/tutorials/MoarRam/res/values/styles.xml b/tutorials/MoarRam/res/values/styles.xml
new file mode 100644
index 0000000..4a10ca4
--- /dev/null
+++ b/tutorials/MoarRam/res/values/styles.xml
@@ -0,0 +1,20 @@
+<resources>
+
+    <!--
+        Base application theme, dependent on API level. This theme is replaced
+        by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+    -->
+    <style name="AppBaseTheme" parent="android:Theme.Light">
+        <!--
+            Theme customizations available in newer API levels can go in
+            res/values-vXX/styles.xml, while customizations related to
+            backward-compatibility can go here.
+        -->
+    </style>
+
+    <!-- Application theme. -->
+    <style name="AppTheme" parent="AppBaseTheme">
+        <!-- All customizations that are NOT specific to a particular API-level can go here. -->
+    </style>
+
+</resources>
\ No newline at end of file
diff --git a/tutorials/MoarRam/src/com/android/benchmark/moarram/MainActivity.java b/tutorials/MoarRam/src/com/android/benchmark/moarram/MainActivity.java
new file mode 100644
index 0000000..aa83b8c
--- /dev/null
+++ b/tutorials/MoarRam/src/com/android/benchmark/moarram/MainActivity.java
@@ -0,0 +1,64 @@
+package com.android.benchmark.moarram;
+
+import android.os.Bundle;
+import android.app.Activity;
+import android.view.Menu;
+import android.view.View;
+import android.widget.RadioGroup;
+
+public class MainActivity extends Activity {
+
+    @Override
+    protected void onCreate(Bundle savedInstanceState) {
+        super.onCreate(savedInstanceState);
+        System.loadLibrary("moarram-32");
+        System.loadLibrary("moarram-2M");
+        System.loadLibrary("moarram-17_71");
+        setContentView(R.layout.activity_main);
+    }
+
+    @Override
+    public boolean onCreateOptionsMenu(Menu menu) {
+        getMenuInflater().inflate(R.menu.main, menu);
+        return true;
+    }
+
+    public void add32ByteBlocks(View view) {
+        add32ByteBlocksNative();
+    }
+
+    public void free32ByteBlocks(View view) {
+        free32ByteBlocksNative();
+    }
+
+    public void add2MByteBlocks(View view) {
+        add2MByteBlocksNative();
+    }
+
+    public void free2MByteBlocks(View view) {
+        free2MByteBlocksNative();
+    }
+
+    public void addVariableSizedBlocks(View view) {
+
+        RadioGroup sizeGroup = (RadioGroup) findViewById(R.id.blockSize);
+
+        int sizeId = sizeGroup.getCheckedRadioButtonId();
+        addVariableSizedBlocksNative(sizeId == R.id.radio17 ? 0 : 1);
+    }
+
+    public void freeVariableSizedBlocks(View view) {
+
+        RadioGroup sizeGroup = (RadioGroup) findViewById(R.id.blockSize);
+
+        int sizeId = sizeGroup.getCheckedRadioButtonId();
+        freeVariableSizedBlocksNative(sizeId == R.id.radio17 ? 0 : 1);
+    }
+
+    public native void add32ByteBlocksNative();
+    public native void free32ByteBlocksNative();
+    public native void add2MByteBlocksNative();
+    public native void free2MByteBlocksNative();
+    public native void addVariableSizedBlocksNative(int sizeId);
+    public native void freeVariableSizedBlocksNative(int sizeId);
+}