summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--include/nativebridge/native_bridge.h31
-rw-r--r--libnativebridge/Android.mk4
-rw-r--r--libnativebridge/native_bridge.cc247
-rw-r--r--libnativebridge/tests/Android.mk2
-rw-r--r--libnativebridge/tests/NeedsNativeBridge_test.cpp48
-rw-r--r--libnativebridge/tests/PreInitializeNativeBridge_test.cpp66
-rw-r--r--libnativebridge/tests/UnavailableNativeBridge_test.cpp2
7 files changed, 388 insertions, 12 deletions
diff --git a/include/nativebridge/native_bridge.h b/include/nativebridge/native_bridge.h
index 16939f1..ac254e9 100644
--- a/include/nativebridge/native_bridge.h
+++ b/include/nativebridge/native_bridge.h
@@ -19,18 +19,29 @@
#include "jni.h"
#include <stdint.h>
+#include <sys/types.h>
namespace android {
struct NativeBridgeRuntimeCallbacks;
+struct NativeBridgeRuntimeValues;
// Open the native bridge, if any. Should be called by Runtime::Init(). A null library filename
// signals that we do not want to load a native bridge.
bool LoadNativeBridge(const char* native_bridge_library_filename,
const NativeBridgeRuntimeCallbacks* runtime_callbacks);
-// Initialize the native bridge, if any. Should be called by Runtime::DidForkFromZygote.
-bool InitializeNativeBridge();
+// Quick check whether a native bridge will be needed. This is based off of the instruction set
+// of the process.
+bool NeedsNativeBridge(const char* instruction_set);
+
+// Do the early initialization part of the native bridge, if necessary. This should be done under
+// high privileges.
+void PreInitializeNativeBridge(const char* app_data_dir, const char* instruction_set);
+
+// Initialize the native bridge, if any. Should be called by Runtime::DidForkFromZygote. The JNIEnv*
+// will be used to modify the app environment for the bridge.
+bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set);
// Unload the native bridge, if any. Should be called by Runtime::DidForkFromZygote.
void UnloadNativeBridge();
@@ -65,6 +76,9 @@ bool NativeBridgeNameAcceptable(const char* native_bridge_library_filename);
// Native bridge interfaces to runtime.
struct NativeBridgeCallbacks {
+ // Version number of the interface.
+ uint32_t version;
+
// Initialize native bridge. Native bridge's internal implementation must ensure MT safety and
// that the native bridge is initialized only once. Thus it is OK to call this interface for an
// already initialized native bridge.
@@ -73,7 +87,8 @@ struct NativeBridgeCallbacks {
// runtime_cbs [IN] the pointer to NativeBridgeRuntimeCallbacks.
// Returns:
// true iff initialization was successful.
- bool (*initialize)(const NativeBridgeRuntimeCallbacks* runtime_cbs);
+ bool (*initialize)(const NativeBridgeRuntimeCallbacks* runtime_cbs, const char* private_dir,
+ const char* instruction_set);
// Load a shared library that is supported by the native bridge.
//
@@ -102,6 +117,16 @@ struct NativeBridgeCallbacks {
// Returns:
// TRUE if library is supported by native bridge, FALSE otherwise
bool (*isSupported)(const char* libpath);
+
+ // Provide environment values required by the app running with native bridge according to the
+ // instruction set.
+ //
+ // Parameters:
+ // instruction_set [IN] the instruction set of the app
+ // Returns:
+ // NULL if not supported by native bridge.
+ // Otherwise, return all environment values to be set after fork.
+ const struct NativeBridgeRuntimeValues* (*getAppEnv)(const char* instruction_set);
};
// Runtime interfaces to native bridge.
diff --git a/libnativebridge/Android.mk b/libnativebridge/Android.mk
index 3009bb9..6c2e43e 100644
--- a/libnativebridge/Android.mk
+++ b/libnativebridge/Android.mk
@@ -13,7 +13,7 @@ LOCAL_SRC_FILES:= $(NATIVE_BRIDGE_COMMON_SRC_FILES)
LOCAL_SHARED_LIBRARIES := liblog
LOCAL_CLANG := true
LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS := -Werror
+LOCAL_CFLAGS := -Werror -Wall
LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
LOCAL_LDFLAGS := -ldl
LOCAL_MULTILIB := both
@@ -30,7 +30,7 @@ LOCAL_SRC_FILES:= $(NATIVE_BRIDGE_COMMON_SRC_FILES)
LOCAL_SHARED_LIBRARIES := liblog
LOCAL_CLANG := true
LOCAL_CPP_EXTENSION := .cc
-LOCAL_CFLAGS := -Werror
+LOCAL_CFLAGS := -Werror -Wall
LOCAL_CPPFLAGS := -std=gnu++11 -fvisibility=protected
LOCAL_LDFLAGS := -ldl
LOCAL_MULTILIB := both
diff --git a/libnativebridge/native_bridge.cc b/libnativebridge/native_bridge.cc
index 6602d3f..d460f6f 100644
--- a/libnativebridge/native_bridge.cc
+++ b/libnativebridge/native_bridge.cc
@@ -16,13 +16,27 @@
#include "nativebridge/native_bridge.h"
+#include <cstring>
#include <cutils/log.h>
#include <dlfcn.h>
+#include <errno.h>
+#include <fcntl.h>
#include <stdio.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
namespace android {
+// Environment values required by the apps running with native bridge.
+struct NativeBridgeRuntimeValues {
+ const char* os_arch;
+ const char* cpu_abi;
+ const char* cpu_abi2;
+ const char* *supported_abis;
+ int32_t abi_count;
+};
+
// The symbol name exposed by native-bridge with the type of NativeBridgeCallbacks.
static constexpr const char* kNativeBridgeInterfaceSymbol = "NativeBridgeItf";
@@ -68,6 +82,11 @@ static NativeBridgeCallbacks* callbacks = nullptr;
// Callbacks provided by the environment to the bridge. Passed to LoadNativeBridge.
static const NativeBridgeRuntimeCallbacks* runtime_callbacks = nullptr;
+// The app's data directory.
+static char* app_data_dir = nullptr;
+
+static constexpr uint32_t kNativeBridgeCallbackVersion = 1;
+
// Characters allowed in a native bridge filename. The first character must
// be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
static bool CharacterAllowed(char c, bool first) {
@@ -109,6 +128,10 @@ bool NativeBridgeNameAcceptable(const char* nb_library_filename) {
}
}
+static bool VersionCheck(NativeBridgeCallbacks* cb) {
+ return cb != nullptr && cb->version == kNativeBridgeCallbackVersion;
+}
+
bool LoadNativeBridge(const char* nb_library_filename,
const NativeBridgeRuntimeCallbacks* runtime_cbs) {
// We expect only one place that calls LoadNativeBridge: Runtime::Init. At that point we are not
@@ -116,8 +139,10 @@ bool LoadNativeBridge(const char* nb_library_filename,
if (state != NativeBridgeState::kNotSetup) {
// Setup has been called before. Ignore this call.
- ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
- GetNativeBridgeStateString(state));
+ if (nb_library_filename != nullptr) { // Avoids some log-spam for dalvikvm.
+ ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
+ GetNativeBridgeStateString(state));
+ }
// Note: counts as an error, even though the bridge may be functional.
had_error = true;
return false;
@@ -137,8 +162,14 @@ bool LoadNativeBridge(const char* nb_library_filename,
callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
kNativeBridgeInterfaceSymbol));
if (callbacks != nullptr) {
- // Store the handle for later.
- native_bridge_handle = handle;
+ if (VersionCheck(callbacks)) {
+ // Store the handle for later.
+ native_bridge_handle = handle;
+ } else {
+ callbacks = nullptr;
+ dlclose(handle);
+ ALOGW("Unsupported native bridge interface.");
+ }
} else {
dlclose(handle);
}
@@ -158,13 +189,217 @@ bool LoadNativeBridge(const char* nb_library_filename,
}
}
-bool InitializeNativeBridge() {
+#if defined(__arm__)
+static const char* kRuntimeISA = "arm";
+#elif defined(__aarch64__)
+static const char* kRuntimeISA = "arm64";
+#elif defined(__mips__)
+static const char* kRuntimeISA = "mips";
+#elif defined(__i386__)
+static const char* kRuntimeISA = "x86";
+#elif defined(__x86_64__)
+static const char* kRuntimeISA = "x86_64";
+#else
+static const char* kRuntimeISA = "unknown";
+#endif
+
+
+bool NeedsNativeBridge(const char* instruction_set) {
+ if (instruction_set == nullptr) {
+ ALOGE("Null instruction set in NeedsNativeBridge.");
+ return false;
+ }
+ return strncmp(instruction_set, kRuntimeISA, strlen(kRuntimeISA) + 1) != 0;
+}
+
+#ifdef __APPLE__
+template<typename T> void UNUSED(const T&) {}
+#endif
+
+void PreInitializeNativeBridge(const char* app_data_dir_in, const char* instruction_set) {
+ if (app_data_dir_in == nullptr) {
+ return;
+ }
+
+ const size_t len = strlen(app_data_dir_in);
+ // Make a copy for us.
+ app_data_dir = new char[len];
+ strncpy(app_data_dir, app_data_dir_in, len);
+
+#ifndef __APPLE__
+ if (instruction_set == nullptr) {
+ return;
+ }
+ size_t isa_len = strlen(instruction_set);
+ if (isa_len > 10) {
+ // 10 is a loose upper bound on the currently known instruction sets (a tight bound is 7 for
+ // x86_64 [including the trailing \0]). This is so we don't have to change here if there will
+ // be another instruction set in the future.
+ ALOGW("Instruction set %s is malformed, must be less than or equal to 10 characters.",
+ instruction_set);
+ return;
+ }
+
+ // Bind-mount /system/lib{,64}/<isa>/cpuinfo to /proc/cpuinfo. If the file does not exist, the
+ // mount command will fail, so we safe the extra file existence check...
+ char cpuinfo_path[1024];
+
+#ifdef HAVE_ANDROID_OS
+ snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/lib"
+#ifdef __LP64__
+ "64"
+#endif // __LP64__
+ "/%s/cpuinfo", instruction_set);
+#else // !HAVE_ANDROID_OS
+ // To be able to test on the host, we hardwire a relative path.
+ snprintf(cpuinfo_path, sizeof(cpuinfo_path), "./cpuinfo");
+#endif
+
+ // Bind-mount.
+ if (TEMP_FAILURE_RETRY(mount(cpuinfo_path, // Source.
+ "/proc/cpuinfo", // Target.
+ nullptr, // FS type.
+ MS_BIND, // Mount flags: bind mount.
+ nullptr)) == -1) { // "Data."
+ ALOGW("Failed to bind-mount %s as /proc/cpuinfo: %s", cpuinfo_path, strerror(errno));
+ }
+#else
+ UNUSED(instruction_set);
+ ALOGW("Mac OS does not support bind-mounting. Host simulation of native bridge impossible.");
+#endif
+}
+
+static void SetCpuAbi(JNIEnv* env, jclass build_class, const char* field, const char* value) {
+ if (value != nullptr) {
+ jfieldID field_id = env->GetStaticFieldID(build_class, field, "Ljava/lang/String;");
+ if (field_id == nullptr) {
+ env->ExceptionClear();
+ ALOGW("Could not find %s field.", field);
+ return;
+ }
+
+ jstring str = env->NewStringUTF(value);
+ if (str == nullptr) {
+ env->ExceptionClear();
+ ALOGW("Could not create string %s.", value);
+ return;
+ }
+
+ env->SetStaticObjectField(build_class, field_id, str);
+ }
+}
+
+static void SetSupportedAbis(JNIEnv* env, jclass build_class, const char* field,
+ const char* *values, int32_t value_count) {
+ if (value_count < 0) {
+ return;
+ }
+ if (values == nullptr && value_count > 0) {
+ ALOGW("More than zero values expected: %d.", value_count);
+ return;
+ }
+
+ jfieldID field_id = env->GetStaticFieldID(build_class, field, "[Ljava/lang/String;");
+ if (field_id != nullptr) {
+ // Create the array.
+ jobjectArray array = env->NewObjectArray(value_count, env->FindClass("java/lang/String"),
+ nullptr);
+ if (array == nullptr) {
+ env->ExceptionClear();
+ ALOGW("Could not create array.");
+ return;
+ }
+
+ // Fill the array.
+ for (int32_t i = 0; i < value_count; i++) {
+ jstring str = env->NewStringUTF(values[i]);
+ if (str == nullptr) {
+ env->ExceptionClear();
+ ALOGW("Could not create string %s.", values[i]);
+ return;
+ }
+
+ env->SetObjectArrayElement(array, i, str);
+ }
+
+ env->SetStaticObjectField(build_class, field_id, array);
+ } else {
+ env->ExceptionClear();
+ ALOGW("Could not find %s field.", field);
+ }
+}
+
+// Set up the environment for the bridged app.
+static void SetupEnvironment(NativeBridgeCallbacks* callbacks, JNIEnv* env, const char* isa) {
+ // Need a JNIEnv* to do anything.
+ if (env == nullptr) {
+ ALOGW("No JNIEnv* to set up app environment.");
+ return;
+ }
+
+ // Query the bridge for environment values.
+ const struct NativeBridgeRuntimeValues* env_values = callbacks->getAppEnv(isa);
+ if (env_values == nullptr) {
+ return;
+ }
+
+ // Keep the JNIEnv clean.
+ jint success = env->PushLocalFrame(16); // That should be small and large enough.
+ if (success < 0) {
+ // Out of memory, really borked.
+ ALOGW("Out of memory while setting up app environment.");
+ env->ExceptionClear();
+ return;
+ }
+
+ // Reset CPU_ABI & CPU_ABI2 to values required by the apps running with native bridge.
+ if (env_values->cpu_abi != nullptr || env_values->cpu_abi2 != nullptr ||
+ env_values->abi_count >= 0) {
+ jclass bclass_id = env->FindClass("android/os/Build");
+ if (bclass_id != nullptr) {
+ SetCpuAbi(env, bclass_id, "CPU_ABI", env_values->cpu_abi);
+ SetCpuAbi(env, bclass_id, "CPU_ABI2", env_values->cpu_abi2);
+
+ SetSupportedAbis(env, bclass_id, "SUPPORTED_ABIS", env_values->supported_abis,
+ env_values->abi_count);
+ } else {
+ // For example in a host test environment.
+ env->ExceptionClear();
+ ALOGW("Could not find Build class.");
+ }
+ }
+
+ if (env_values->os_arch != nullptr) {
+ jclass sclass_id = env->FindClass("java/lang/System");
+ if (sclass_id != nullptr) {
+ jmethodID set_prop_id = env->GetStaticMethodID(sclass_id, "setProperty",
+ "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
+ if (set_prop_id != nullptr) {
+ // Reset os.arch to the value reqired by the apps running with native bridge.
+ env->CallStaticObjectMethod(sclass_id, set_prop_id, env->NewStringUTF("os.arch"),
+ env->NewStringUTF(env_values->os_arch));
+ } else {
+ env->ExceptionClear();
+ ALOGW("Could not find setProperty method.");
+ }
+ } else {
+ env->ExceptionClear();
+ ALOGW("Could not find System class.");
+ }
+ }
+
+ // Make it pristine again.
+ env->PopLocalFrame(nullptr);
+}
+
+bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
// We expect only one place that calls InitializeNativeBridge: Runtime::DidForkFromZygote. At that
// point we are not multi-threaded, so we do not need locking here.
if (state == NativeBridgeState::kOpened) {
// Try to initialize.
- if (callbacks->initialize(runtime_callbacks)) {
+ if (callbacks->initialize(runtime_callbacks, app_data_dir, instruction_set)) {
+ SetupEnvironment(callbacks, env, instruction_set);
state = NativeBridgeState::kInitialized;
} else {
// Unload the library.
diff --git a/libnativebridge/tests/Android.mk b/libnativebridge/tests/Android.mk
index 457b163..9c7e1b8 100644
--- a/libnativebridge/tests/Android.mk
+++ b/libnativebridge/tests/Android.mk
@@ -5,6 +5,8 @@ include $(CLEAR_VARS)
# Build the unit tests.
test_src_files := \
InvalidCharsNativeBridge_test.cpp \
+ NeedsNativeBridge_test.cpp \
+ PreInitializeNativeBridge_test.cpp \
ReSetupNativeBridge_test.cpp \
UnavailableNativeBridge_test.cpp \
ValidNameNativeBridge_test.cpp
diff --git a/libnativebridge/tests/NeedsNativeBridge_test.cpp b/libnativebridge/tests/NeedsNativeBridge_test.cpp
new file mode 100644
index 0000000..e1c0876
--- /dev/null
+++ b/libnativebridge/tests/NeedsNativeBridge_test.cpp
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2014 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 "NativeBridgeTest.h"
+
+namespace android {
+
+static const char* kISAs[] = { "arm", "arm64", "mips", "x86", "x86_64", "random", "64arm", "64_x86",
+ "64_x86_64", "", "reallylongstringabcd", nullptr };
+
+#if defined(__arm__)
+static const char* kRuntimeISA = "arm";
+#elif defined(__aarch64__)
+static const char* kRuntimeISA = "arm64";
+#elif defined(__mips__)
+static const char* kRuntimeISA = "mips";
+#elif defined(__i386__)
+static const char* kRuntimeISA = "x86";
+#elif defined(__x86_64__)
+static const char* kRuntimeISA = "x86_64";
+#else
+static const char* kRuntimeISA = "unknown";
+#endif
+
+TEST_F(NativeBridgeTest, NeedsNativeBridge) {
+ EXPECT_EQ(false, NeedsNativeBridge(kRuntimeISA));
+
+ const size_t kISACount = sizeof(kISAs)/sizeof(kISAs[0]);
+ for (size_t i = 0; i < kISACount; i++) {
+ EXPECT_EQ(kISAs[i] == nullptr ? false : strcmp(kISAs[i], kRuntimeISA) != 0,
+ NeedsNativeBridge(kISAs[i]));
+ }
+}
+
+} // namespace android
diff --git a/libnativebridge/tests/PreInitializeNativeBridge_test.cpp b/libnativebridge/tests/PreInitializeNativeBridge_test.cpp
new file mode 100644
index 0000000..9b487d7
--- /dev/null
+++ b/libnativebridge/tests/PreInitializeNativeBridge_test.cpp
@@ -0,0 +1,66 @@
+/*
+ * Copyright (C) 2014 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 "NativeBridgeTest.h"
+
+#include <cstdio>
+#include <cstring>
+#include <cutils/log.h>
+#include <dlfcn.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+
+namespace android {
+
+static constexpr const char* kTestData = "PreInitializeNativeBridge test.";
+
+TEST_F(NativeBridgeTest, PreInitializeNativeBridge) {
+#ifndef __APPLE_ // Mac OS does not support bind-mount.
+#ifndef HAVE_ANDROID_OS // Cannot write into the hard-wired location.
+ // Try to create our mount namespace.
+ if (unshare(CLONE_NEWNS) != -1) {
+ // Create a dummy file.
+ FILE* cpuinfo = fopen("./cpuinfo", "w");
+ ASSERT_NE(nullptr, cpuinfo) << strerror(errno);
+ fprintf(cpuinfo, kTestData);
+ fclose(cpuinfo);
+
+ // Call the setup.
+ PreInitializeNativeBridge("does not matter 1", "short 2");
+
+ // Read /proc/cpuinfo
+ FILE* proc_cpuinfo = fopen("/proc/cpuinfo", "r");
+ ASSERT_NE(nullptr, proc_cpuinfo) << strerror(errno);
+ char buf[1024];
+ EXPECT_NE(nullptr, fgets(buf, sizeof(buf), proc_cpuinfo)) << "Error reading.";
+ fclose(proc_cpuinfo);
+
+ EXPECT_EQ(0, strcmp(buf, kTestData));
+
+ // Delete the file.
+ ASSERT_EQ(0, unlink("./cpuinfo")) << "Error unlinking temporary file.";
+ // Ending the test will tear down the mount namespace.
+ } else {
+ GTEST_LOG_(WARNING) << "Could not create mount namespace. Are you running this as root?";
+ }
+#endif
+#endif
+}
+
+} // namespace android
diff --git a/libnativebridge/tests/UnavailableNativeBridge_test.cpp b/libnativebridge/tests/UnavailableNativeBridge_test.cpp
index ec96c32..ad374a5 100644
--- a/libnativebridge/tests/UnavailableNativeBridge_test.cpp
+++ b/libnativebridge/tests/UnavailableNativeBridge_test.cpp
@@ -21,7 +21,7 @@ namespace android {
TEST_F(NativeBridgeTest, NoNativeBridge) {
EXPECT_EQ(false, NativeBridgeAvailable());
// Try to initialize. This should fail as we are not set up.
- EXPECT_EQ(false, InitializeNativeBridge());
+ EXPECT_EQ(false, InitializeNativeBridge(nullptr, nullptr));
EXPECT_EQ(true, NativeBridgeError());
EXPECT_EQ(false, NativeBridgeAvailable());
}