libnativehelper: refactoring for Runtime Module

This change puts a C ABI between the caller and libnativehelper which
means each could link separate libc++ library instances using
namespaces.

Bug: b/119840313
Test: Builds & boots
Test: atest JniInvocation_test
Test: atest libnativehelper_api_test

Change-Id: Idaa4ddd3118cbb4f3997abdcf355220ef80eb775
diff --git a/include/nativehelper/AsynchronousCloseMonitor.h b/include/nativehelper/AsynchronousCloseMonitor.h
index 2afc35c..e172ac4 100644
--- a/include/nativehelper/AsynchronousCloseMonitor.h
+++ b/include/nativehelper/AsynchronousCloseMonitor.h
@@ -19,6 +19,17 @@
 
 #include <pthread.h>
 
+#include "module_api.h"
+
+// Public API for library function.
+MODULE_API void async_close_monitor_destroy(void* instance);
+MODULE_API void async_close_monitor_static_init();
+MODULE_API void async_close_monitor_signal_blocked_threads(int fd);
+MODULE_API int async_close_monitor_was_signalled(const void* instance);
+MODULE_API void* async_close_monitor_create(int fd);
+
+#ifdef __cplusplus
+
 /**
  * AsynchronousCloseMonitor helps implement Java's asynchronous close semantics.
  *
@@ -42,24 +53,31 @@
  */
 class AsynchronousCloseMonitor {
 public:
-    explicit AsynchronousCloseMonitor(int fd);
-    ~AsynchronousCloseMonitor();
-    bool wasSignaled() const;
+    explicit AsynchronousCloseMonitor(int fd) {
+        instance_ = async_close_monitor_create(fd);
+    }
+    ~AsynchronousCloseMonitor() {
+        async_close_monitor_destroy(instance_);
+    }
+    bool wasSignaled() const {
+        return async_close_monitor_was_signalled(instance_) != 0;
+    }
 
-    static void init();
+    static void init() {
+        async_close_monitor_static_init();
+    }
 
-    static void signalBlockedThreads(int fd);
+    static void signalBlockedThreads(int fd) {
+        async_close_monitor_signal_blocked_threads(fd);
+    }
 
 private:
-    AsynchronousCloseMonitor* mPrev;
-    AsynchronousCloseMonitor* mNext;
-    pthread_t mThread;
-    int mFd;
-    bool mSignaled;
+    AsynchronousCloseMonitor(const AsynchronousCloseMonitor&) = delete;
+    AsynchronousCloseMonitor& operator=(const AsynchronousCloseMonitor&) = delete;
 
-    // Disallow copy and assignment.
-    AsynchronousCloseMonitor(const AsynchronousCloseMonitor&);
-    void operator=(const AsynchronousCloseMonitor&);
+    void* instance_;
 };
 
+#endif  // __cplusplus
+
 #endif  // ASYNCHRONOUS_CLOSE_MONITOR_H_included
diff --git a/include/nativehelper/JNIHelp.h b/include/nativehelper/JNIHelp.h
index d70fdad..08616b7 100644
--- a/include/nativehelper/JNIHelp.h
+++ b/include/nativehelper/JNIHelp.h
@@ -19,30 +19,29 @@
  *
  * This file may be included by C or C++ code, which is trouble because jni.h
  * uses different typedefs for JNIEnv in each language.
- *
- * TODO: remove C support.
  */
 #ifndef NATIVEHELPER_JNIHELP_H_
 #define NATIVEHELPER_JNIHELP_H_
 
-#include "jni.h"
 #include <errno.h>
 #include <unistd.h>
 
+#include <jni.h>
+#include "module_api.h"
+
 #ifndef NELEM
 # define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
 #endif
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
 /*
  * Register one or more native methods with a particular class.
  * "className" looks like "java/lang/String". Aborts on failure.
  * TODO: fix all callers and change the return type to void.
  */
-int jniRegisterNativeMethods(C_JNIEnv* env, const char* className, const JNINativeMethod* gMethods, int numMethods);
+MODULE_API int jniRegisterNativeMethods(C_JNIEnv* env,
+                                        const char* className,
+                                        const JNINativeMethod* gMethods,
+                                        int numMethods);
 
 /*
  * Throw an exception with the specified class and an optional message.
@@ -58,22 +57,38 @@
  *
  * Currently aborts the VM if it can't throw the exception.
  */
-int jniThrowException(C_JNIEnv* env, const char* className, const char* msg);
+MODULE_API int jniThrowException(C_JNIEnv* env, const char* className, const char* msg);
+
+/*
+ * Throw an exception with the specified class and formatted error message.
+ *
+ * The "className" argument will be passed directly to FindClass, which
+ * takes strings with slashes (e.g. "java/lang/Object").
+ *
+ * If an exception is currently pending, we log a warning message and
+ * clear it.
+ *
+ * Returns 0 on success, nonzero if something failed (e.g. the exception
+ * class couldn't be found, so *an* exception will still be pending).
+ *
+ * Currently aborts the VM if it can't throw the exception.
+ */
+MODULE_API int jniThrowExceptionFmt(C_JNIEnv* env, const char* className, const char* fmt, va_list args);
 
 /*
  * Throw a java.lang.NullPointerException, with an optional message.
  */
-int jniThrowNullPointerException(C_JNIEnv* env, const char* msg);
+MODULE_API int jniThrowNullPointerException(C_JNIEnv* env, const char* msg);
 
 /*
  * Throw a java.lang.RuntimeException, with an optional message.
  */
-int jniThrowRuntimeException(C_JNIEnv* env, const char* msg);
+MODULE_API int jniThrowRuntimeException(C_JNIEnv* env, const char* msg);
 
 /*
  * Throw a java.io.IOException, generating the message from errno.
  */
-int jniThrowIOException(C_JNIEnv* env, int errnum);
+MODULE_API int jniThrowIOException(C_JNIEnv* env, int errnum);
 
 /*
  * Return a pointer to a locale-dependent error string explaining errno
@@ -81,56 +96,54 @@
  * This function is thread-safe (unlike strerror) and portable (unlike
  * strerror_r).
  */
-const char* jniStrError(int errnum, char* buf, size_t buflen);
+MODULE_API const char* jniStrError(int errnum, char* buf, size_t buflen);
 
 /*
  * Returns a new java.io.FileDescriptor for the given int fd.
  */
-jobject jniCreateFileDescriptor(C_JNIEnv* env, int fd);
+MODULE_API jobject jniCreateFileDescriptor(C_JNIEnv* env, int fd);
 
 /*
  * Returns the int fd from a java.io.FileDescriptor.
  */
-int jniGetFDFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor);
+MODULE_API int jniGetFDFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor);
 
 /*
  * Sets the int fd in a java.io.FileDescriptor.  Throws java.lang.NullPointerException
  * if fileDescriptor is null.
  */
-void jniSetFileDescriptorOfFD(C_JNIEnv* env, jobject fileDescriptor, int value);
+MODULE_API void jniSetFileDescriptorOfFD(C_JNIEnv* env,
+                                         jobject fileDescriptor,
+                                         int value);
 
 /*
  * Returns the long ownerId from a java.io.FileDescriptor.
  */
-jlong jniGetOwnerIdFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor);
+MODULE_API jlong jniGetOwnerIdFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor);
 
 /*
  * Returns the reference from a java.lang.ref.Reference.
  */
-jobject jniGetReferent(C_JNIEnv* env, jobject ref);
+MODULE_API jobject jniGetReferent(C_JNIEnv* env, jobject ref);
 
 /*
  * Returns a Java String object created from UTF-16 data either from jchar or,
  * if called from C++11, char16_t (a bitwise identical distinct type).
  */
-jstring jniCreateString(C_JNIEnv* env, const jchar* unicodeChars, jsize len);
+MODULE_API jstring jniCreateString(C_JNIEnv* env, const jchar* unicodeChars, jsize len);
 
 /*
  * Log a message and an exception.
  * If exception is NULL, logs the current exception in the JNI environment.
  */
-void jniLogException(C_JNIEnv* env, int priority, const char* tag, jthrowable exception);
-
-#ifdef __cplusplus
-}
-#endif
-
+MODULE_API void jniLogException(C_JNIEnv* env, int priority, const char* tag, jthrowable exception);
 
 /*
  * For C++ code, we provide inlines that map to the C functions.  g++ always
  * inlines these, even on non-optimized builds.
  */
 #if defined(__cplusplus)
+
 inline int jniRegisterNativeMethods(JNIEnv* env, const char* className, const JNINativeMethod* gMethods, int numMethods) {
     return jniRegisterNativeMethods(&env->functions, className, gMethods, numMethods);
 }
@@ -139,8 +152,6 @@
     return jniThrowException(&env->functions, className, msg);
 }
 
-extern "C" int jniThrowExceptionFmt(C_JNIEnv* env, const char* className, const char* fmt, va_list args);
-
 /*
  * Equivalent to jniThrowException but with a printf-like format string and
  * variable-length argument list. This is only available in C++.
@@ -204,7 +215,7 @@
   void operator=(const TypeName&) = delete
 #endif  // !defined(DISALLOW_COPY_AND_ASSIGN)
 
-#endif
+#endif  // defined(__cplusplus)
 
 /*
  * TEMP_FAILURE_RETRY is defined by some, but not all, versions of
diff --git a/include/nativehelper/JniInvocation.h b/include/nativehelper/JniInvocation.h
index 58beec5..0d87aa9 100644
--- a/include/nativehelper/JniInvocation.h
+++ b/include/nativehelper/JniInvocation.h
@@ -18,6 +18,16 @@
 #define JNI_INVOCATION_H_included
 
 #include <jni.h>
+#include "module_api.h"
+
+struct JniInvocationImpl;
+
+MODULE_API struct JniInvocationImpl* JniInvocationCreate();
+MODULE_API void JniInvocationDestroy(struct JniInvocationImpl* instance);
+MODULE_API int JniInvocationInit(struct JniInvocationImpl* instance, const char* library);
+MODULE_API const char* JniInvocationGetLibrary(const char* library, char* buffer);
+
+#ifdef __cplusplus
 
 // JniInvocation adds a layer of indirection for applications using
 // the JNI invocation API to allow the JNI implementation to be
@@ -26,48 +36,45 @@
 // library will chosen based on the value of Android system property
 // persist.sys.dalvik.vm.lib on the device, and otherwise fall back to
 // a hard-coded default implementation.
-class JniInvocation {
+class JniInvocation final {
  public:
-  JniInvocation();
+  JniInvocation() {
+    impl_ = JniInvocationCreate();
+  }
 
-  ~JniInvocation();
+  ~JniInvocation() {
+    JniInvocationDestroy(impl_);
+  }
 
   // Initialize JNI invocation API. library should specifiy a valid
   // shared library for opening via dlopen providing a JNI invocation
   // implementation, or null to allow defaulting via
   // persist.sys.dalvik.vm.lib.
-  bool Init(const char* library);
+  bool Init(const char* library) {
+    return JniInvocationInit(impl_, library) != 0;
+  }
 
   // Exposes which library is actually loaded from the given name. The
   // buffer of size PROPERTY_VALUE_MAX will be used to load the system
   // property for the default library, if necessary. If no buffer is
   // provided, the fallback value will be used.
-  static const char* GetLibrary(const char* library, char* buffer);
+  static const char* GetLibrary(const char* library, char* buffer) {
+    return JniInvocationGetLibrary(library, buffer);
+  }
 
  private:
+  JniInvocation(const JniInvocation&) = delete;
+  JniInvocation& operator=(const JniInvocation&) = delete;
+
   static const char* GetLibrary(const char* library, char* buffer, bool (*is_debuggable)(),
                                 int (*get_library_system_property)(char* buffer));
 
-  bool FindSymbol(void** pointer, const char* symbol);
+  JniInvocationImpl* impl_;
 
-  static JniInvocation& GetJniInvocation();
-
-  jint JNI_GetDefaultJavaVMInitArgs(void* vmargs);
-  jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args);
-  jint JNI_GetCreatedJavaVMs(JavaVM** vms, jsize size, jsize* vm_count);
-
-  static JniInvocation* jni_invocation_;
-
-  void* handle_;
-  jint (*JNI_GetDefaultJavaVMInitArgs_)(void*);
-  jint (*JNI_CreateJavaVM_)(JavaVM**, JNIEnv**, void*);
-  jint (*JNI_GetCreatedJavaVMs_)(JavaVM**, jsize, jsize*);
-
-  friend jint JNI_GetDefaultJavaVMInitArgs(void* vm_args);
-  friend jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args);
-  friend jint JNI_GetCreatedJavaVMs(JavaVM** vms, jsize size, jsize* vm_count);
   friend class JNIInvocation_Debuggable_Test;
   friend class JNIInvocation_NonDebuggable_Test;
 };
 
+#endif  // __cplusplus
+
 #endif  // JNI_INVOCATION_H_included
diff --git a/include/nativehelper/module_api.h b/include/nativehelper/module_api.h
new file mode 100644
index 0000000..8b109e3
--- /dev/null
+++ b/include/nativehelper/module_api.h
@@ -0,0 +1,23 @@
+/*
+ * 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.
+ */
+
+#pragma once
+
+#ifdef __cplusplus
+#define MODULE_API extern "C"
+#else
+#define MODULE_API
+#endif  // __cplusplus
diff --git a/include/nativehelper/toStringArray.h b/include/nativehelper/toStringArray.h
index cb46024..1965d6a 100644
--- a/include/nativehelper/toStringArray.h
+++ b/include/nativehelper/toStringArray.h
@@ -17,13 +17,20 @@
 #ifndef TO_STRING_ARRAY_H_included
 #define TO_STRING_ARRAY_H_included
 
-#include "jni.h"
-#include "ScopedLocalRef.h"
+#include <stddef.h>
+
+#include <jni.h>
+#include "module_api.h"
+
+// Public API for libnativehelper library.
+MODULE_API jobjectArray newStringArray(JNIEnv* env, size_t count);
+MODULE_API jobjectArray toStringArray(JNIEnv* env, const char* const* strings);
+
+#ifdef __cplusplus
 
 #include <string>
 #include <vector>
-
-jobjectArray newStringArray(JNIEnv* env, size_t count);
+#include "ScopedLocalRef.h"
 
 template <typename Counter, typename Getter>
 jobjectArray toStringArray(JNIEnv* env, Counter* counter, Getter* getter) {
@@ -66,6 +73,6 @@
     return toStringArray<VectorCounter, VectorGetter>(env, &counter, &getter);
 }
 
-JNIEXPORT jobjectArray toStringArray(JNIEnv* env, const char* const* strings);
+#endif  // __cplusplus
 
 #endif  // TO_STRING_ARRAY_H_included