Merge "Revert "Change linker config variable: VNDK_VER""
diff --git a/benchmarks/Android.bp b/benchmarks/Android.bp
index 70f7bab..a7be965 100644
--- a/benchmarks/Android.bp
+++ b/benchmarks/Android.bp
@@ -29,6 +29,7 @@
         "bionic_benchmarks.cpp",
         "atomic_benchmark.cpp",
         "ctype_benchmark.cpp",
+        "dlfcn_benchmark.cpp",
         "get_heap_size_benchmark.cpp",
         "inttypes_benchmark.cpp",
         "malloc_benchmark.cpp",
diff --git a/benchmarks/dlfcn_benchmark.cpp b/benchmarks/dlfcn_benchmark.cpp
new file mode 100644
index 0000000..6a2bb57
--- /dev/null
+++ b/benchmarks/dlfcn_benchmark.cpp
@@ -0,0 +1,39 @@
+/*
+ * Copyright (C) 2019 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 <android-base/strings.h>
+#include <benchmark/benchmark.h>
+#include <dlfcn.h>
+
+#include "util.h"
+
+void local_function() {}
+
+template<typename F>
+int bm_dladdr(F fun) {
+    const void* addr = reinterpret_cast<void*>(fun);
+    Dl_info info;
+    int res = dladdr(addr, &info);
+    if (res == 0) abort();
+    if (info.dli_fname == nullptr) abort();
+
+    // needed for DoNotOptimize
+    return res;
+}
+BIONIC_TRIVIAL_BENCHMARK(BM_dladdr_libc_printf, bm_dladdr(printf));
+BIONIC_TRIVIAL_BENCHMARK(BM_dladdr_libdl_dladdr, bm_dladdr(dladdr));
+BIONIC_TRIVIAL_BENCHMARK(BM_dladdr_local_function, bm_dladdr(local_function));
+BIONIC_TRIVIAL_BENCHMARK(BM_dladdr_libbase_split, bm_dladdr(android::base::Split));
diff --git a/docs/defines.md b/docs/defines.md
new file mode 100644
index 0000000..4775cd2
--- /dev/null
+++ b/docs/defines.md
@@ -0,0 +1,66 @@
+# When to use which `#define`
+
+Using `#ifdef` or equivalents is common when writing portable code. Which to use
+when can be quite tricky. This document describes the most common choices
+related to Android.
+
+## `__BIONIC__`
+
+If your code is specific to Android's C library, bionic, use `__BIONIC__`. This
+is typically a good choice when you use libc API that's only in bionic, such as
+the system property functions. Common alternatives on this dimension are
+`__GLIBC__`, `__APPLE__`, or `_WIN32`. Note that although bionic is most often
+seen on Android devices, it is possible to use bionic on the host too.
+
+## `__ANDROID__`
+
+If your code is specific to Android devices, use `__ANDROID__`. This isn't
+useful as you might think, and one of the other choices on this page is usually
+more appropriate. This is typically a good choice if you have code that's part
+of the OS and needs to behave differently on the host than on the device.
+Genuine cases are quite rare, and `__BIONIC__` is often more specific (but
+remember that it is possible -- if unusual -- to use bionic on the host).
+
+## `__ANDROID_API__`
+
+If your code can be built targeting a variety of different OS versions, use
+`__ANDROID_API__` to test which version you're building against. This is
+typically useful if you can use new NDK APIs when available, but don't require
+them if not.
+
+One thing to note (if your code may also be built as part of the OS itself) is
+that for most of the year, the OS builds with this set to 10,000 rather than the
+obvious "next" API level such as 19. Once the API level has been decided, the
+value of `__ANDROID_API__` drops to that number.
+
+## `__linux__`
+
+If your code requires a Linux kernel, use `__linux__`. This is typically a good
+choice when you use Linux-specific API, such as a Linux-specific system call or
+a file in `/proc`, but aren't restricted to just Android and would work equally
+well on a desktop Linux distro, say. Common alternatives on this dimension
+are `__APPLE__` or `_WIN32`.
+
+## `__ANDROID_NDK__`
+
+If your code can be built either as part of an app _or_ as part of the OS
+itself, use `__ANDROID_NDK__` to differentiate between those two circumstances.
+This is typically a good choice when your code uses non-NDK API if it's built as
+part of the OS, but sticks to just the NDK APIs otherwise.
+
+## `__NDK_MAJOR__`, `__NDK_MINOR__`, `__NDK_BETA__`, `__NDK_BUILD__`, `__NDK_CANARY__`
+
+If your code can be built with a variety of different NDK versions, and needs to
+work around issues with some of them, use these macros to detect the versinon of
+the NDK you're being built with. Usually only `__NDK_MAJOR__` will be necessary.
+
+## `__arm__`, `__aarch64__`, `__i386__`, `__x86_64__`
+
+If your code is specific to a particular processor architecture, use these
+macros to conditionally compile. Note that the ABI usually called `arm64` uses
+the macro `__aarch64__` and the ABI usually called `x86` uses `__i386__`.
+
+## `__LP32__` and `__LP64__`
+
+If your code depends on "bitness" -- whether `long` and pointers are 32- or
+64-bit -- use these macros to conditionally compile.
diff --git a/libc/Android.bp b/libc/Android.bp
index 37e0f09..3e2ee1d 100644
--- a/libc/Android.bp
+++ b/libc/Android.bp
@@ -1525,6 +1525,22 @@
     ],
 }
 
+// Versions of dl_iterate_phdr and similar APIs used to lookup unwinding information in a static
+// executable.
+cc_library_static {
+    name: "libc_unwind_static",
+    defaults: ["libc_defaults"],
+    cflags: ["-DLIBC_STATIC"],
+
+    srcs: ["bionic/dl_iterate_phdr_static.cpp"],
+    arch: {
+        // arm32-specific dl_unwind_find_exidx and __gnu_Unwind_Find_exidx APIs
+        arm: {
+            srcs: ["arch-arm/bionic/exidx_static.c"],
+        },
+    },
+}
+
 // ========================================================
 // libc_nomalloc.a
 // ========================================================
@@ -1537,20 +1553,13 @@
 
 cc_library_static {
     name: "libc_nomalloc",
-
     defaults: ["libc_defaults"],
-
-    arch: {
-        arm: {
-            srcs: ["arch-arm/bionic/exidx_static.c"],
-        },
-    },
-
     cflags: ["-DLIBC_STATIC"],
 
     whole_static_libs: [
         "libc_common_static",
         "libc_init_static",
+        "libc_unwind_static",
     ],
 }
 
@@ -1572,7 +1581,6 @@
 filegroup {
     name: "libc_sources_static",
     srcs: [
-        "bionic/dl_iterate_phdr_static.cpp",
         "bionic/malloc_common.cpp",
         "bionic/malloc_limit.cpp",
     ],
@@ -1586,11 +1594,6 @@
     ],
 }
 
-filegroup {
-    name: "libc_sources_static_arm",
-    srcs: [ "arch-arm/bionic/exidx_static.c" ],
-}
-
 // ========================================================
 // libc.a + libc.so
 // ========================================================
@@ -1613,6 +1616,7 @@
         whole_static_libs: [
             "libc_init_static",
             "libc_common_static",
+            "libc_unwind_static",
         ],
     },
     shared: {
@@ -1662,9 +1666,6 @@
                 // special for arm
                 cflags: ["-DCRT_LEGACY_WORKAROUND"],
             },
-            static: {
-                srcs: [":libc_sources_static_arm"],
-            },
 
             // Arm 32 bit does not produce complete exidx unwind information
             // so keep the .debug_frame which is relatively small and does
diff --git a/libc/arch-arm/bionic/exidx_static.c b/libc/arch-arm/bionic/exidx_static.c
index ef3745f..9830c54 100644
--- a/libc/arch-arm/bionic/exidx_static.c
+++ b/libc/arch-arm/bionic/exidx_static.c
@@ -43,7 +43,11 @@
 extern struct exidx_entry __exidx_end;
 extern struct exidx_entry __exidx_start;
 
-_Unwind_Ptr __gnu_Unwind_Find_exidx(_Unwind_Ptr pc __attribute__((unused)), int* pcount) {
+_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr pc __attribute__((unused)), int* pcount) {
   *pcount = (&__exidx_end - &__exidx_start);
   return (_Unwind_Ptr)&__exidx_start;
 }
+
+_Unwind_Ptr __gnu_Unwind_Find_exidx(_Unwind_Ptr pc, int *pcount) {
+  return dl_unwind_find_exidx(pc, pcount);
+}
diff --git a/libc/include/android/api-level.h b/libc/include/android/api-level.h
index 4a3d052..577fb00 100644
--- a/libc/include/android/api-level.h
+++ b/libc/include/android/api-level.h
@@ -31,6 +31,9 @@
 /**
  * @file android/api-level.h
  * @brief Functions and constants for dealing with multiple API levels.
+ *
+ * See
+ * https://android.googlesource.com/platform/bionic/+/master/docs/defines.md.
  */
 
 #include <sys/cdefs.h>
@@ -38,9 +41,9 @@
 __BEGIN_DECLS
 
 /**
- * Magic version number for an Android OS build which has
- * not yet turned into an official release,
- * for comparison against `__ANDROID_API__`.
+ * Magic version number for an Android OS build which has not yet turned
+ * into an official release, for comparison against `__ANDROID_API__`. See
+ * https://android.googlesource.com/platform/bionic/+/master/docs/defines.md.
  */
 #define __ANDROID_API_FUTURE__ 10000
 
@@ -49,27 +52,12 @@
 /**
  * `__ANDROID_API__` is the API level being targeted. For the OS,
  * this is `__ANDROID_API_FUTURE__`. For the NDK, this is set by the
- * compiler system based on the API level you claimed to target.
+ * compiler system based on the API level you claimed to target. See
+ * https://android.googlesource.com/platform/bionic/+/master/docs/defines.md.
  */
 #define __ANDROID_API__ __ANDROID_API_FUTURE__
 #endif
 
-#if __ANDROID_API__ != __ANDROID_API_FUTURE__
-/**
- * `__ANDROID_NDK__` is defined for code that's built by the NDK
- * rather than as part of the OS. "Built by the NDK" is an ambiguous idea,
- * so you might prefer to check `__ANDROID__`, `__BIONIC__`, `__linux__`,
- * or `__NDK_MAJOR__` instead, depending on exactly what you're trying to say.
- *
- * `__ANDROID_NDK__` is intended to capture "this code is being built for
- * Android, but targeting a specific API level". This is true for all code built
- * by the NDK proper, but also for OS code that sets `sdk_version` in its build
- * file. This distinction might matter to you if, for example, your code could
- * be built as part of an app *or* as part of the OS.
- */
-#define __ANDROID_NDK__ 1
-#endif
-
 /** Names the Gingerbread API level (9), for comparison against `__ANDROID_API__`. */
 #define __ANDROID_API_G__ 9
 
diff --git a/libc/include/sys/cdefs.h b/libc/include/sys/cdefs.h
index b061c22..8078bda 100644
--- a/libc/include/sys/cdefs.h
+++ b/libc/include/sys/cdefs.h
@@ -36,6 +36,10 @@
 
 #pragma once
 
+/**
+ * `__BIONIC__` is always defined if you're building with bionic. See
+ * https://android.googlesource.com/platform/bionic/+/master/docs/defines.md.
+ */
 #define __BIONIC__ 1
 
 #if defined(__cplusplus)
diff --git a/libc/malloc_debug/Android.bp b/libc/malloc_debug/Android.bp
index ce80a97..7340f95 100644
--- a/libc/malloc_debug/Android.bp
+++ b/libc/malloc_debug/Android.bp
@@ -109,9 +109,13 @@
     ],
 
     apex_available: [
-        "//apex_available:platform",
         "com.android.runtime",
     ],
+    static: {
+        apex_available: [
+            "//apex_available:platform",
+        ],
+    },
 }
 
 // ==============================================================
diff --git a/libc/malloc_hooks/Android.bp b/libc/malloc_hooks/Android.bp
index a0f8102..861c371 100644
--- a/libc/malloc_hooks/Android.bp
+++ b/libc/malloc_hooks/Android.bp
@@ -32,6 +32,15 @@
         "-Werror",
         "-fno-stack-protector",
     ],
+
+    apex_available: [
+        "com.android.runtime",
+    ],
+    static: {
+        apex_available: [
+            "//apex_available:platform",
+        ],
+    },
 }
 
 // ==============================================================
diff --git a/libdl/libdl_static.cpp b/libdl/libdl_static.cpp
index 0a36e6f..3bbf963 100644
--- a/libdl/libdl_static.cpp
+++ b/libdl/libdl_static.cpp
@@ -41,9 +41,3 @@
 int dlclose(void* /*handle*/) {
   return -1;
 }
-
-#if defined(__arm__)
-_Unwind_Ptr dl_unwind_find_exidx(_Unwind_Ptr /*pc*/, int* /*pcount*/) {
-  return 0;
-}
-#endif
diff --git a/linker/Android.bp b/linker/Android.bp
index 18f2527..bb9d26d 100644
--- a/linker/Android.bp
+++ b/linker/Android.bp
@@ -96,7 +96,6 @@
     name: "linker_sources_arm",
     srcs: [
         "arch/arm/begin.S",
-        "linker_exidx_static.c",
     ],
 }
 
@@ -233,6 +232,7 @@
         arm: {
             srcs: [ ":linker_sources_arm" ],
             version_script: ":linker_version_script_arm",
+            static_libs: ["libunwind_llvm"],
         },
         arm64: {
             srcs: [":linker_sources_arm64"],
@@ -276,6 +276,17 @@
         "liblinker_malloc",
     ],
 
+    // Ensure that if the linker needs __gnu_Unwind_Find_exidx, then the linker will have a
+    // definition of the symbol. The linker links against libgcc.a, whose arm32 unwinder has a weak
+    // reference to __gnu_Unwind_Find_exidx, which isn't sufficient to pull in the strong definition
+    // of __gnu_Unwind_Find_exidx from libc. An unresolved weak reference would create a
+    // non-relative dynamic relocation in the linker binary, which complicates linker startup.
+    //
+    // This line should be unnecessary because the linker's dependency on libunwind_llvm.a should
+    // override libgcc.a, but this line provides a simpler guarantee. It can be removed once the
+    // linker stops linking against libgcc.a's arm32 unwinder.
+    whole_static_libs: ["libc_unwind_static"],
+
     name: "linker",
     symlinks: ["linker_asan"],
     recovery_available: true,
diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp
index 18301e0..228e30a 100644
--- a/linker/dlfcn.cpp
+++ b/linker/dlfcn.cpp
@@ -31,6 +31,7 @@
 #include "linker_globals.h"
 #include "linker_dlwarning.h"
 
+#include <link.h>
 #include <pthread.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -193,11 +194,6 @@
   return do_dl_iterate_phdr(cb, data);
 }
 
-// This function is needed by libgcc.a
-int dl_iterate_phdr(int (*cb)(dl_phdr_info* info, size_t size, void* data), void* data) {
-  return __loader_dl_iterate_phdr(cb, data);
-}
-
 #if defined(__arm__)
 _Unwind_Ptr __loader_dl_unwind_find_exidx(_Unwind_Ptr pc, int* pcount) {
   ScopedPthreadMutexLocker locker(&g_dl_mutex);
diff --git a/linker/linker_exidx_static.c b/linker/linker_exidx_static.c
deleted file mode 100644
index b38ef17..0000000
--- a/linker/linker_exidx_static.c
+++ /dev/null
@@ -1,46 +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.
- */
-
-#include <link.h>
-
-/* Find the .ARM.exidx section (which in the case of a static executable
- * can be identified through its start and end symbols), and return its
- * beginning and numbe of entries to the caller.  Note that for static
- * executables we do not need to use the value of the PC to find the
- * EXIDX section.
- */
-
-extern unsigned __exidx_end;
-extern unsigned __exidx_start;
-
-_Unwind_Ptr __gnu_Unwind_Find_exidx(_Unwind_Ptr pc __unused,
-                                    int* pcount)
-{
-  *pcount = (__exidx_end-__exidx_start)/8;
-  return __exidx_start;
-}
diff --git a/tests/dlext_test.cpp b/tests/dlext_test.cpp
index e7274f7..e98d66f 100644
--- a/tests/dlext_test.cpp
+++ b/tests/dlext_test.cpp
@@ -600,7 +600,7 @@
 void GetPss(bool shared_relro, const char* lib, const char* relro_file, pid_t pid,
             size_t* total_pss) {
   android::meminfo::ProcMemInfo proc_mem(pid);
-  const std::vector<android::meminfo::Vma>& maps = proc_mem.Maps();
+  const std::vector<android::meminfo::Vma>& maps = proc_mem.MapsWithoutUsageStats();
   ASSERT_GT(maps.size(), 0UL);
 
   // Calculate total PSS of the library.
@@ -612,7 +612,9 @@
           saw_relro_file = true;
       }
 
-      *total_pss += vma.usage.pss;
+      android::meminfo::Vma update_vma(vma);
+      ASSERT_TRUE(proc_mem.FillInVmaStats(update_vma));
+      *total_pss += update_vma.usage.pss;
     }
   }