Repository: bazelbuild/bazel
Issue: Support NDK r19
Labels: type: feature request
P1
team-Android

Expected release: Q4 2018

Changes: https://android.googlesource.com/platform/ndk/+/master/docs/Roadmap.md#ndk-r19


* Make all toolchains be standalone toolchains

> Now that the NDK is down to a single compiler and STL, if we just taught the Clang driver to emit -D__ANDROID_API__=foo and to link libc.so.18 instead of libc.so, standalone toolchains would be obsolete because the compiler would already be a standalone toolchain. The NDK toolchain would Just Work regardless of build system, and the logic contained in each build system could be greatly reduced.

> Related to this (but maybe occurring in a later release), we'll want to switch from libgcc to libcompiler-rt and our own unwinder.

> See the corresponding bug make all toolchains standalone toolchains for detailed discussion of the implementation and sub-tasks.

Issue comments:
r19 beta 2 is available, r19 is expected to ship soon.

https://developer.android.com/ndk/downloads/
NDK 19 has dropped: https://developer.android.com/ndk/downloads/#stable-downloads
Link to changelog: https://github.com/android-ndk/ndk/wiki/Changelog-r19
After speaking with @hlopko, the right way forward here is to implement the NDK CROSSTOOL in Starlark. This isn't a necessary blocker for NDK 19, since we can adapt the NDK 18 configuration for 19, but it would be nice to turn down proto CROSSTOOL generation to move to the modern approach.

@hlopko's suggestion:

> write a rule ndk_cc_toolchain_config that has attributes for things that are different between versions, and only instantiate that in BUILD files.

More information: 

- https://github.com/bazelbuild/bazel/issues/7320
- https://docs.bazel.build/versions/master/cc-toolchain-config-reference.html

@jin do you plan on supporting `lld` too ?
@steeve definitely. We want the Android rules to be 100% compatible with the recommended set of tools in the NDK.
The NDK CROSSTOOL has been ported to Starlark with massive help from @hlopko - thanks!

Going through the [changelog](https://github.com/android-ndk/ndk/wiki/Changelog-r19):

> # Announcements

> Developers should begin testing their apps with LLD. AOSP has switched to using LLD by default and the NDK will use it by default in the next release. BFD and Gold will be removed once LLD has been through a release cycle with no major unresolved issues (estimated r21). Test LLD in your app by passing -fuse-ld=lld when linking.
 
> Note: lld does not currently support compressed symbols on Windows. See Issue 888. Clang also cannot generate compressed symbols on Windows, but this can be a problem when using artifacts built from Darwin or Linux.

We will need to add support for this.

> The Play Store will require 64-bit support when uploading an APK beginning in August 2019. Start porting now to avoid surprises when the time comes. For more information, see this blog post.

We may want to add a warning message about this when building for non-64-bit.

> Issue 780: Standalone toolchains are now unnecessary. Clang, binutils, the sysroot, and other toolchain pieces are now all installed to $NDK/toolchains/llvm/prebuilt/<host-tag> and Clang will automatically find them. Instead of creating a standalone toolchain for API 26 ARM, instead invoke the compiler directly from the NDK:
> 
> $ $NDK/toolchains/llvm/prebuilt/<host-tag>/bin/armv7a-linux-androideabi26-clang++ src.cpp
> For r19 the toolchain is also installed to the old path to give build systems a chance to adapt to the new layout. The old paths will be removed in r20.

We must definitely support this, but the effects of it should be transparent to end users. It's not clear what the impact of having a standalone toolchain will be on the Starlark crosstool configuration.
 
> The make_standalone_toolchain.py script will not be removed. It is now unnecessary and will emit a warning with the above information, but the script will remain to preserve existing workflows.

Not applicable, we don't use this.

> If you're using ndk-build, CMake, or a standalone toolchain, there should be no change to your workflow. This change is meaningful for maintainers of third-party build systems, who should now be able to delete some Android-specific code. For more information, see the Build System Maintainers guide.

More reading: https://android.googlesource.com/platform/ndk/+/ndk-release-r19/docs/BuildSystemMaintainers.md

> ndk-depends has been removed. We believe that ReLinker is a better solution to native library loading issues on old Android versions.

Not applicable, we don't use this.

> Issue 862: The GCC wrapper scripts which redirected to Clang have been removed, as they are not functional enough to be drop in replacements.

This should be addressed by the standalone toolchain support.

---

> r19c
> ----
> 
>  * [Issue 912]: Prevent the CMake toolchain file from clobbering a user
>    specified `CMAKE_FIND_ROOT_PATH`.
>  * [Issue 920]: Fix clang wrapper scripts on Windows.
> 
> [Issue 912]: https://github.com/android-ndk/ndk/issues/912
> [Issue 920]: https://github.com/android-ndk/ndk/issues/920
> 
> r19b
> ----
> 
>  * [Issue 855]: ndk-build automatically disables multithreaded linking for LLD
>    on Windows, where it may hang. It is not possible for the NDK to detect this
>    situation for CMake, so CMake users and custom build systems must pass
>    `-Wl,--no-threads` when linking with LLD on Windows.

We'll need to take note of this for the `lld` support.

>  * [Issue 849]: Fixed unused command line argument warning when using standalone
>    toolchains to compile C code.
>  * [Issue 890]: Fixed `CMAKE_FIND_ROOT_PATH`. CMake projects will no longer
>    search the host's sysroot for headers and libraries.
>  * [Issue 906]: Explicitly set `-march=armv7-a` for 32-bit ARM to workaround
>    Clang not setting that flag automatically when using `-fno-integrated-as`.
>    This fix only affects ndk-build and CMake. Standalone toolchains and custom
>    build systems will need to apply this fix themselves.
>  * [Issue 907]: Fixed `find_path` for NDK headers in CMake.
> 
> [Issue 849]: https://github.com/android-ndk/ndk/issues/849
> [Issue 890]: https://github.com/android-ndk/ndk/issues/890
> [Issue 907]: https://github.com/android-ndk/ndk/issues/907
> 
> Changes
> -------
> 
>  * Updated Clang to r339409.
>      * C++ compilation now defaults to C++14.

Need to update default std to `-std=c++14`.

>  * [Issue 780]: A complete NDK toolchain is now installed to the Clang
>    directory. See the announcements section for more information.
>  * ndk-build no longer removes artifacts from `NDK_LIBS_OUT` for ABIs not
>    present in `APP_ABI`. This enables workflows like the following:
> 
>    ```bash
>    for abi in armeabi-v7a arm64-v8a x86 x86_64; do
>        ndk-build APP_ABI=$abi
>    done
>    ```
> 
>    Prior to this change, the above workflow would remove the previously built
>    ABI's artifacts on each successive build, resulting in only x86_64 being
>    present at the end of the loop.
>  * ndk-stack has been rewritten in Python.
>  * [Issue 776]: To better support LLD, ndk-build and CMake no longer pass
>    `-Wl,--fix-cortex-a8` by default.
>      * CPUs that require this fix are uncommon in the NDK's supported API range
>        (16+).
>      * If you need to continue supporting these devices, add
>        `-Wl,--fix-cortex-a8` to your `APP_LDFLAGS` or `CMAKE_C_FLAGS`, but note
>        that LLD will not be adding support for this workaround.
>      * Alternatively, use the Play Console to [blacklist] Cortex-A8 CPUs to
>        disallow your app from being installed on those devices.

Our ARM crosstool add this `--fix-cortex-a8` linker flag, so we should drop them here.

```
src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r18/ArmCrosstools.java
149:        .addLinkerFlag("-Wl,--fix-cortex-a8")
```

>  * [Issue 798]: The ndk-build and CMake options to disable RelRO and noexecstack
>    are now ignored. All code is built with RelRO and non-executable stacks.

Not sure how/if we do this, will need to investigate.

>  * [Issue 294]: All code is now built with a subset of [compiler-rt] to provide
>    a complete set of compiler built-ins for Clang.
> 
> [Issue 294]: https://github.com/android-ndk/ndk/issues/294
> [Issue 776]: https://github.com/android-ndk/ndk/issues/776
> [Issue 798]: https://github.com/android-ndk/ndk/issues/798
> [blacklist]: https://support.google.com/googleplay/android-developer/answer/7353455?hl=en
> [compiler-rt]: https://compiler-rt.llvm.org/
> 
> Known Issues
> ------------
> 
>  * This is not intended to be a comprehensive list of all outstanding bugs.
>  * [Issue 888]: lld does not support compressed symbols on Windows. Clang also
>    cannot generate compressed symbols on Windows, but this can be a problem when
>    using artifacts built from Darwin or Linux.
>  * [Issue 360]: `thread_local` variables with non-trivial destructors will cause
>    segfaults if the containing library is `dlclose`ed on devices running M or
>    newer, or devices before M when using a static STL. The simple workaround is
>    to not call `dlclose`.
>  * [Issue 70838247]: Gold emits broken debug information for AArch64. AArch64
>    still uses BFD by default.
>  * [Issue 855]: LLD may hang on Windows when using multithreaded linking.
>    ndk-build will automatically disable multithreaded linking in this situation,
>    but CMake users and custom build systems should pass `-Wl,--no-threads` when
>    using LLD on Windows. The other linkers and operating systems are unaffected.

Addressed above.

>  * [Issue 884]: Third-party build systems must pass `-fno-addrsig` to Clang for
>    compatibility with binutils. ndk-build, CMake, and standalone toolchains
>    handle this automatically.

Looks like standalone toolchains support this, but will be good to verify.

>  * [Issue 906]: Clang does not pass `-march=armv7-a` to the assembler when using
>    `-fno-integrated-as`. This results in the assembler generating ARMv5
>    instructions. Note that by default Clang uses the integrated assembler which
>    does not have this problem. To workaround this issue, explicitly use
>    `-march=armv7-a` when building for 32-bit ARM with the non-integrated
>    assembler, or use the integrated assembler. ndk-build and CMake already
>    contain these workarounds.

We'll need to add this workaround.

>  * This version of the NDK is incompatible with the Android Gradle plugin
>    version 3.0 or older. If you see an error like
>    `No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android`,
>    update your project file to [use plugin version 3.1 or newer]. You will also
>    need to upgrade to Android Studio 3.1 or newer.
> 
> [Issue 360]: https://github.com/android-ndk/ndk/issues/360
> [Issue 70838247]: https://issuetracker.google.com/70838247
> [Issue 855]: https://github.com/android-ndk/ndk/issues/855
> [Issue 884]: https://github.com/android-ndk/ndk/issues/884
> [Issue 888]: https://github.com/android-ndk/ndk/issues/888
> [Issue 906]: https://github.com/android-ndk/ndk/issues/906
> [use plugin version 3.1 or newer]: https://developer.android.com/studio/releases/gradle-plugin#updating-plugin



Addressed in https://github.com/bazelbuild/bazel/pull/8524

Pull request review comments:

Patch that resolved the issue:
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
index d595dfe5b340d2..ab4bd6e30dd20a 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/AndroidNdkCrosstools.java
@@ -23,6 +23,7 @@
 import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r15.NdkMajorRevisionR15;
 import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r17.NdkMajorRevisionR17;
 import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r18.NdkMajorRevisionR18;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19.NdkMajorRevisionR19;
 import com.google.devtools.build.lib.util.OS;
 import java.util.Map;
 
@@ -50,6 +51,7 @@ private AndroidNdkCrosstools() {}
           .put(16, new NdkMajorRevisionR15("5.0.300080")) // no changes relevant to Bazel
           .put(17, new NdkMajorRevisionR17("6.0.2"))
           .put(18, new NdkMajorRevisionR18("7.0.2"))
+          .put(19, new NdkMajorRevisionR19("8.0.1"))
           .build();
 
   public static final Map.Entry<Integer, NdkMajorRevision> LATEST_KNOWN_REVISION =
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java
new file mode 100644
index 00000000000000..5fc2c6945b1d83
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/AndroidNdkCrosstoolsR19.java
@@ -0,0 +1,78 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// 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.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CrosstoolRelease;
+import java.util.ArrayList;
+import java.util.List;
+
+/** Generates a CrosstoolRelease proto for the Android NDK. */
+final class AndroidNdkCrosstoolsR19 {
+
+  /**
+   * Creates a CrosstoolRelease proto for the Android NDK, given the API level to use and the
+   * release revision. The crosstools are generated through code rather than checked in as a flat
+   * file to reduce the amount of templating needed (for parameters like the release name and
+   * certain paths), to reduce duplication, and to make it easier to support future versions of the
+   * NDK. TODO(bazel-team): Eventually we should move this into Skylark so the crosstools can be
+   * updated independently of Bazel itself.
+   *
+   * @return A CrosstoolRelease for the Android NDK.
+   */
+  static CrosstoolRelease create(
+      NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform, String clangVersion) {
+    return CrosstoolRelease.newBuilder()
+        .setMajorVersion("android")
+        .setMinorVersion("")
+        .setDefaultTargetCpu("armeabi")
+        .addAllToolchain(createToolchains(ndkPaths, stlImpl, hostPlatform, clangVersion))
+        .build();
+  }
+
+  private static ImmutableList<CToolchain> createToolchains(
+      NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform, String clangVersion) {
+
+    List<CToolchain.Builder> toolchainBuilders = new ArrayList<>();
+    toolchainBuilders.addAll(new ArmCrosstools(ndkPaths, stlImpl, clangVersion).createCrosstools());
+    toolchainBuilders.addAll(new X86Crosstools(ndkPaths, stlImpl, clangVersion).createCrosstools());
+
+    ImmutableList.Builder<CToolchain> toolchains = new ImmutableList.Builder<>();
+
+    // Set attributes common to all toolchains.
+    for (CToolchain.Builder toolchainBuilder : toolchainBuilders) {
+      toolchainBuilder
+          .setHostSystemName(hostPlatform)
+          .setTargetLibc("local")
+          .setAbiVersion(toolchainBuilder.getTargetCpu())
+          .setAbiLibcVersion("local");
+
+      // builtin_sysroot is set individually on each toolchain.
+      // platforms/arch sysroot
+      toolchainBuilder.addCxxBuiltinIncludeDirectory("%sysroot%/usr/include");
+      toolchainBuilder.addCxxBuiltinIncludeDirectory(
+          ndkPaths.createBuiltinSysroot() + "/usr/include");
+      toolchainBuilder.addUnfilteredCxxFlag(
+          "-isystem%ndk%/usr/include".replace("%ndk%", ndkPaths.createBuiltinSysroot()));
+
+      toolchains.add(toolchainBuilder.build());
+    }
+
+    return toolchains.build();
+  }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java
new file mode 100644
index 00000000000000..cdcee9caba93a1
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ApiLevelR19.java
@@ -0,0 +1,61 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// 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.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableListMultimap;
+import com.google.common.collect.ImmutableMap;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.ApiLevel;
+import com.google.devtools.build.lib.events.EventHandler;
+
+/** Class which encodes information from the Android NDK makefiles about API levels. */
+final class ApiLevelR19 extends ApiLevel {
+  /** This is the contents of {@code platforms/android-*} */
+  private static final ImmutableListMultimap<String, String> API_LEVEL_TO_ARCHITECTURES =
+      ImmutableListMultimap.<String, String>builder()
+          .putAll("16", "arm", "x86")
+          .putAll("17", "arm", "x86")
+          .putAll("18", "arm", "x86")
+          .putAll("19", "arm", "x86")
+          .putAll("21", "arm", "x86", "arm64", "x86_64")
+          .putAll("22", "arm", "x86", "arm64", "x86_64")
+          .putAll("23", "arm", "x86", "arm64", "x86_64")
+          .putAll("24", "arm", "x86", "arm64", "x86_64")
+          .putAll("26", "arm", "x86", "arm64", "x86_64")
+          .putAll("27", "arm", "x86", "arm64", "x86_64")
+          .putAll("28", "arm", "x86", "arm64", "x86_64")
+          .build();
+
+  /** This map fill in the gaps of {@code API_LEVEL_TO_ARCHITECTURES}. */
+  private static final ImmutableMap<String, String> API_EQUIVALENCIES =
+      ImmutableMap.<String, String>builder()
+          .put("16", "16")
+          .put("17", "16")
+          .put("18", "18")
+          .put("19", "19")
+          .put("20", "19")
+          .put("21", "21")
+          .put("22", "22")
+          .put("23", "23")
+          .put("24", "24")
+          .put("25", "24")
+          .put("26", "26")
+          .put("27", "27")
+          .put("28", "28")
+          .build();
+
+  ApiLevelR19(EventHandler eventHandler, String repositoryName, String apiLevel) {
+    super(API_LEVEL_TO_ARCHITECTURES, API_EQUIVALENCIES, eventHandler, repositoryName, apiLevel);
+  }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java
new file mode 100644
index 00000000000000..f88ee6672219fb
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/ArmCrosstools.java
@@ -0,0 +1,172 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// 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.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationMode;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationModeFlags;
+
+/**
+ * Crosstool definitions for ARM. These values are based on the setup.mk files in the Android NDK
+ * toolchain directories.
+ */
+final class ArmCrosstools {
+  private final NdkPaths ndkPaths;
+  private final StlImpl stlImpl;
+  private final String clangVersion;
+
+  ArmCrosstools(NdkPaths ndkPaths, StlImpl stlImpl, String clangVersion) {
+    this.ndkPaths = ndkPaths;
+    this.stlImpl = stlImpl;
+    this.clangVersion = clangVersion;
+  }
+
+  ImmutableList<CToolchain.Builder> createCrosstools() {
+    CToolchain.Builder aarch64Toolchain = createAarch64ClangToolchain();
+    CToolchain.Builder armeabiToolchain = createArmeabiClangToolchain();
+
+    stlImpl.addStlImpl(aarch64Toolchain, "4.9");
+    stlImpl.addStlImpl(armeabiToolchain, "4.9");
+
+    return ImmutableList.<CToolchain.Builder>builder()
+        .add(aarch64Toolchain)
+        .add(armeabiToolchain)
+        .build();
+  }
+
+  private CToolchain.Builder createAarch64ClangToolchain() {
+    String toolchainName = "aarch64-linux-android-4.9";
+    String targetPlatform = "aarch64-linux-android";
+    String gccToolchain = ndkPaths.createGccToolchainPath(toolchainName);
+    String llvmTriple = "aarch64-none-linux-android";
+
+    return CToolchain.newBuilder()
+        .setToolchainIdentifier("aarch64-linux-android-clang" + clangVersion)
+        .setTargetSystemName(targetPlatform)
+        .setTargetCpu("arm64-v8a")
+        .setCompiler("clang" + clangVersion)
+        .addAllToolPath(ndkPaths.createClangToolpaths(toolchainName, targetPlatform, null))
+        .addCxxBuiltinIncludeDirectory(
+            ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+        .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("arm64"))
+
+        // Compiler flags
+        .addCompilerFlag("-gcc-toolchain")
+        .addCompilerFlag(gccToolchain)
+        .addCompilerFlag("-target")
+        .addCompilerFlag(llvmTriple)
+        .addCompilerFlag("-ffunction-sections")
+        .addCompilerFlag("-funwind-tables")
+        .addCompilerFlag("-fstack-protector-strong")
+        .addCompilerFlag("-fpic")
+        .addCompilerFlag("-Wno-invalid-command-line-argument")
+        .addCompilerFlag("-Wno-unused-command-line-argument")
+        .addCompilerFlag("-no-canonical-prefixes")
+        .addCompilerFlag(
+            "-isystem%ndk%/usr/include/%triple%"
+                .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+                .replace("%triple%", targetPlatform))
+        .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel("arm"))
+
+        // Linker flags
+        .addLinkerFlag("-gcc-toolchain")
+        .addLinkerFlag(gccToolchain)
+        .addLinkerFlag("-target")
+        .addLinkerFlag(llvmTriple)
+        .addLinkerFlag("-no-canonical-prefixes")
+
+        // Additional release flags
+        .addCompilationModeFlags(
+            CompilationModeFlags.newBuilder()
+                .setMode(CompilationMode.OPT)
+                .addCompilerFlag("-O2")
+                .addCompilerFlag("-g")
+                .addCompilerFlag("-DNDEBUG"))
+
+        // Additional debug flags
+        .addCompilationModeFlags(
+            CompilationModeFlags.newBuilder()
+                .setMode(CompilationMode.DBG)
+                .addCompilerFlag("-O0")
+                .addCompilerFlag("-g")
+                .addCompilerFlag("-UNDEBUG"));
+  }
+
+  private CToolchain.Builder createArmeabiClangToolchain() {
+    String toolchainName = "arm-linux-androideabi-4.9";
+    String targetPlatform = "arm-linux-androideabi";
+    String gccToolchain = ndkPaths.createGccToolchainPath("arm-linux-androideabi-4.9");
+
+    return CToolchain.newBuilder()
+        .setToolchainIdentifier("arm-linux-androideabi-clang" + clangVersion + "-v7a")
+        .setTargetCpu("armeabi-v7a")
+        .setTargetSystemName("arm-linux-androideabi")
+        .setCompiler("clang" + clangVersion)
+        .addAllToolPath(ndkPaths.createClangToolpaths(toolchainName, targetPlatform, null))
+        .addCxxBuiltinIncludeDirectory(
+            ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+        .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("arm"))
+        .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel("arm"))
+        .addCompilerFlag(
+            "-isystem%ndk%/usr/include/%triple%"
+                .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+                .replace("%triple%", targetPlatform))
+
+        // Compiler flags
+        .addCompilerFlag("-target")
+        .addCompilerFlag("armv7-none-linux-androideabi") // LLVM_TRIPLE
+        .addCompilerFlag("-march=armv7-a")
+        .addCompilerFlag("-mfloat-abi=softfp")
+        .addCompilerFlag("-mfpu=vfpv3-d16")
+        .addCompilerFlag("-gcc-toolchain")
+        .addCompilerFlag(gccToolchain)
+        .addCompilerFlag("-fpic")
+        .addCompilerFlag("-ffunction-sections")
+        .addCompilerFlag("-funwind-tables")
+        .addCompilerFlag("-fstack-protector-strong")
+        .addCompilerFlag("-Wno-invalid-command-line-argument")
+        .addCompilerFlag("-Wno-unused-command-line-argument")
+        .addCompilerFlag("-no-canonical-prefixes")
+
+        // Linker flags
+        .addLinkerFlag("-target")
+        .addLinkerFlag("armv7-none-linux-androideabi") // LLVM_TRIPLE
+        .addLinkerFlag("-Wl,--fix-cortex-a8")
+        .addLinkerFlag("-gcc-toolchain")
+        .addLinkerFlag(gccToolchain)
+        .addLinkerFlag("-no-canonical-prefixes")
+
+        // Additional release flags
+        .addCompilationModeFlags(
+            CompilationModeFlags.newBuilder()
+                .setMode(CompilationMode.OPT)
+                .addCompilerFlag("-mthumb")
+                .addCompilerFlag("-Os")
+                .addCompilerFlag("-g")
+                .addCompilerFlag("-DNDEBUG"))
+
+        // Additional debug flags
+        .addCompilationModeFlags(
+            CompilationModeFlags.newBuilder()
+                .setMode(CompilationMode.DBG)
+                .addCompilerFlag("-g")
+                .addCompilerFlag("-fno-strict-aliasing")
+                .addCompilerFlag("-O0")
+                .addCompilerFlag("-UNDEBUG"));
+  }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java
new file mode 100644
index 00000000000000..067475d8391d7a
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/NdkMajorRevisionR19.java
@@ -0,0 +1,42 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// 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.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.ApiLevel;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkMajorRevision;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.events.EventHandler;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CrosstoolRelease;
+
+/** Logic specific to Android NDK R17. */
+public class NdkMajorRevisionR19 implements NdkMajorRevision {
+  private final String clangVersion;
+
+  public NdkMajorRevisionR19(String clangVersion) {
+    this.clangVersion = clangVersion;
+  }
+
+  @Override
+  public CrosstoolRelease crosstoolRelease(
+      NdkPaths ndkPaths, StlImpl stlImpl, String hostPlatform) {
+    return AndroidNdkCrosstoolsR19.create(ndkPaths, stlImpl, hostPlatform, clangVersion);
+  }
+
+  @Override
+  public ApiLevel apiLevel(EventHandler eventHandler, String name, String apiLevel) {
+    return new ApiLevelR19(eventHandler, name, apiLevel);
+  }
+}
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java
new file mode 100644
index 00000000000000..a3c24fe2276682
--- /dev/null
+++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/android/ndkcrosstools/r19/X86Crosstools.java
@@ -0,0 +1,118 @@
+// Copyright 2018 The Bazel Authors. All rights reserved.
+//
+// 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.
+
+package com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.r19;
+
+import com.google.common.collect.ImmutableList;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.NdkPaths;
+import com.google.devtools.build.lib.bazel.rules.android.ndkcrosstools.StlImpl;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CToolchain;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationMode;
+import com.google.devtools.build.lib.view.config.crosstool.CrosstoolConfig.CompilationModeFlags;
+
+/**
+ * Crosstool definitions for x86. These values are based on the setup.mk files in the Android NDK
+ * toolchain directories.
+ */
+final class X86Crosstools {
+  private final NdkPaths ndkPaths;
+  private final StlImpl stlImpl;
+  private final String clangVersion;
+
+  X86Crosstools(NdkPaths ndkPaths, StlImpl stlImpl, String clangVersion) {
+    this.ndkPaths = ndkPaths;
+    this.stlImpl = stlImpl;
+    this.clangVersion = clangVersion;
+  }
+
+  ImmutableList<CToolchain.Builder> createCrosstools() {
+    /** x86 */
+    // clang
+    CToolchain.Builder x86Clang =
+        createBaseX86ClangToolchain("x86", "i686", "i686-linux-android")
+            // Workaround for https://code.google.com/p/android/issues/detail?id=220159.
+            .addCompilerFlag("-mstackrealign")
+            .setToolchainIdentifier("x86-clang" + clangVersion)
+            .setTargetCpu("x86")
+            .addAllToolPath(ndkPaths.createClangToolpaths("x86-4.9", "i686-linux-android", null))
+            .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("x86"));
+
+    stlImpl.addStlImpl(x86Clang, null);
+
+    /** x86_64 */
+    CToolchain.Builder x8664Clang =
+        createBaseX86ClangToolchain("x86_64", "x86_64", "x86_64-linux-android")
+            .setToolchainIdentifier("x86_64-clang" + clangVersion)
+            .setTargetCpu("x86_64")
+            .addAllToolPath(
+                ndkPaths.createClangToolpaths("x86_64-4.9", "x86_64-linux-android", null))
+            .setBuiltinSysroot(ndkPaths.createBuiltinSysroot("x86_64"));
+
+    stlImpl.addStlImpl(x8664Clang, null);
+
+    return ImmutableList.of(x86Clang, x8664Clang);
+  }
+
+  private CToolchain.Builder createBaseX86ClangToolchain(
+      String x86Arch, String llvmArch, String triple) {
+    String gccToolchain = ndkPaths.createGccToolchainPath(x86Arch + "-4.9");
+    String llvmTriple = llvmArch + "-none-linux-android";
+
+    return CToolchain.newBuilder()
+        .setCompiler("clang" + clangVersion)
+        .addCxxBuiltinIncludeDirectory(
+            ndkPaths.createClangToolchainBuiltinIncludeDirectory(clangVersion))
+
+        // Compiler flags
+        .addCompilerFlag("-gcc-toolchain")
+        .addCompilerFlag(gccToolchain)
+        .addCompilerFlag("-target")
+        .addCompilerFlag(llvmTriple)
+        .addCompilerFlag("-ffunction-sections")
+        .addCompilerFlag("-funwind-tables")
+        .addCompilerFlag("-fstack-protector-strong")
+        .addCompilerFlag("-fPIC")
+        .addCompilerFlag("-Wno-invalid-command-line-argument")
+        .addCompilerFlag("-Wno-unused-command-line-argument")
+        .addCompilerFlag("-no-canonical-prefixes")
+        .addCompilerFlag(
+            "-isystem%ndk%/usr/include/%triple%"
+                .replace("%ndk%", ndkPaths.createBuiltinSysroot())
+                .replace("%triple%", triple))
+        .addCompilerFlag("-D__ANDROID_API__=" + ndkPaths.getCorrectedApiLevel(x86Arch))
+
+        // Linker flags
+        .addLinkerFlag("-gcc-toolchain")
+        .addLinkerFlag(gccToolchain)
+        .addLinkerFlag("-target")
+        .addLinkerFlag(llvmTriple)
+        .addLinkerFlag("-no-canonical-prefixes")
+
+        // Additional release flags
+        .addCompilationModeFlags(
+            CompilationModeFlags.newBuilder()
+                .setMode(CompilationMode.OPT)
+                .addCompilerFlag("-O2")
+                .addCompilerFlag("-g")
+                .addCompilerFlag("-DNDEBUG"))
+
+        // Additional debug flags
+        .addCompilationModeFlags(
+            CompilationModeFlags.newBuilder()
+                .setMode(CompilationMode.DBG)
+                .addCompilerFlag("-O0")
+                .addCompilerFlag("-g"))
+        .setTargetSystemName("x86-linux-android");
+  }
+}


Test patch:
diff --git a/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java b/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
index c75bad7eb217d4..5260e67ec454c1 100644
--- a/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
+++ b/src/test/java/com/google/devtools/build/lib/bazel/rules/android/AndroidNdkRepositoryTest.java
@@ -115,7 +115,7 @@ public void testInvalidNdkReleaseTxt() throws Exception {
         eventCollector,
         "The revision of the Android NDK referenced by android_ndk_repository rule 'androidndk' "
             + "could not be determined (the revision string found is 'not a valid release string')."
-            + " Bazel will attempt to treat the NDK as if it was r18.");
+            + " Bazel will attempt to treat the NDK as if it was r19.");
   }
 
   @Test
@@ -142,7 +142,7 @@ public void testInvalidNdkSourceProperties() throws Exception {
         eventCollector,
         "The revision of the Android NDK referenced by android_ndk_repository rule 'androidndk' "
             + "could not be determined (the revision string found is 'invalid package revision'). "
-            + "Bazel will attempt to treat the NDK as if it was r18.");
+            + "Bazel will attempt to treat the NDK as if it was r19.");
   }
 
   @Test
@@ -166,8 +166,8 @@ public void testUnsupportedNdkVersion() throws Exception {
         eventCollector,
         "The major revision of the Android NDK referenced by android_ndk_repository rule "
             + "'androidndk' is 19. The major revisions supported by Bazel are "
-            + "[10, 11, 12, 13, 14, 15, 16, 17, 18]. Bazel will attempt to treat the NDK as if it "
-            + "was r18.");
+            + "[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]. Bazel will attempt to treat the NDK as if "
+            + "it was r19.");
   }
 
   @Test
diff --git a/src/test/shell/bazel/android/android_ndk_integration_test.sh b/src/test/shell/bazel/android/android_ndk_integration_test.sh
index c8e85e7ee304a4..8c82626b5f701f 100755
--- a/src/test/shell/bazel/android/android_ndk_integration_test.sh
+++ b/src/test/shell/bazel/android/android_ndk_integration_test.sh
@@ -175,7 +175,7 @@ EOF
 
 function check_num_sos() {
   num_sos=$(unzip -Z1 bazel-bin/java/bazel/bin.apk '*.so' | wc -l | sed -e 's/[[:space:]]//g')
-  assert_equals "5" "$num_sos"
+  assert_equals "4" "$num_sos"
 }
 
 function check_soname() {
@@ -202,7 +202,7 @@ function test_android_binary() {
   setup_android_ndk_support
   create_android_binary
 
-  cpus="armeabi,armeabi-v7a,arm64-v8a,x86,x86_64"
+  cpus="armeabi-v7a,arm64-v8a,x86,x86_64"
 
   bazel build -s //java/bazel:bin --fat_apk_cpu="$cpus" || fail "build failed"
   check_num_sos
@@ -215,11 +215,11 @@ function test_android_binary_clang() {
   setup_android_ndk_support
   create_android_binary
 
-  cpus="armeabi,armeabi-v7a,arm64-v8a,x86,x86_64"
+  cpus="armeabi-v7a,arm64-v8a,x86,x86_64"
 
   bazel build -s //java/bazel:bin \
       --fat_apk_cpu="$cpus" \
-      --android_compiler=clang5.0.300080 \
+      --android_compiler=clang8.0.1 \
       || fail "build failed"
   check_num_sos
   check_soname
@@ -234,6 +234,7 @@ cc_binary(
     name = "foo",
     srcs = ["foo.cc"],
     copts = ["-mfpu=neon"],
+    linkopts = ["-ldl"],
 )
 EOF
   cat > foo.cc <<EOF
@@ -241,7 +242,7 @@ EOF
 int main() { return 0; }
 EOF
   bazel build //:foo \
-    --compiler=clang5.0.300080 \
+    --compiler=clang8.0.1 \
     --cpu=armeabi-v7a \
     --crosstool_top=//external:android/crosstool \
     --host_crosstool_top=@bazel_tools//tools/cpp:toolchain \
@@ -296,6 +297,7 @@ function test_stripped_cc_binary() {
 cc_binary(
     name = "foo",
     srcs = ["foo.cc"],
+    linkopts = ["-ldl"],
 )
 EOF
   cat > foo.cc <<EOF
@@ -308,7 +310,8 @@ EOF
     || fail "build failed"
 }
 
-function test_crosstool_stlport() {
+# stlport is no longer in the ndk
+function ignore_test_crosstool_stlport() {
   create_new_workspace
   setup_android_ndk_support
   cat > BUILD <<EOF
@@ -370,7 +373,8 @@ EOF
     --host_crosstool_top=@bazel_tools//tools/cpp:toolchain
 }
 
-function test_crosstool_gnu_libstdcpp() {
+# libstdcpp is no longer in the NDK
+function ignore_test_crosstool_gnu_libstdcpp() {
   create_new_workspace
   setup_android_ndk_support
   cat > BUILD <<EOF
@@ -406,7 +410,7 @@ function test_crosstool_libcpp_with_multiarch() {
   setup_android_ndk_support
   create_android_binary
 
-  cpus="armeabi,armeabi-v7a,arm64-v8a,x86,x86_64"
+  cpus="armeabi-v7a,arm64-v8a,x86,x86_64"
 
   assert_build //java/bazel:bin \
     --fat_apk_cpu="$cpus" \