Add __BIONIC_AVAILABILITY_GUARD().

Putting this behavior behind a macro so we can easily change it across
bionic if needed.

Bug: https://github.com/android/ndk/issues/2081
Test: None
Change-Id: Ia08b54a61b5b06f6fa4646f036ef1e788d7c3ece
diff --git a/libc/include/android/versioning.h b/libc/include/android/versioning.h
index b09cf14..1676a72 100644
--- a/libc/include/android/versioning.h
+++ b/libc/include/android/versioning.h
@@ -32,6 +32,11 @@
 // load even on systems too old to contain the API, but calls must be guarded
 // with `__builtin_available(android api_level, *)` to avoid segfaults.
 #define __BIONIC_AVAILABILITY(__what, ...) __attribute__((__availability__(android,__what __VA_OPT__(,) __VA_ARGS__)))
+
+// When the caller is using weak API references, we should expose the decls for
+// APIs which are not available in the caller's minSdkVersion, otherwise there's
+// no way to take advantage of the weak references.
+#define __BIONIC_AVAILABILITY_GUARD(api_level) 1
 #else
 // The 'strict' flag is required for NDK clients where the code was not written
 // to handle the case where the API was available at build-time but not at
@@ -40,6 +45,17 @@
 // compile in this mode (or worse, if the build doesn't use
 // -Werror=unguarded-availability, it would build but crash at runtime).
 #define __BIONIC_AVAILABILITY(__what, ...) __attribute__((__availability__(android,strict,__what __VA_OPT__(,) __VA_ARGS__)))
+
+// When the caller is using strict API references, we hide APIs which are not
+// available in the caller's minSdkVersion. This is a bionic-only deviation in
+// behavior from the rest of the NDK headers, but it's necessary to maintain
+// source compatibility with 3p libraries that either can't correctly detect API
+// availability (either incorrectly detecting as always-available or as
+// never-available, but neither is true), or define their own polyfills which
+// conflict with our declarations.
+//
+// https://github.com/android/ndk/issues/2081
+#define __BIONIC_AVAILABILITY_GUARD(api_level) (__ANDROID_MIN_SDK_VERSION__ >= (api_level))
 #endif
 
 #pragma clang diagnostic push
@@ -69,4 +85,5 @@
 #if defined(__ANDROID_VNDK__)
 #undef __BIONIC_AVAILABILITY
 #define __BIONIC_AVAILABILITY(api_level, ...)
+#define __BIONIC_AVAILABILITY_GUARD(api_level) 1
 #endif // defined(__ANDROID_VNDK__)