blob: 9f9c83faf18b5e5b7ce572792366712a5551b311 [file] [log] [blame]
Calin Juravle961ae122014-08-11 16:11:59 +01001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "nativebridge/native_bridge.h"
18
19#include <dlfcn.h>
jgu21ab0da5a2014-09-10 06:58:32 -040020#include <errno.h>
21#include <fcntl.h>
Calin Juravle961ae122014-08-11 16:11:59 +010022#include <stdio.h>
jgu21ab0da5a2014-09-10 06:58:32 -040023#include <sys/mount.h>
24#include <sys/stat.h>
Calin Juravle961ae122014-08-11 16:11:59 +010025
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070026#include <cstring>
27
28#include <android/log.h>
Calin Juravle961ae122014-08-11 16:11:59 +010029
30namespace android {
31
jgu21ab0da5a2014-09-10 06:58:32 -040032// Environment values required by the apps running with native bridge.
33struct NativeBridgeRuntimeValues {
34 const char* os_arch;
35 const char* cpu_abi;
36 const char* cpu_abi2;
37 const char* *supported_abis;
38 int32_t abi_count;
39};
40
Calin Juravle961ae122014-08-11 16:11:59 +010041// The symbol name exposed by native-bridge with the type of NativeBridgeCallbacks.
42static constexpr const char* kNativeBridgeInterfaceSymbol = "NativeBridgeItf";
43
Andreas Gampe035bd752014-09-02 21:17:03 -070044enum class NativeBridgeState {
45 kNotSetup, // Initial state.
46 kOpened, // After successful dlopen.
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010047 kPreInitialized, // After successful pre-initialization.
Andreas Gampe035bd752014-09-02 21:17:03 -070048 kInitialized, // After successful initialization.
49 kClosed // Closed or errors.
50};
Calin Juravle961ae122014-08-11 16:11:59 +010051
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010052static constexpr const char* kNotSetupString = "kNotSetup";
53static constexpr const char* kOpenedString = "kOpened";
54static constexpr const char* kPreInitializedString = "kPreInitialized";
55static constexpr const char* kInitializedString = "kInitialized";
56static constexpr const char* kClosedString = "kClosed";
Andreas Gampe035bd752014-09-02 21:17:03 -070057
58static const char* GetNativeBridgeStateString(NativeBridgeState state) {
59 switch (state) {
60 case NativeBridgeState::kNotSetup:
61 return kNotSetupString;
62
63 case NativeBridgeState::kOpened:
64 return kOpenedString;
65
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010066 case NativeBridgeState::kPreInitialized:
67 return kPreInitializedString;
68
Andreas Gampe035bd752014-09-02 21:17:03 -070069 case NativeBridgeState::kInitialized:
70 return kInitializedString;
71
72 case NativeBridgeState::kClosed:
73 return kClosedString;
74 }
75}
76
77// Current state of the native bridge.
78static NativeBridgeState state = NativeBridgeState::kNotSetup;
79
Andreas Gampe049249c2014-08-19 22:31:31 -070080// Whether we had an error at some point.
81static bool had_error = false;
Calin Juravle961ae122014-08-11 16:11:59 +010082
Andreas Gampe035bd752014-09-02 21:17:03 -070083// Handle of the loaded library.
84static void* native_bridge_handle = nullptr;
85// Pointer to the callbacks. Available as soon as LoadNativeBridge succeeds, but only initialized
86// later.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -070087static const NativeBridgeCallbacks* callbacks = nullptr;
Andreas Gampe035bd752014-09-02 21:17:03 -070088// Callbacks provided by the environment to the bridge. Passed to LoadNativeBridge.
Calin Juravle961ae122014-08-11 16:11:59 +010089static const NativeBridgeRuntimeCallbacks* runtime_callbacks = nullptr;
90
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010091// The app's code cache directory.
92static char* app_code_cache_dir = nullptr;
93
94// Code cache directory (relative to the application private directory)
95// Ideally we'd like to call into framework to retrieve this name. However that's considered an
96// implementation detail and will require either hacks or consistent refactorings. We compromise
97// and hard code the directory name again here.
98static constexpr const char* kCodeCacheDir = "code_cache";
jgu21ab0da5a2014-09-10 06:58:32 -040099
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700100static constexpr uint32_t kLibNativeBridgeVersion = 2;
jgu21ab0da5a2014-09-10 06:58:32 -0400101
Andreas Gampe049249c2014-08-19 22:31:31 -0700102// Characters allowed in a native bridge filename. The first character must
103// be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
104static bool CharacterAllowed(char c, bool first) {
105 if (first) {
106 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
107 } else {
108 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
109 (c == '.') || (c == '_') || (c == '-');
110 }
111}
112
jgu21cef898f2015-07-02 12:02:11 +0800113static void ReleaseAppCodeCacheDir() {
114 if (app_code_cache_dir != nullptr) {
115 delete[] app_code_cache_dir;
116 app_code_cache_dir = nullptr;
117 }
118}
119
Andreas Gampe049249c2014-08-19 22:31:31 -0700120// We only allow simple names for the library. It is supposed to be a file in
121// /system/lib or /vendor/lib. Only allow a small range of characters, that is
122// names consisting of [a-zA-Z0-9._-] and starting with [a-zA-Z].
123bool NativeBridgeNameAcceptable(const char* nb_library_filename) {
124 const char* ptr = nb_library_filename;
125 if (*ptr == 0) {
126 // Emptry string. Allowed, means no native bridge.
127 return true;
128 } else {
129 // First character must be [a-zA-Z].
130 if (!CharacterAllowed(*ptr, true)) {
131 // Found an invalid fist character, don't accept.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700132 ALOGE("Native bridge library %s has been rejected for first character %c",
133 nb_library_filename,
134 *ptr);
Andreas Gampe049249c2014-08-19 22:31:31 -0700135 return false;
136 } else {
137 // For the rest, be more liberal.
138 ptr++;
139 while (*ptr != 0) {
140 if (!CharacterAllowed(*ptr, false)) {
141 // Found an invalid character, don't accept.
142 ALOGE("Native bridge library %s has been rejected for %c", nb_library_filename, *ptr);
143 return false;
144 }
145 ptr++;
146 }
147 }
148 return true;
149 }
150}
151
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700152static bool VersionCheck(const NativeBridgeCallbacks* cb) {
153 // Libnativebridge is now designed to be forward-compatible. So only "0" is an unsupported
154 // version.
155 if (cb == nullptr || cb->version == 0) {
156 return false;
157 }
158
159 // If this is a v2+ bridge, it may not be forwards- or backwards-compatible. Check.
160 if (cb->version >= 2) {
161 if (!callbacks->isCompatibleWith(kLibNativeBridgeVersion)) {
162 // TODO: Scan which version is supported, and fall back to handle it.
163 return false;
164 }
165 }
166
167 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400168}
169
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100170static void CloseNativeBridge(bool with_error) {
171 state = NativeBridgeState::kClosed;
172 had_error |= with_error;
jgu21cef898f2015-07-02 12:02:11 +0800173 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100174}
175
Andreas Gampe035bd752014-09-02 21:17:03 -0700176bool LoadNativeBridge(const char* nb_library_filename,
177 const NativeBridgeRuntimeCallbacks* runtime_cbs) {
178 // We expect only one place that calls LoadNativeBridge: Runtime::Init. At that point we are not
179 // multi-threaded, so we do not need locking here.
Calin Juravle961ae122014-08-11 16:11:59 +0100180
Andreas Gampe035bd752014-09-02 21:17:03 -0700181 if (state != NativeBridgeState::kNotSetup) {
Andreas Gampe049249c2014-08-19 22:31:31 -0700182 // Setup has been called before. Ignore this call.
jgu21ab0da5a2014-09-10 06:58:32 -0400183 if (nb_library_filename != nullptr) { // Avoids some log-spam for dalvikvm.
184 ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
185 GetNativeBridgeStateString(state));
186 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700187 // Note: counts as an error, even though the bridge may be functional.
188 had_error = true;
Andreas Gampe049249c2014-08-19 22:31:31 -0700189 return false;
190 }
191
Andreas Gampe035bd752014-09-02 21:17:03 -0700192 if (nb_library_filename == nullptr || *nb_library_filename == 0) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100193 CloseNativeBridge(false);
194 return false;
Andreas Gampe035bd752014-09-02 21:17:03 -0700195 } else {
196 if (!NativeBridgeNameAcceptable(nb_library_filename)) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100197 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700198 } else {
199 // Try to open the library.
200 void* handle = dlopen(nb_library_filename, RTLD_LAZY);
201 if (handle != nullptr) {
202 callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
203 kNativeBridgeInterfaceSymbol));
204 if (callbacks != nullptr) {
jgu21ab0da5a2014-09-10 06:58:32 -0400205 if (VersionCheck(callbacks)) {
206 // Store the handle for later.
207 native_bridge_handle = handle;
208 } else {
209 callbacks = nullptr;
210 dlclose(handle);
211 ALOGW("Unsupported native bridge interface.");
212 }
Andreas Gampe035bd752014-09-02 21:17:03 -0700213 } else {
214 dlclose(handle);
215 }
216 }
217
218 // Two failure conditions: could not find library (dlopen failed), or could not find native
219 // bridge interface (dlsym failed). Both are an error and close the native bridge.
220 if (callbacks == nullptr) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100221 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700222 } else {
223 runtime_callbacks = runtime_cbs;
224 state = NativeBridgeState::kOpened;
225 }
226 }
227 return state == NativeBridgeState::kOpened;
228 }
229}
230
jgu21ab0da5a2014-09-10 06:58:32 -0400231#if defined(__arm__)
232static const char* kRuntimeISA = "arm";
233#elif defined(__aarch64__)
234static const char* kRuntimeISA = "arm64";
Douglas Leungd10e0172015-05-19 17:30:08 -0700235#elif defined(__mips__) && !defined(__LP64__)
jgu21ab0da5a2014-09-10 06:58:32 -0400236static const char* kRuntimeISA = "mips";
Douglas Leungd10e0172015-05-19 17:30:08 -0700237#elif defined(__mips__) && defined(__LP64__)
238static const char* kRuntimeISA = "mips64";
jgu21ab0da5a2014-09-10 06:58:32 -0400239#elif defined(__i386__)
240static const char* kRuntimeISA = "x86";
241#elif defined(__x86_64__)
242static const char* kRuntimeISA = "x86_64";
243#else
244static const char* kRuntimeISA = "unknown";
245#endif
246
247
248bool NeedsNativeBridge(const char* instruction_set) {
Andreas Gampe04054e22014-09-25 22:33:01 -0700249 if (instruction_set == nullptr) {
250 ALOGE("Null instruction set in NeedsNativeBridge.");
251 return false;
252 }
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700253 return strncmp(instruction_set, kRuntimeISA, strlen(kRuntimeISA) + 1) != 0;
jgu21ab0da5a2014-09-10 06:58:32 -0400254}
255
Andreas Gampe4390a632014-09-24 18:53:26 -0700256#ifdef __APPLE__
257template<typename T> void UNUSED(const T&) {}
258#endif
259
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100260bool PreInitializeNativeBridge(const char* app_data_dir_in, const char* instruction_set) {
261 if (state != NativeBridgeState::kOpened) {
262 ALOGE("Invalid state: native bridge is expected to be opened.");
263 CloseNativeBridge(true);
264 return false;
jgu21ab0da5a2014-09-10 06:58:32 -0400265 }
266
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100267 if (app_data_dir_in == nullptr) {
268 ALOGE("Application private directory cannot be null.");
269 CloseNativeBridge(true);
270 return false;
271 }
272
273 // Create the path to the application code cache directory.
274 // The memory will be release after Initialization or when the native bridge is closed.
275 const size_t len = strlen(app_data_dir_in) + strlen(kCodeCacheDir) + 2; // '\0' + '/'
276 app_code_cache_dir = new char[len];
277 snprintf(app_code_cache_dir, len, "%s/%s", app_data_dir_in, kCodeCacheDir);
278
279 // Bind-mount /system/lib{,64}/<isa>/cpuinfo to /proc/cpuinfo.
280 // Failure is not fatal and will keep the native bridge in kPreInitialized.
281 state = NativeBridgeState::kPreInitialized;
jgu21ab0da5a2014-09-10 06:58:32 -0400282
Andreas Gampe962eb402014-09-24 16:36:17 -0700283#ifndef __APPLE__
jgu21ab0da5a2014-09-10 06:58:32 -0400284 if (instruction_set == nullptr) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100285 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400286 }
287 size_t isa_len = strlen(instruction_set);
288 if (isa_len > 10) {
289 // 10 is a loose upper bound on the currently known instruction sets (a tight bound is 7 for
290 // x86_64 [including the trailing \0]). This is so we don't have to change here if there will
291 // be another instruction set in the future.
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700292 ALOGW("Instruction set %s is malformed, must be less than or equal to 10 characters.",
293 instruction_set);
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100294 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400295 }
296
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100297 // If the file does not exist, the mount command will fail,
298 // so we save the extra file existence check.
jgu21ab0da5a2014-09-10 06:58:32 -0400299 char cpuinfo_path[1024];
300
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700301#if defined(__ANDROID__)
Andreas Gampe04054e22014-09-25 22:33:01 -0700302 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/lib"
jgu21ab0da5a2014-09-10 06:58:32 -0400303#ifdef __LP64__
Andreas Gampe04054e22014-09-25 22:33:01 -0700304 "64"
305#endif // __LP64__
306 "/%s/cpuinfo", instruction_set);
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700307#else // !__ANDROID__
Andreas Gampe04054e22014-09-25 22:33:01 -0700308 // To be able to test on the host, we hardwire a relative path.
309 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "./cpuinfo");
jgu21ab0da5a2014-09-10 06:58:32 -0400310#endif
jgu21ab0da5a2014-09-10 06:58:32 -0400311
312 // Bind-mount.
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700313 if (TEMP_FAILURE_RETRY(mount(cpuinfo_path, // Source.
314 "/proc/cpuinfo", // Target.
315 nullptr, // FS type.
316 MS_BIND, // Mount flags: bind mount.
317 nullptr)) == -1) { // "Data."
Andreas Gampe04054e22014-09-25 22:33:01 -0700318 ALOGW("Failed to bind-mount %s as /proc/cpuinfo: %s", cpuinfo_path, strerror(errno));
jgu21ab0da5a2014-09-10 06:58:32 -0400319 }
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100320#else // __APPLE__
Andreas Gampe4390a632014-09-24 18:53:26 -0700321 UNUSED(instruction_set);
Andreas Gampe962eb402014-09-24 16:36:17 -0700322 ALOGW("Mac OS does not support bind-mounting. Host simulation of native bridge impossible.");
323#endif
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100324
325 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400326}
327
328static void SetCpuAbi(JNIEnv* env, jclass build_class, const char* field, const char* value) {
329 if (value != nullptr) {
330 jfieldID field_id = env->GetStaticFieldID(build_class, field, "Ljava/lang/String;");
331 if (field_id == nullptr) {
332 env->ExceptionClear();
333 ALOGW("Could not find %s field.", field);
334 return;
335 }
336
337 jstring str = env->NewStringUTF(value);
338 if (str == nullptr) {
339 env->ExceptionClear();
340 ALOGW("Could not create string %s.", value);
341 return;
342 }
343
344 env->SetStaticObjectField(build_class, field_id, str);
345 }
346}
347
jgu21ab0da5a2014-09-10 06:58:32 -0400348// Set up the environment for the bridged app.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700349static void SetupEnvironment(const NativeBridgeCallbacks* callbacks, JNIEnv* env, const char* isa) {
jgu21ab0da5a2014-09-10 06:58:32 -0400350 // Need a JNIEnv* to do anything.
351 if (env == nullptr) {
352 ALOGW("No JNIEnv* to set up app environment.");
353 return;
354 }
355
356 // Query the bridge for environment values.
357 const struct NativeBridgeRuntimeValues* env_values = callbacks->getAppEnv(isa);
358 if (env_values == nullptr) {
359 return;
360 }
361
362 // Keep the JNIEnv clean.
363 jint success = env->PushLocalFrame(16); // That should be small and large enough.
364 if (success < 0) {
365 // Out of memory, really borked.
366 ALOGW("Out of memory while setting up app environment.");
367 env->ExceptionClear();
368 return;
369 }
370
371 // Reset CPU_ABI & CPU_ABI2 to values required by the apps running with native bridge.
372 if (env_values->cpu_abi != nullptr || env_values->cpu_abi2 != nullptr ||
373 env_values->abi_count >= 0) {
374 jclass bclass_id = env->FindClass("android/os/Build");
375 if (bclass_id != nullptr) {
376 SetCpuAbi(env, bclass_id, "CPU_ABI", env_values->cpu_abi);
377 SetCpuAbi(env, bclass_id, "CPU_ABI2", env_values->cpu_abi2);
jgu21ab0da5a2014-09-10 06:58:32 -0400378 } else {
379 // For example in a host test environment.
380 env->ExceptionClear();
381 ALOGW("Could not find Build class.");
382 }
383 }
384
385 if (env_values->os_arch != nullptr) {
386 jclass sclass_id = env->FindClass("java/lang/System");
387 if (sclass_id != nullptr) {
Narayan Kamath484c55b2015-02-10 15:33:36 +0000388 jmethodID set_prop_id = env->GetStaticMethodID(sclass_id, "setUnchangeableSystemProperty",
Calin Juravlec3eb4312014-10-01 17:29:19 +0100389 "(Ljava/lang/String;Ljava/lang/String;)V");
jgu21ab0da5a2014-09-10 06:58:32 -0400390 if (set_prop_id != nullptr) {
Calin Juravlec3eb4312014-10-01 17:29:19 +0100391 // Init os.arch to the value reqired by the apps running with native bridge.
392 env->CallStaticVoidMethod(sclass_id, set_prop_id, env->NewStringUTF("os.arch"),
jgu21ab0da5a2014-09-10 06:58:32 -0400393 env->NewStringUTF(env_values->os_arch));
394 } else {
395 env->ExceptionClear();
Narayan Kamath484c55b2015-02-10 15:33:36 +0000396 ALOGW("Could not find System#setUnchangeableSystemProperty.");
jgu21ab0da5a2014-09-10 06:58:32 -0400397 }
398 } else {
399 env->ExceptionClear();
400 ALOGW("Could not find System class.");
401 }
402 }
403
404 // Make it pristine again.
405 env->PopLocalFrame(nullptr);
406}
407
408bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700409 // We expect only one place that calls InitializeNativeBridge: Runtime::DidForkFromZygote. At that
410 // point we are not multi-threaded, so we do not need locking here.
411
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100412 if (state == NativeBridgeState::kPreInitialized) {
413 // Check for code cache: if it doesn't exist try to create it.
414 struct stat st;
415 if (stat(app_code_cache_dir, &st) == -1) {
416 if (errno == ENOENT) {
417 if (mkdir(app_code_cache_dir, S_IRWXU | S_IRWXG | S_IXOTH) == -1) {
jgu21cef898f2015-07-02 12:02:11 +0800418 ALOGW("Cannot create code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
419 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100420 }
421 } else {
jgu21cef898f2015-07-02 12:02:11 +0800422 ALOGW("Cannot stat code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
423 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100424 }
425 } else if (!S_ISDIR(st.st_mode)) {
jgu21cef898f2015-07-02 12:02:11 +0800426 ALOGW("Code cache is not a directory %s.", app_code_cache_dir);
427 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100428 }
429
430 // If we're still PreInitialized (dind't fail the code cache checks) try to initialize.
431 if (state == NativeBridgeState::kPreInitialized) {
432 if (callbacks->initialize(runtime_callbacks, app_code_cache_dir, instruction_set)) {
433 SetupEnvironment(callbacks, env, instruction_set);
434 state = NativeBridgeState::kInitialized;
435 // We no longer need the code cache path, release the memory.
jgu21cef898f2015-07-02 12:02:11 +0800436 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100437 } else {
438 // Unload the library.
439 dlclose(native_bridge_handle);
440 CloseNativeBridge(true);
441 }
Calin Juravle961ae122014-08-11 16:11:59 +0100442 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700443 } else {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100444 CloseNativeBridge(true);
Calin Juravle961ae122014-08-11 16:11:59 +0100445 }
446
Andreas Gampe035bd752014-09-02 21:17:03 -0700447 return state == NativeBridgeState::kInitialized;
448}
Calin Juravle961ae122014-08-11 16:11:59 +0100449
Andreas Gampe035bd752014-09-02 21:17:03 -0700450void UnloadNativeBridge() {
451 // We expect only one place that calls UnloadNativeBridge: Runtime::DidForkFromZygote. At that
452 // point we are not multi-threaded, so we do not need locking here.
453
454 switch(state) {
455 case NativeBridgeState::kOpened:
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100456 case NativeBridgeState::kPreInitialized:
Andreas Gampe035bd752014-09-02 21:17:03 -0700457 case NativeBridgeState::kInitialized:
458 // Unload.
459 dlclose(native_bridge_handle);
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100460 CloseNativeBridge(false);
Andreas Gampe035bd752014-09-02 21:17:03 -0700461 break;
462
463 case NativeBridgeState::kNotSetup:
464 // Not even set up. Error.
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100465 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700466 break;
467
468 case NativeBridgeState::kClosed:
469 // Ignore.
470 break;
471 }
Calin Juravle961ae122014-08-11 16:11:59 +0100472}
473
Andreas Gampe049249c2014-08-19 22:31:31 -0700474bool NativeBridgeError() {
475 return had_error;
476}
477
478bool NativeBridgeAvailable() {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100479 return state == NativeBridgeState::kOpened
480 || state == NativeBridgeState::kPreInitialized
481 || state == NativeBridgeState::kInitialized;
Andreas Gampe035bd752014-09-02 21:17:03 -0700482}
483
484bool NativeBridgeInitialized() {
485 // Calls of this are supposed to happen in a state where the native bridge is stable, i.e., after
486 // Runtime::DidForkFromZygote. In that case we do not need a lock.
487 return state == NativeBridgeState::kInitialized;
Andreas Gampe049249c2014-08-19 22:31:31 -0700488}
489
Calin Juravle961ae122014-08-11 16:11:59 +0100490void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700491 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100492 return callbacks->loadLibrary(libpath, flag);
493 }
494 return nullptr;
495}
496
497void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty,
498 uint32_t len) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700499 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100500 return callbacks->getTrampoline(handle, name, shorty, len);
501 }
502 return nullptr;
503}
504
505bool NativeBridgeIsSupported(const char* libpath) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700506 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100507 return callbacks->isSupported(libpath);
508 }
509 return false;
510}
511
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700512uint32_t NativeBridgeGetVersion() {
513 if (NativeBridgeAvailable()) {
514 return callbacks->version;
515 }
516 return 0;
517}
518
519NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
520 if (NativeBridgeInitialized() && callbacks->version >= 2) {
521 return callbacks->getSignalHandler(signal);
522 }
523 return nullptr;
524}
525
Calin Juravle961ae122014-08-11 16:11:59 +0100526}; // namespace android