Merge "ndk-gdb.py: work around permissions issue with minSdkVersion >= 24."
diff --git a/README.md b/README.md
index 3278160..35c8aa7 100644
--- a/README.md
+++ b/README.md
@@ -87,18 +87,19 @@
         ```
 
 * Additional Linux Dependencies (available from apt):
+    * asciidoctor
     * bison
+    * dos2unix
     * flex
     * libtool
     * mingw-w64
-    * zip
     * pbzip2 (optional, improves packaging times)
-    * texinfo
-    * asciidoctor
-    * ruby-pygments.rb
+    * python-lxml (used for Vulkan validation layer generation)
     * python-nose
     * python3 (used for Vulkan validation layer generation)
-    * python-lxml (used for Vulkan validation layer generation)
+    * ruby-pygments.rb
+    * texinfo
+    * zip
 * Mac OS X also requires Xcode.
 * Running tests requires that `adb` is in your `PATH`. This is provided as part
   of the [Android SDK].
diff --git a/build/cmake/android.toolchain.cmake b/build/cmake/android.toolchain.cmake
index 8412854..9ee2cdd 100644
--- a/build/cmake/android.toolchain.cmake
+++ b/build/cmake/android.toolchain.cmake
@@ -297,6 +297,7 @@
 	set(ANDROID_LLVM_TOOLCHAIN_PREFIX "${ANDROID_NDK}/toolchains/llvm/prebuilt/${ANDROID_HOST_TAG}/bin/")
 	set(ANDROID_C_COMPILER   "${ANDROID_LLVM_TOOLCHAIN_PREFIX}clang${ANDROID_TOOLCHAIN_SUFFIX}")
 	set(ANDROID_CXX_COMPILER "${ANDROID_LLVM_TOOLCHAIN_PREFIX}clang++${ANDROID_TOOLCHAIN_SUFFIX}")
+	set(ANDROID_ASM_COMPILER "${ANDROID_LLVM_TOOLCHAIN_PREFIX}clang${ANDROID_TOOLCHAIN_SUFFIX}")
 	# Clang can fail to compile if CMake doesn't correctly supply the target and
 	# external toolchain, but to do so, CMake needs to already know that the
 	# compiler is clang. Tell CMake that the compiler is really clang, but don't
@@ -308,11 +309,14 @@
 	set(CMAKE_CXX_COMPILER_ID Clang)
 	set(CMAKE_C_COMPILER_TARGET   ${ANDROID_LLVM_TRIPLE})
 	set(CMAKE_CXX_COMPILER_TARGET ${ANDROID_LLVM_TRIPLE})
+	set(CMAKE_ASM_COMPILER_TARGET ${ANDROID_LLVM_TRIPLE})
 	set(CMAKE_C_COMPILER_EXTERNAL_TOOLCHAIN   "${ANDROID_TOOLCHAIN_ROOT}")
 	set(CMAKE_CXX_COMPILER_EXTERNAL_TOOLCHAIN "${ANDROID_TOOLCHAIN_ROOT}")
+	set(CMAKE_ASM_COMPILER_EXTERNAL_TOOLCHAIN "${ANDROID_TOOLCHAIN_ROOT}")
 elseif(ANDROID_TOOLCHAIN STREQUAL gcc)
 	set(ANDROID_C_COMPILER   "${ANDROID_TOOLCHAIN_PREFIX}gcc${ANDROID_TOOLCHAIN_SUFFIX}")
 	set(ANDROID_CXX_COMPILER "${ANDROID_TOOLCHAIN_PREFIX}g++${ANDROID_TOOLCHAIN_SUFFIX}")
+	set(ANDROID_ASM_COMPILER "${ANDROID_TOOLCHAIN_PREFIX}gcc${ANDROID_TOOLCHAIN_SUFFIX}")
 else()
 	message(FATAL_ERROR "Invalid Android toolchain: ${ANDROID_TOOLCHAIN}.")
 endif()
@@ -547,14 +551,20 @@
 	CACHE STRING "Flags used by the compiler during all build types.")
 set(CMAKE_CXX_FLAGS ""
 	CACHE STRING "Flags used by the compiler during all build types.")
+set(CMAKE_ASM_FLAGS ""
+	CACHE STRING "Flags used by the compiler during all build types.")
 set(CMAKE_C_FLAGS_DEBUG ""
 	CACHE STRING "Flags used by the compiler during debug builds.")
 set(CMAKE_CXX_FLAGS_DEBUG ""
 	CACHE STRING "Flags used by the compiler during debug builds.")
+set(CMAKE_ASM_FLAGS_DEBUG ""
+	CACHE STRING "Flags used by the compiler during debug builds.")
 set(CMAKE_C_FLAGS_RELEASE ""
 	CACHE STRING "Flags used by the compiler during release builds.")
 set(CMAKE_CXX_FLAGS_RELEASE ""
 	CACHE STRING "Flags used by the compiler during release builds.")
+set(CMAKE_ASM_FLAGS_RELEASE ""
+	CACHE STRING "Flags used by the compiler during release builds.")
 set(CMAKE_MODULE_LINKER_FLAGS ""
 	CACHE STRING "Flags used by the linker during the creation of modules.")
 set(CMAKE_SHARED_LINKER_FLAGS ""
@@ -564,10 +574,13 @@
 
 set(CMAKE_C_FLAGS             "${ANDROID_COMPILER_FLAGS} ${CMAKE_C_FLAGS}")
 set(CMAKE_CXX_FLAGS           "${ANDROID_COMPILER_FLAGS} ${ANDROID_COMPILER_FLAGS_CXX} ${CMAKE_CXX_FLAGS}")
+set(CMAKE_ASM_FLAGS           "${ANDROID_COMPILER_FLAGS} ${CMAKE_ASM_FLAGS}")
 set(CMAKE_C_FLAGS_DEBUG       "${ANDROID_COMPILER_FLAGS_DEBUG} ${CMAKE_C_FLAGS_DEBUG}")
 set(CMAKE_CXX_FLAGS_DEBUG     "${ANDROID_COMPILER_FLAGS_DEBUG} ${CMAKE_CXX_FLAGS_DEBUG}")
+set(CMAKE_ASM_FLAGS_DEBUG     "${ANDROID_COMPILER_FLAGS_DEBUG} ${CMAKE_ASM_FLAGS_DEBUG}")
 set(CMAKE_C_FLAGS_RELEASE     "${ANDROID_COMPILER_FLAGS_RELEASE} ${CMAKE_C_FLAGS_RELEASE}")
 set(CMAKE_CXX_FLAGS_RELEASE   "${ANDROID_COMPILER_FLAGS_RELEASE} ${CMAKE_CXX_FLAGS_RELEASE}")
+set(CMAKE_ASM_FLAGS_RELEASE   "${ANDROID_COMPILER_FLAGS_RELEASE} ${CMAKE_ASM_FLAGS_RELEASE}")
 set(CMAKE_SHARED_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_SHARED_LINKER_FLAGS}")
 set(CMAKE_MODULE_LINKER_FLAGS "${ANDROID_LINKER_FLAGS} ${CMAKE_MODULE_LINKER_FLAGS}")
 set(CMAKE_EXE_LINKER_FLAGS    "${ANDROID_LINKER_FLAGS} ${ANDROID_LINKER_FLAGS_EXE} ${CMAKE_EXE_LINKER_FLAGS}")
diff --git a/build/core/definitions.mk b/build/core/definitions.mk
index 33bb5e9..5cc5707 100644
--- a/build/core/definitions.mk
+++ b/build/core/definitions.mk
@@ -378,6 +378,7 @@
     MODULE_FILENAME \
     PATH \
     SRC_FILES \
+    HAS_CPP \
     CPP_EXTENSION \
     C_INCLUDES \
     CFLAGS \
@@ -721,6 +722,10 @@
 # -----------------------------------------------------------------------------
 module-get-all-dependencies = $(call -ndk-mod-get-closure,$1,module-get-depends)
 
+# Same as module-get-all-dependencies, but topologically sorted.
+module-get-all-dependencies-topo = \
+    $(call -ndk-mod-get-topological-depends,$1,module-get-all-dependencies)
+
 # -----------------------------------------------------------------------------
 # Compute the list of all static and shared libraries required to link a
 # given module.
@@ -809,7 +814,8 @@
 
 # Returns true if a module has C++ sources
 #
-module-has-c++-sources = $(strip $(call module-get-c++-sources,$1))
+module-has-c++-sources = $(strip $(call module-get-c++-sources,$1) \
+                                 $(filter true,$(__ndk_modules.$1.HAS_CPP)))
 
 
 # Add C++ dependencies to any module that has C++ sources.
diff --git a/build/core/import-locals.mk b/build/core/import-locals.mk
index 7812453..3a97dd5 100644
--- a/build/core/import-locals.mk
+++ b/build/core/import-locals.mk
@@ -26,7 +26,7 @@
 # and 'zoo'
 #
 
-all_depends := $(call module-get-all-dependencies,$(LOCAL_MODULE))
+all_depends := $(call module-get-all-dependencies-topo,$(LOCAL_MODULE))
 all_depends := $(filter-out $(LOCAL_MODULE),$(all_depends))
 
 imported_CFLAGS     := $(call module-get-listed-export,$(all_depends),CFLAGS)
diff --git a/build/ndk-build b/build/ndk-build
index d3700b4..166d002 100755
--- a/build/ndk-build
+++ b/build/ndk-build
@@ -39,6 +39,7 @@
 #
 PROGDIR=`dirname $0`
 PROGDIR=`cd $PROGDIR && pwd -P`
+ANDROID_NDK_ROOT=$PROGDIR/..
 
 # Check if absolute NDK path contain space
 #
@@ -152,7 +153,7 @@
 # on 32-bit ones. This gives us more freedom in packaging the NDK.
 LOG_MESSAGE=
 if [ $HOST_ARCH = x86_64 ]; then
-  if [ ! -d $PROGDIR/prebuilt/$HOST_TAG ]; then
+  if [ ! -d $ANDROID_NDK_ROOT/prebuilt/$HOST_TAG ]; then
     HOST_ARCH=x86
     LOG_MESSAGE="(no 64-bit prebuilt binaries detected)"
   fi
@@ -179,7 +180,7 @@
     # Otherwise use the prebuilt version for our host tag, if it exists
     # Note: we intentionally do not provide prebuilt make binaries for Cygwin
     # or MSys.
-    GNUMAKE=$PROGDIR/prebuilt/$HOST_TAG/bin/make
+    GNUMAKE=$ANDROID_NDK_ROOT/prebuilt/$HOST_TAG/bin/make
     if [ ! -f "$GNUMAKE" ]; then
         # Otherwise, use 'make' and check that it is available
         GNUMAKE=`which make 2> /dev/null`
@@ -224,7 +225,7 @@
 fi
 
 if [ "$NDK_ANALYZE" = 1 ]; then
-    . $PROGDIR/build/tools/dev-defaults.sh  # for DEFAULT_LLVM_VERSION
+    . $PROGDIR/tools/dev-defaults.sh  # for DEFAULT_LLVM_VERSION
 
     # Return flags send in env. or command line which are enough to retrive APP_ABI and TOOLCHAIN_PREFIX later
     gen_flags ()
@@ -261,8 +262,8 @@
     APP_ABIS=`get_build_var APP_ABI`
     for ABI in $APP_ABIS; do
         TOOLCHAIN_PREFIX=`get_build_var_for_abi TOOLCHAIN_PREFIX $ABI`
-        LLVM_PATH=$PROGDIR/toolchains/llvm-${DEFAULT_LLVM_VERSION}/prebuilt
-        perl $LLVM_PATH/tools/scan-build/scan-build \
+        LLVM_PATH=$ANDROID_NDK_ROOT/toolchains/llvm/prebuilt/$HOST_TAG
+        perl $LLVM_PATH/tools/scan-build/bin/scan-build \
             --use-analyzer $LLVM_PATH/bin/${ABI}/analyzer \
             --use-cc ${TOOLCHAIN_PREFIX}gcc \
             --use-c++ ${TOOLCHAIN_PREFIX}g++ \
diff --git a/build/tools/build-llvm.py b/build/tools/build-llvm.py
index bf19e33..9388669 100755
--- a/build/tools/build-llvm.py
+++ b/build/tools/build-llvm.py
@@ -36,7 +36,7 @@
 
 
 def main(args):
-    LLVM_VERSION = 'clang-2812033'
+    LLVM_VERSION = 'clang-3362437'
 
     host = args.host
     package_dir = args.dist_dir
@@ -58,7 +58,8 @@
         host = 'windows-x86_64'
 
     if host == 'windows':
-        # We need to replace clang.exe with clang_32.exe. Copy clang into a
+        # We need to replace clang.exe with clang_32.exe and
+        # libwinpthread-1.dll with libwinpthread-1.dll.32. Copy clang into a
         # temporary directory for rearranging.
         build_path = os.path.join(args.out_dir, 'clang/windows')
         if os.path.exists(build_path):
@@ -69,11 +70,33 @@
                         install_path)
         os.rename(os.path.join(install_path, 'bin/clang_32.exe'),
                   os.path.join(install_path, 'bin/clang.exe'))
+        os.rename(os.path.join(install_path, 'bin/libwinpthread-1.dll.32'),
+                  os.path.join(install_path, 'bin/libwinpthread-1.dll'))
         # clang++.exe is not a symlink in the Windows package. Need to copy to
         # there as well.
         shutil.copy2(os.path.join(install_path, 'bin/clang.exe'),
                      os.path.join(install_path, 'bin/clang++.exe'))
         prebuilt_path = build_path
+    elif host in ('darwin-x86_64', 'linux-x86_64'):
+        # The Linux and Darwin toolchains have Python compiler wrappers that
+        # currently do nothing. We don't have these for Windows and we want to
+        # make sure Windows behavior is consistent with the other platforms, so
+        # just unwrap the compilers until they do something useful and are
+        # available on Windows.
+        build_path = os.path.join(args.out_dir, 'clang/windows')
+        if os.path.exists(build_path):
+            shutil.rmtree(build_path)
+        install_path = os.path.join(build_path, LLVM_VERSION)
+        os.makedirs(build_path)
+        shutil.copytree(os.path.join(prebuilt_path, LLVM_VERSION),
+                        install_path)
+
+        os.rename(os.path.join(install_path, 'bin/clang.real'),
+                  os.path.join(install_path, 'bin/clang'))
+        os.rename(os.path.join(install_path, 'bin/clang++.real'),
+                  os.path.join(install_path, 'bin/clang++'))
+
+        prebuilt_path = build_path
 
     package_name = 'llvm-{}.zip'.format(host)
     package_path = os.path.join(package_dir, package_name)
diff --git a/build/tools/build-shader-tools.py b/build/tools/build-shader-tools.py
index cd32047..af76e47 100755
--- a/build/tools/build-shader-tools.py
+++ b/build/tools/build-shader-tools.py
@@ -126,13 +126,26 @@
     files_to_copy = ['glslc' + file_extension,
                      'spirv-as' + file_extension,
                      'spirv-dis' + file_extension,
-                     'spirv-val' + file_extension]
+                     'spirv-val' + file_extension,
+                     'spirv-cfg' + file_extension,
+                     'spirv-opt' + file_extension]
+    scripts_to_copy = ['spirv-lesspipe.sh',]
+    files_to_copy.extend(scripts_to_copy)
+
+    # Test, except on windows.
     if (not args.host.startswith('windows')):
         subprocess.check_call([ctest, '--verbose'], cwd=obj_out)
 
+    # Copy to install tree.
     for src in files_to_copy:
         shutil.copy2(os.path.join(install_dir, 'bin', src),
                      os.path.join(package_src, src))
+    if args.host.startswith('windows'):
+        for src in scripts_to_copy:
+            # Convert line endings on scripts.
+            # Do it in place to preserve executable permissions.
+            subprocess.check_call(['unix2dos', '-o',
+                                   os.path.join(package_src, src)])
 
     build_support.make_package(package_name, package_src, package_dir)
 
diff --git a/docs/.gitignore b/docs/.gitignore
index ef24885..e2e7327 100644
--- a/docs/.gitignore
+++ b/docs/.gitignore
@@ -1,2 +1 @@
-/.build
-/html
+/out
diff --git a/docs/PlatformApis.md b/docs/PlatformApis.md
index 4d56fc7..1484090 100644
--- a/docs/PlatformApis.md
+++ b/docs/PlatformApis.md
@@ -8,6 +8,54 @@
 NDK. For the time being, the old method is still in use as well, and is covered
 by [Generating Sysroots](GeneratingSysroots.md).
 
+Implications of Adding a New Platform API
+-----------------------------------------
+
+Before adding a platform API to the NDK, there are some guarantees and
+restrictions that need to be considered.
+
+### ABI Compatibility
+
+The NDK ABI must be forward compatible. Apps that are in the Play Store must
+continue to function on new devices. This means that once something becomes NDK
+ABI, it must continue to be exposed and behavior must be preserved by the
+platform for the lifetime of the ABI (for all intents and purposes, forever).
+The NDK ABI includes but is not limited to:
+
+ * Exposed functions and global data.
+ * Layout and size of publicly visible data structures.
+ * Values of constants (such as enums).
+
+### Source Compatibility
+
+Source compatibility should be maintained, though exceptions have been made.
+When appropriate, source compatibility breaking features can be limited to only
+breaking when the user is targeting at least the API level that broke the change
+(e.g. `#if __ANDROID_API__ >= 24`), which ensures that any currently building
+app will continue building until the developer chooses to upgrade to a new
+platform level.
+
+Note that the definition of target API level in the NDK differs from the SDK.
+For the NDK, the target API level is the minimum supported API level for the
+app. If any non-ABI features are guarded by the target API level, they will only
+be available to apps with a minimum target that includes that API level.
+
+As a practical example of this, the NDK historically did not expose the `ALOG*`
+log macros, only the `__android_log_*` functions. If the macros were to be added
+but only exposed for API levels android-24 and newer, these helper macros that
+could otherwise be available to Gingerbread would only be usable by developers
+that chose to forfeit all Android users on devices older than android-24.
+
+### API Restrictions
+
+NDK APIs are C APIs only. This restriction may be lifted in the future, but at
+the moment Android's C++ ABI is not guaranteed to be stable. Note that this does
+not restrict the implementation of the API to C, only the interface that is
+exposed in the headers.
+
+NDK API headers can only depend on other NDK API headers. Platform headers from
+android-base, libcutils, libnativehelper, etc are not available to the NDK.
+
 For Platform Developers
 -----------------------
 
@@ -69,21 +117,6 @@
 }
 ```
 
-### Inform the build system
-
-The build system needs to know your library has been migrated to the new form so
-it can get the libraries from the out directory instead of prebuilts/ndk.
-Example CL: https://android-review.googlesource.com/#/c/251420/
-
-Note that if you're migraring an existing library you'll also need to remove the
-old prebuilt/ndk module. Here's an example of doing that for libc and libm:
-https://android-review.googlesource.com/#/c/251420/ (and also the CL for running
-the generator: https://android-review.googlesource.com/#/c/251441/).
-
-A full topic of migrating libc and libm from prebuilts/ndk to `ndk_library` and
-`ndk_headers` can be found here:
-https://android-review.googlesource.com/#/q/topic:ndk_library-libc-libm
-
 [bionic/libc/Android.bp]: https://android.googlesource.com/platform/bionic/+/master/libc/Android.bp
 
 For NDK Developers
diff --git a/docs/Toolchains.md b/docs/Toolchains.md
index 3be9c9b..afd53b4 100644
--- a/docs/Toolchains.md
+++ b/docs/Toolchains.md
@@ -70,7 +70,9 @@
 ### Updating to a New Clang
 
 These steps need to be run after installing the new prebuilt from the build
-server to `prebuilts/clang` (see the Clang docs).
+server to `prebuilts/clang` (see the [Clang docs]).
+
+[Clang docs]: https://android.googlesource.com/platform/external/clang/+/dev/ToolchainPrebuilts.md
 
 ```bash
 # Edit ndk/build/tools/build-llvm.py and update the build number.
diff --git a/docs/user/dac_template.jd b/docs/user/dac_template.jd
deleted file mode 100644
index 2fc7817..0000000
--- a/docs/user/dac_template.jd
+++ /dev/null
@@ -1,14 +0,0 @@
-page.title=$title$
-@jd:body
-
-<!-- This file is auto-generated from the NDK. To update this page, see
-https://android.googlesource.com/platform/ndk/+/master/docs/UpdatingDocumentation.md -->
-
-<div id="qv-wrapper">
-  <div id="qv">
-    <h2>On this page</h2>
-    $toc$
-  </div>
-</div>
-
-$body$
diff --git a/docs/user/standalone_toolchain.md b/docs/user/standalone_toolchain.md
index 532265d..71d9860 100644
--- a/docs/user/standalone_toolchain.md
+++ b/docs/user/standalone_toolchain.md
@@ -1,6 +1,8 @@
 Standalone Toolchains
 =====================
 
+[TOC]
+
 You can use the toolchains provided with the Android NDK independently or as
 plug-ins with an existing IDE. This flexibility can be useful if you already
 have your own build system, and only need the ability to invoke the
@@ -9,12 +11,10 @@
 A typical use case is invoking the configure script of an open-source library
 that expects a cross-compiler in the `CC` environment variable.
 
-<p class="note">
-<strong>Note:</strong> This page assumes significant understanding of compiling,
-linking, and low-level architecture. In addition, the techniques it describes
-are unnecessary for most use cases. In most cases, we recommend that you forego
-using a standalone toolchain, and instead stick to the NDK build system.
-</p>
+Note: This page assumes significant understanding of compiling, linking, and
+low-level architecture. In addition, the techniques it describes are unnecessary
+for most use cases. In most cases, we recommend that you forego using a
+standalone toolchain, and instead stick to the NDK build system.
 
 Selecting Your Toolchain
 ------------------------
@@ -79,13 +79,15 @@
 paths. In other words, you can install them in any location or even move them if
 you need to.
 
-The `--arch` arugment is required, but the STL will default to gnustl and the
+The `--arch` argument is required, but the STL will default to gnustl and the
 API level will be set to the minimum supported level for the given architecture
 (currently 9 for 32-bit architectures and 21 for 64-bit architectures) if not
 explicitly stated.
 
 Unlike the old tool, Clang is always copied into the toolchain. Every standalone
-toolchain is useable for both Clang and GCC.
+toolchain is useable for both Clang and GCC. For more information about Clang,
+see [Clang's website](http://clang.llvm.org/), especially the GCC compatibility
+section.
 
 You may specify `--stl=stlport` to copy `libstlport` instead of the default
 `libgnustl`. If you do so, and you wish to link against the shared library, you
@@ -93,17 +95,14 @@
 use `-lgnustl_shared` for GNU `libstdc++`.
 
 Similarly, you can specify `--stl=libc++` to copy the LLVM libc++ headers and
-libraries.  To link against the shared library, you must explicitly use
-`-lc++_shared`. As mentioned in [C++ Library Support](cpp-support.html), you
-will often need to pass `-latomic` when linking against libc++.
+libraries. Unlike gnustl and stlport, you do not need to explicitly pass
+`-lc++_shared` to use the shared library. The shared library will be used by
+default unless building a static executable. To force the use of the static
+library, pass `-static-libstdc++` when linking. This behavior matches that of a
+normal host toolchain.
 
-You can make these settings directly, as in the following example:
-
-```bash
-export PATH=/tmp/my-android-toolchain/bin:$PATH
-export CC=arm-linux-androideabi-gcc   # or export CC=clang
-export CXX=arm-linux-androideabi-g++  # or export CXX=clang++
-```
+As mentioned in [C++ Library Support](cpp-support.html), you will often need to
+pass `-latomic` when linking against libc++.
 
 Note that if you omit the `--install-dir` option, the tool creates a tarball in
 the current directory named `$TOOLCHAIN_NAME.tar.bz2`. The tarball can be placed
@@ -117,11 +116,11 @@
 Clang binaries are automatically included in standalone toolchains created with
 the new tool.
 
-Note that Clang binaries are copied along with the GCC ones, because they rely
-on the same assembler, linker, headers, libraries, and C++ STL implementation.
+Note: Clang binaries are copied along with the GCC ones, because they rely on
+the same assembler, linker, headers, libraries, and C++ STL implementation.
 
-This operation also installs two scripts, named `clang` and `clang++`, under
-`<install-dir>/bin`. These scripts invoke the real `clang` binary with the
+This operation also installs two wrapper scripts, named `clang` and `clang++`,
+under `<install-dir>/bin`. These scripts invoke the `clang` binary with the
 correct target architecture flags. In other words, they should work without any
 modification, and you should be able to use them in your own builds by just
 setting the `CC` and `CXX` environment variables to point to them.
@@ -129,7 +128,7 @@
 ### Clang targets with ARM
 
 When building for ARM, Clang changes the target based on the presence of the
-`-march=armv7-a` and/or `-mthumb` options:
+`-march=armv7-a` and/or `-mthumb` compiler flags:
 
 **Table 2.** Specifiable `-march` values and their resulting targets.
 
@@ -141,21 +140,15 @@
 
 You may also override with your own `-target` if you wish.
 
-The `-gcc-toolchain` option is unnecessary in a standalone toolchain because
-Clang locates `as` and `ld` in a predefined relative location.
-
 `clang` and `clang++` should be drop-in replacements for `gcc` and `g++` in a
-makefile. When in doubt, add the following options to verify that they are
-working properly:
+makefile. When in doubt, use the following options when invoking the compiler to
+verify that they are working properly:
 
 * `-v` to dump commands associated with compiler driver issues
 * `-###` to dump command line options, including implicitly predefined ones.
 * `-x c < /dev/null -dM -E` to dump predefined preprocessor definitions
 * `-save-temps` to compare `*.i` or `*.ii` preprocessed files.
 
-For more information about Clang, see http://clang.llvm.org/, especially the GCC
-compatibility section.
-
 ABI Compatibility
 -----------------
 
@@ -163,11 +156,8 @@
 GCC will target armeabi. Either can be controlled by passing the appropriate
 `-march` flag, and Clang can also be controlled with `-target`.
 
-To target armeabi-v7a with GCC, you must set the following flags:
-
-```
-CFLAGS= -march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16
-```
+To target armeabi-v7a with GCC, you must set the following flags when invoking
+the compiler: `-march=armv7-a -mfloat-abi=softfp -mfpu=vfpv3-d16`.
 
 The first flag targets the armv7 architecture. The second flag enables
 hardware-FPU instructions while ensuring that the system passes floating-point
@@ -177,23 +167,16 @@
 16-bit Thumb-2 instructions (Thumb-1 for armeabi). If omitted, the toolchain
 will emit 32-bit ARM instructions.
 
-To use NEON instructions, you must change the `-mfpu` compiler flag:
-
-```
-CFLAGS= -march=armv7-a -mfloat-abi=softfp -mfpu=neon
-```
+To use NEON instructions, you must use the `-mfpu` compiler flag: `-mfpu=neon`.
 
 Note that this setting forces the use of `VFPv3-D32`, per the ARM specification.
 
 Also, make sure to provide the following two flags to the linker:
+`-march=armv7-a -Wl,--fix-cortex-a8`.
 
-```
-LDFLAGS= -march=armv7-a -Wl,--fix-cortex-a8
-```
-
-The first flag instructs the linker to pick `libgcc.a`, `libgcov.a`, and
-`crt*.o`, which are tailored for armv7-a. The 2nd flag is required as a
-workaround for a CPU bug in some Cortex-A8 implementations.
+The first flag instructs the linker to pick toolchain libraries which are
+tailored for armv7-a. The 2nd flag is required as a workaround for a CPU bug in
+some Cortex-A8 implementations.
 
 You don't have to use any specific compiler flag when targeting the other ABIs.
 
@@ -232,11 +215,12 @@
 
 The standalone toolchain includes a copy of a C++ Standard Template Library
 implementation. This implementation is either for GNU libstdc++, STLport, or
-libc++, depending on what you specify for the `--stl=<name>` option described
-previously. To use this implementation of STL, you need to link your project
-with the proper library:
+libc++, depending on what you specify for the `--stl=<name>` option [described
+previously](#creating_the_toolchain). To use this implementation of STL, you
+need to link your project with the proper library:
 
-* Use `-lstdc++` to link against the static library version of any
+* Use `-static-libstdc++` when using libc++ for the static library version, or
+  `-lstdc++` (implicit) to link against the static library version of any other
   implementation. Doing so ensures that all required C++ STL code is included
   into your final binary. This method is ideal if you are only generating a
   single shared library or executable.
@@ -245,20 +229,21 @@
 
 * Alternatively, use `-lgnustl_shared` to link against the shared library
   version of GNU `libstdc++`. If you use this option, you must also make sure to
-  copy `libgnustl_shared.so` to your device in order for your code to load
-  properly. Table 6 shows where this file is for each toolchain type.
+  package `libgnustl_shared.so` with your app in order for your code to load
+  properly. Table 3 shows where this file is for each toolchain type.
 
-  <p class="note">
-  <strong>Note:</strong> GNU libstdc++ is licensed under the GPLv3 license, with
-  a linking exception. If you cannot comply with its requirements, you cannot
-  redistribute the shared library in your project.
-  </p>
-
+  Note: GNU libstdc++ is licensed under the GPLv3 license, with a linking
+  exception. If you cannot comply with its requirements, you cannot redistribute
+  the shared library in your project.
 
 * Use `-lstlport_shared` to link against the shared library version of STLport.
-  When you do so, you need to make sure that you also copy
-  `libstlport_shared.so` to your device in order for your code to load properly.
-  Table 6 shows where this file is for each toolchain:
+  When you do so, you need to make sure that you also package
+  `libstlport_shared.so` with your app in order for your code to load properly.
+  Table 3 shows where this file is for each toolchain:
+
+* The shared library version of libc++ will be used by default. If you use this
+  option, `libc++_shared.so` must be packaged with your app or your code will
+  not load.  Table 3 shows where this file is for each architecture.
 
   **Table 3.** Specifiable `-march` values and their resulting targets.
 
@@ -271,15 +256,13 @@
   | x86       | `$TOOLCHAIN/i686-linux-android/lib/`     |
   | x86\_64   | `$TOOLCHAIN/x86_64-linux-android/lib/`   |
 
-<p class="note">
-<strong>Note:</strong> If your project contains multiple shared libraries or
-executables, you must link against a shared-library STL implementation.
-Otherwise global state in these libraries will not be unique, which can result
-in unpredictable runtime behavior. This behavior may include crashes and
-failure to properly catch exceptions.
-</p>
+Note: If your project contains multiple shared libraries or executables, you
+must link against a shared-library STL implementation.  Otherwise global state
+in these libraries will not be unique, which can result in unpredictable runtime
+behavior. This behavior may include crashes and failure to properly catch
+exceptions.
 
 The reason the shared version of the libraries is not simply called
 `libstdc++.so` is that this name would conflict at runtime with the system's own
 minimal C++ runtime. For this reason, the build system enforces a new name for
-the GNU ELF library. The static library does not have this problem.
+the GNU library. The static library does not have this problem.
diff --git a/scripts/update_dac.py b/scripts/update_dac.py
index 2029cb8..f2d14cc 100755
--- a/scripts/update_dac.py
+++ b/scripts/update_dac.py
@@ -18,35 +18,76 @@
 import argparse
 import logging
 import os.path
-import shutil
-import subprocess
 
 
 THIS_DIR = os.path.realpath(os.path.dirname(__file__))
 NDK_DIR = os.path.dirname(THIS_DIR)
 
 
-def check_call(cmd, *args, **kwargs):
-    logging.getLogger(__name__).info('COMMAND: %s', ' '.join(cmd))
-    subprocess.check_call(cmd, *args, **kwargs)
+def logger():
+    """Get the module logger."""
+    return logging.getLogger(__name__)
+
+
+def copy2(src, dst):
+    """shutil.copy2 with logging."""
+    import shutil
+    logger().info('copy2: %s %s', src, dst)
+    shutil.copy2(src, dst)
+
+
+def rmtree(path):
+    """shutil.rmtree with logging."""
+    import shutil
+    logger().info('rmtree: %s', path)
+    shutil.rmtree(path)
+
+
+def makedirs(path):
+    """os.makedirs with logging."""
+    logger().info('makedirs: %s', path)
+    os.makedirs(path)
 
 
 def build_docs():
-    docs_dir = os.path.join(NDK_DIR, 'docs')
-    check_call(['make', '-C', docs_dir])
-    return os.path.join(docs_dir, 'html/user')
+    """Perform any necessary preprocessing steps.
+
+    * Rewrite "[TOC]" (gitiles spelling) to "[[TOC]]" (devsite spelling).
+    * Add devsite metadata for navigation support.
+    """
+    docs_dir = os.path.join(NDK_DIR, 'docs/user')
+    out_dir = os.path.join(NDK_DIR, 'docs/out')
+    if os.path.exists(out_dir):
+        rmtree(out_dir)
+    makedirs(out_dir)
+    for doc in os.listdir(docs_dir):
+        with open(os.path.join(out_dir, doc), 'w') as out_file:
+            out_file.write(
+                'Project: /ndk/_project.yaml\n'
+                'Book: /ndk/guides/_book.yaml\n'
+                'Subcategory: guide\n'
+                '\n')
+
+            path = os.path.join(docs_dir, doc)
+            with open(path) as in_file:
+                contents = in_file.read()
+                contents = contents.replace('[TOC]', '[[TOC]]')
+                out_file.write(contents)
+    return out_dir
 
 
 def copy_docs(docs_tree, docs_out):
-    dest_dir = os.path.join(docs_tree, 'frameworks/base/docs/html/ndk/guides')
+    """Copy the docs to the devsite directory."""
+    dest_dir = os.path.join(
+        docs_tree, 'googledata/devsite/site-android/en/ndk/guides')
 
-    for root, _dirs, files in os.walk(docs_out):
+    for root, _, files in os.walk(docs_out):
         for file_name in files:
-            shutil.copy2(os.path.join(root, file_name), dest_dir)
-            check_call(['git', '-C', dest_dir, 'add', file_name])
+            copy2(os.path.join(root, file_name), dest_dir)
 
 
 def parse_args():
+    """Parse command line arguments."""
     parser = argparse.ArgumentParser()
 
     parser.add_argument(
@@ -57,6 +98,7 @@
 
 
 def main():
+    """Program entry point."""
     logging.basicConfig(level=logging.INFO)
     args = parse_args()
     docs_out = build_docs()
diff --git a/sources/android/support/Android.mk b/sources/android/support/Android.mk
index ceaca06..84ab738 100644
--- a/sources/android/support/Android.mk
+++ b/sources/android/support/Android.mk
@@ -145,6 +145,7 @@
 include $(CLEAR_VARS)
 LOCAL_MODULE := android_support
 LOCAL_SRC_FILES := $(LIBCXX_LIBS)/lib$(LOCAL_MODULE)$(TARGET_LIB_EXTENSION)
+LOCAL_EXPORT_C_INCLUDES := $(android_support_c_includes)
 include $(PREBUILT_STATIC_LIBRARY)
 
 else # Building
@@ -170,8 +171,7 @@
   -Wno-shift-negative-value
 endif
 
-LOCAL_CFLAGS += $(android_support_cflags)
-LOCAL_EXPORT_CFLAGS := $(android_support_cflags)
+LOCAL_EXPORT_C_INCLUDES := $(android_support_c_includes)
 include $(BUILD_STATIC_LIBRARY)
 
 endif # Prebuilt/building
diff --git a/sources/android/support/include/locale.h b/sources/android/support/include/locale.h
index b051a97..c9607fb 100644
--- a/sources/android/support/include/locale.h
+++ b/sources/android/support/include/locale.h
@@ -94,7 +94,9 @@
 extern locale_t uselocale(locale_t);
 extern void     freelocale(locale_t);
 
+#ifndef LC_GLOBAL_LOCALE
 #define LC_GLOBAL_LOCALE    ((locale_t) -1L)
+#endif
 
 struct lconv {
     char* decimal_point;       /* Decimal point character */
diff --git a/sources/cxx-stl/llvm-libc++/build.py b/sources/cxx-stl/llvm-libc++/build.py
index cf87c44..eaf011f 100755
--- a/sources/cxx-stl/llvm-libc++/build.py
+++ b/sources/cxx-stl/llvm-libc++/build.py
@@ -116,7 +116,7 @@
             static_libs.extend(['-lunwind', '-latomic'])
         make_linker_script(os.path.join(install_dir, 'libc++.a'), static_libs)
 
-        shared_libs = ['-lc++abi', '-landroid_support']
+        shared_libs = ['-landroid_support']
         if is_arm:
             shared_libs.extend(['-lunwind', '-latomic'])
         shared_libs.append('-lc++_shared')
diff --git a/tests/build/LOCAL_HAS_CPP/jni/Android.mk b/tests/build/LOCAL_HAS_CPP/jni/Android.mk
new file mode 100644
index 0000000..803f846
--- /dev/null
+++ b/tests/build/LOCAL_HAS_CPP/jni/Android.mk
@@ -0,0 +1,10 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libfoo
+LOCAL_SRC_FILES := foo.c
+LOCAL_HAS_CPP := true
+ifeq ($(TARGET_ARCH_ABI),armeabi)
+    LOCAL_LDFLAGS := -latomic
+endif
+include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/build/LOCAL_HAS_CPP/jni/Application.mk b/tests/build/LOCAL_HAS_CPP/jni/Application.mk
new file mode 100644
index 0000000..ce09535
--- /dev/null
+++ b/tests/build/LOCAL_HAS_CPP/jni/Application.mk
@@ -0,0 +1 @@
+APP_STL := c++_static
diff --git a/tests/build/LOCAL_HAS_CPP/jni/foo.c b/tests/build/LOCAL_HAS_CPP/jni/foo.c
new file mode 100644
index 0000000..e6674b5
--- /dev/null
+++ b/tests/build/LOCAL_HAS_CPP/jni/foo.c
@@ -0,0 +1,12 @@
+// https://github.com/android-ndk/ndk/issues/205
+// This test is verifying that we can link the STL even if we don't know about
+// any explicit C++ dependencies for the module. `LOCAL_HAS_CPP := true`
+// instructs ndk-build to link the STL anyway.
+//
+// To test that this is working, we define an extern for `std::terminate` and
+// call it in a C file. Without `LOCAL_HAS_CPP := true`, this module would fail
+// to link because it wouldn't be able to find `std::terminate`.
+extern void _ZSt9terminatev();
+void terminate() {
+  _ZSt9terminatev();
+}
diff --git a/tests/build/LOCAL_HAS_CPP_negative_test/jni/Android.mk b/tests/build/LOCAL_HAS_CPP_negative_test/jni/Android.mk
new file mode 100644
index 0000000..164cccb
--- /dev/null
+++ b/tests/build/LOCAL_HAS_CPP_negative_test/jni/Android.mk
@@ -0,0 +1,6 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libfoo
+LOCAL_SRC_FILES := foo.c
+include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/build/LOCAL_HAS_CPP_negative_test/jni/Application.mk b/tests/build/LOCAL_HAS_CPP_negative_test/jni/Application.mk
new file mode 100644
index 0000000..ce09535
--- /dev/null
+++ b/tests/build/LOCAL_HAS_CPP_negative_test/jni/Application.mk
@@ -0,0 +1 @@
+APP_STL := c++_static
diff --git a/tests/build/LOCAL_HAS_CPP_negative_test/jni/foo.c b/tests/build/LOCAL_HAS_CPP_negative_test/jni/foo.c
new file mode 100644
index 0000000..c757983
--- /dev/null
+++ b/tests/build/LOCAL_HAS_CPP_negative_test/jni/foo.c
@@ -0,0 +1,11 @@
+// https://github.com/android-ndk/ndk/issues/205
+// This test is verifying that LOCAL_HAS_CPP defaults to off.
+//
+// To test that this is working, we define an extern for `std::terminate` and
+// call it in a C file. Without `LOCAL_HAS_CPP := true`, this module would fail
+// to link because it wouldn't be able to find `std::terminate`. This test is
+// configured to expect build failure.
+extern void _ZSt9terminatev();
+void terminate() {
+  _ZSt9terminatev();
+}
diff --git a/tests/build/LOCAL_HAS_CPP_negative_test/test_config.py b/tests/build/LOCAL_HAS_CPP_negative_test/test_config.py
new file mode 100644
index 0000000..43ec63b
--- /dev/null
+++ b/tests/build/LOCAL_HAS_CPP_negative_test/test_config.py
@@ -0,0 +1,2 @@
+def is_negative_test():
+    return True
diff --git a/tests/build/NDK_ANALYZE/project/jni/Android.mk b/tests/build/NDK_ANALYZE/project/jni/Android.mk
new file mode 100644
index 0000000..365bbad
--- /dev/null
+++ b/tests/build/NDK_ANALYZE/project/jni/Android.mk
@@ -0,0 +1,6 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := foo
+LOCAL_SRC_FILES := foo.cpp
+include $(BUILD_SHARED_LIBRARY)
diff --git a/tests/build/NDK_ANALYZE/project/jni/foo.cpp b/tests/build/NDK_ANALYZE/project/jni/foo.cpp
new file mode 100644
index 0000000..85e6cd8
--- /dev/null
+++ b/tests/build/NDK_ANALYZE/project/jni/foo.cpp
@@ -0,0 +1 @@
+void foo() {}
diff --git a/tests/build/NDK_ANALYZE/test.py b/tests/build/NDK_ANALYZE/test.py
new file mode 100644
index 0000000..3c8cf14
--- /dev/null
+++ b/tests/build/NDK_ANALYZE/test.py
@@ -0,0 +1,37 @@
+#
+# Copyright (C) 2016 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.
+#
+import os
+import subprocess
+
+
+def run_test(abi=None, platform=None, toolchain=None,
+             build_flags=None):
+    """Runs the static analyzer on a sample project."""
+    if build_flags is None:
+        build_flags = []
+
+    ndk_dir = os.environ['NDK']
+    ndk_build = os.path.join(ndk_dir, 'ndk-build')
+    project_path = 'project'
+    ndk_args = build_flags + [
+        'APP_ABI=' + abi,
+        'APP_PLATFORM=android-{}'.format(platform),
+        'NDK_ANALYZE=1',
+    ]
+    proc = subprocess.Popen([ndk_build, '-C', project_path] + ndk_args,
+                            stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+    out, _ = proc.communicate()
+    return proc.returncode == 0, out
diff --git a/tests/build/NDK_ANALYZE/test_config.py b/tests/build/NDK_ANALYZE/test_config.py
new file mode 100644
index 0000000..8ea0127
--- /dev/null
+++ b/tests/build/NDK_ANALYZE/test_config.py
@@ -0,0 +1,10 @@
+from __future__ import absolute_import
+import sys
+
+
+def build_unsupported(_abi, _api, toolchain):
+    if sys.platform == 'win32':
+        return sys.platform
+    if toolchain != 'clang':
+        return toolchain
+    return None
diff --git a/tests/build/build-assembly-file/CMakeLists.txt b/tests/build/build-assembly-file/CMakeLists.txt
new file mode 100644
index 0000000..bb5f554
--- /dev/null
+++ b/tests/build/build-assembly-file/CMakeLists.txt
@@ -0,0 +1,15 @@
+cmake_minimum_required(VERSION 3.6)
+
+enable_language(ASM)
+
+if(CMAKE_SYSTEM_PROCESSOR STREQUAL armv7-a)
+  set(TEST_SOURCES jni/assembly1.s jni/assembly2.S)
+elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL i686)
+  set(TEST_SOURCES jni/assembly-x86.S)
+elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL mips)
+  set(TEST_SOURCES jni/assembly-mips.S)
+endif()
+
+add_library(test_build_assembly SHARED ${TEST_SOURCES})
+# Without C or C++ files, CMake doesn't know which linker to use.
+set_target_properties(test_build_assembly PROPERTIES LINKER_LANGUAGE C)
diff --git a/tests/build/issue17144-byteswap/test_config.py b/tests/build/issue17144-byteswap/test_config.py
index ae070f2..81008f0 100644
--- a/tests/build/issue17144-byteswap/test_config.py
+++ b/tests/build/issue17144-byteswap/test_config.py
@@ -1,6 +1,4 @@
 def build_broken(abi, platform, toolchain):
     if toolchain == 'clang' and abi.startswith('armeabi-v7a'):
         return '{} {}'.format(toolchain, abi), 'http://b/26091410'
-    if toolchain == 'clang' and abi == 'mips':
-        return '{} {}'.format(toolchain, abi), 'https://github.com/android-ndk/ndk/issues/159'
     return None, None
diff --git a/tests/build/libcxx-cxa_bad_cast/jni/Android.mk b/tests/build/libcxx-cxa_bad_cast/jni/Android.mk
new file mode 100644
index 0000000..25cb7ac
--- /dev/null
+++ b/tests/build/libcxx-cxa_bad_cast/jni/Android.mk
@@ -0,0 +1,7 @@
+LOCAL_PATH := $(call my-dir)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := foo
+LOCAL_SRC_FILES := foo.cpp
+LOCAL_CPPFLAGS := -fexceptions -frtti
+include $(BUILD_EXECUTABLE)
diff --git a/tests/build/libcxx-cxa_bad_cast/jni/Application.mk b/tests/build/libcxx-cxa_bad_cast/jni/Application.mk
new file mode 100644
index 0000000..3b7baf1
--- /dev/null
+++ b/tests/build/libcxx-cxa_bad_cast/jni/Application.mk
@@ -0,0 +1 @@
+APP_STL := c++_shared
diff --git a/tests/build/libcxx-cxa_bad_cast/jni/foo.cpp b/tests/build/libcxx-cxa_bad_cast/jni/foo.cpp
new file mode 100644
index 0000000..5dcbb61
--- /dev/null
+++ b/tests/build/libcxx-cxa_bad_cast/jni/foo.cpp
@@ -0,0 +1,18 @@
+struct Foo {
+  virtual ~Foo() {}
+};
+
+struct Bar {
+  virtual ~Bar() {}
+};
+
+int main(int argc, char** argv) {
+  Foo f;
+
+  try {
+    Bar& b = dynamic_cast<Bar&>(f);
+  } catch (...) {
+  }
+
+  return 0;
+}
diff --git a/tests/build/test-vulkan-layers/test_config.py b/tests/build/test-vulkan-layers/test_config.py
index 4e47d5d..ec3da21 100644
--- a/tests/build/test-vulkan-layers/test_config.py
+++ b/tests/build/test-vulkan-layers/test_config.py
@@ -13,4 +13,6 @@
 def build_broken(abi, platform, toolchain):
     if toolchain == '4.9':
         return toolchain, 'http://b/31021045'
+    elif toolchain == 'clang' and abi == 'armeabi-v7a':
+        return toolchain, 'http://b/32255384'
     return None, None
diff --git a/tests/device/fenv/jni/test_fenv.c b/tests/device/fenv/jni/test_fenv.c
index cb545e0..7076468 100644
--- a/tests/device/fenv/jni/test_fenv.c
+++ b/tests/device/fenv/jni/test_fenv.c
@@ -14,6 +14,9 @@
  * limitations under the License.
  */
 
+// For isnanf.
+#define _BSD_SOURCE
+
 #include <stdio.h>
 #include <stdlib.h>
 #include <assert.h>
diff --git a/tests/device/math/jni/math.c b/tests/device/math/jni/math.c
index c9bd16a..e7901dd 100644
--- a/tests/device/math/jni/math.c
+++ b/tests/device/math/jni/math.c
@@ -13,6 +13,12 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
+// C++ implies _GNU_SOURCE for clang++ and g++.
+#if !defined(__cplusplus)
+#define _GNU_SOURCE
+#endif
+
 #include <android/api-level.h>
 #include <features.h>
 #include <math.h>