blob: ecfd719bce9a133c5d558aa4380ffa5490911b3a [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
jgu21ab0da5a2014-09-10 06:58:32 -040019#include <cstring>
Andreas Gampe049249c2014-08-19 22:31:31 -070020#include <cutils/log.h>
Calin Juravle961ae122014-08-11 16:11:59 +010021#include <dlfcn.h>
jgu21ab0da5a2014-09-10 06:58:32 -040022#include <errno.h>
23#include <fcntl.h>
Calin Juravle961ae122014-08-11 16:11:59 +010024#include <stdio.h>
jgu21ab0da5a2014-09-10 06:58:32 -040025#include <sys/mount.h>
26#include <sys/stat.h>
Calin Juravle961ae122014-08-11 16:11:59 +010027
28
29namespace android {
30
jgu21ab0da5a2014-09-10 06:58:32 -040031// Environment values required by the apps running with native bridge.
32struct NativeBridgeRuntimeValues {
33 const char* os_arch;
34 const char* cpu_abi;
35 const char* cpu_abi2;
36 const char* *supported_abis;
37 int32_t abi_count;
38};
39
Calin Juravle961ae122014-08-11 16:11:59 +010040// The symbol name exposed by native-bridge with the type of NativeBridgeCallbacks.
41static constexpr const char* kNativeBridgeInterfaceSymbol = "NativeBridgeItf";
42
Andreas Gampe035bd752014-09-02 21:17:03 -070043enum class NativeBridgeState {
44 kNotSetup, // Initial state.
45 kOpened, // After successful dlopen.
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010046 kPreInitialized, // After successful pre-initialization.
Andreas Gampe035bd752014-09-02 21:17:03 -070047 kInitialized, // After successful initialization.
48 kClosed // Closed or errors.
49};
Calin Juravle961ae122014-08-11 16:11:59 +010050
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010051static constexpr const char* kNotSetupString = "kNotSetup";
52static constexpr const char* kOpenedString = "kOpened";
53static constexpr const char* kPreInitializedString = "kPreInitialized";
54static constexpr const char* kInitializedString = "kInitialized";
55static constexpr const char* kClosedString = "kClosed";
Andreas Gampe035bd752014-09-02 21:17:03 -070056
57static const char* GetNativeBridgeStateString(NativeBridgeState state) {
58 switch (state) {
59 case NativeBridgeState::kNotSetup:
60 return kNotSetupString;
61
62 case NativeBridgeState::kOpened:
63 return kOpenedString;
64
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010065 case NativeBridgeState::kPreInitialized:
66 return kPreInitializedString;
67
Andreas Gampe035bd752014-09-02 21:17:03 -070068 case NativeBridgeState::kInitialized:
69 return kInitializedString;
70
71 case NativeBridgeState::kClosed:
72 return kClosedString;
73 }
74}
75
76// Current state of the native bridge.
77static NativeBridgeState state = NativeBridgeState::kNotSetup;
78
Andreas Gampe049249c2014-08-19 22:31:31 -070079// Whether we had an error at some point.
80static bool had_error = false;
Calin Juravle961ae122014-08-11 16:11:59 +010081
Andreas Gampe035bd752014-09-02 21:17:03 -070082// Handle of the loaded library.
83static void* native_bridge_handle = nullptr;
84// Pointer to the callbacks. Available as soon as LoadNativeBridge succeeds, but only initialized
85// later.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -070086static const NativeBridgeCallbacks* callbacks = nullptr;
Andreas Gampe035bd752014-09-02 21:17:03 -070087// Callbacks provided by the environment to the bridge. Passed to LoadNativeBridge.
Calin Juravle961ae122014-08-11 16:11:59 +010088static const NativeBridgeRuntimeCallbacks* runtime_callbacks = nullptr;
89
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010090// The app's code cache directory.
91static char* app_code_cache_dir = nullptr;
92
93// Code cache directory (relative to the application private directory)
94// Ideally we'd like to call into framework to retrieve this name. However that's considered an
95// implementation detail and will require either hacks or consistent refactorings. We compromise
96// and hard code the directory name again here.
97static constexpr const char* kCodeCacheDir = "code_cache";
jgu21ab0da5a2014-09-10 06:58:32 -040098
Andreas Gampea6ac9ce2015-04-30 20:39:12 -070099static constexpr uint32_t kLibNativeBridgeVersion = 2;
jgu21ab0da5a2014-09-10 06:58:32 -0400100
Andreas Gampe049249c2014-08-19 22:31:31 -0700101// Characters allowed in a native bridge filename. The first character must
102// be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
103static bool CharacterAllowed(char c, bool first) {
104 if (first) {
105 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
106 } else {
107 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
108 (c == '.') || (c == '_') || (c == '-');
109 }
110}
111
jgu21cef898f2015-07-02 12:02:11 +0800112static void ReleaseAppCodeCacheDir() {
113 if (app_code_cache_dir != nullptr) {
114 delete[] app_code_cache_dir;
115 app_code_cache_dir = nullptr;
116 }
117}
118
Andreas Gampe049249c2014-08-19 22:31:31 -0700119// We only allow simple names for the library. It is supposed to be a file in
120// /system/lib or /vendor/lib. Only allow a small range of characters, that is
121// names consisting of [a-zA-Z0-9._-] and starting with [a-zA-Z].
122bool NativeBridgeNameAcceptable(const char* nb_library_filename) {
123 const char* ptr = nb_library_filename;
124 if (*ptr == 0) {
125 // Emptry string. Allowed, means no native bridge.
126 return true;
127 } else {
128 // First character must be [a-zA-Z].
129 if (!CharacterAllowed(*ptr, true)) {
130 // Found an invalid fist character, don't accept.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700131 ALOGE("Native bridge library %s has been rejected for first character %c",
132 nb_library_filename,
133 *ptr);
Andreas Gampe049249c2014-08-19 22:31:31 -0700134 return false;
135 } else {
136 // For the rest, be more liberal.
137 ptr++;
138 while (*ptr != 0) {
139 if (!CharacterAllowed(*ptr, false)) {
140 // Found an invalid character, don't accept.
141 ALOGE("Native bridge library %s has been rejected for %c", nb_library_filename, *ptr);
142 return false;
143 }
144 ptr++;
145 }
146 }
147 return true;
148 }
149}
150
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700151static bool VersionCheck(const NativeBridgeCallbacks* cb) {
152 // Libnativebridge is now designed to be forward-compatible. So only "0" is an unsupported
153 // version.
154 if (cb == nullptr || cb->version == 0) {
155 return false;
156 }
157
158 // If this is a v2+ bridge, it may not be forwards- or backwards-compatible. Check.
159 if (cb->version >= 2) {
160 if (!callbacks->isCompatibleWith(kLibNativeBridgeVersion)) {
161 // TODO: Scan which version is supported, and fall back to handle it.
162 return false;
163 }
164 }
165
166 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400167}
168
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100169static void CloseNativeBridge(bool with_error) {
170 state = NativeBridgeState::kClosed;
171 had_error |= with_error;
jgu21cef898f2015-07-02 12:02:11 +0800172 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100173}
174
Andreas Gampe035bd752014-09-02 21:17:03 -0700175bool LoadNativeBridge(const char* nb_library_filename,
176 const NativeBridgeRuntimeCallbacks* runtime_cbs) {
177 // We expect only one place that calls LoadNativeBridge: Runtime::Init. At that point we are not
178 // multi-threaded, so we do not need locking here.
Calin Juravle961ae122014-08-11 16:11:59 +0100179
Andreas Gampe035bd752014-09-02 21:17:03 -0700180 if (state != NativeBridgeState::kNotSetup) {
Andreas Gampe049249c2014-08-19 22:31:31 -0700181 // Setup has been called before. Ignore this call.
jgu21ab0da5a2014-09-10 06:58:32 -0400182 if (nb_library_filename != nullptr) { // Avoids some log-spam for dalvikvm.
183 ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
184 GetNativeBridgeStateString(state));
185 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700186 // Note: counts as an error, even though the bridge may be functional.
187 had_error = true;
Andreas Gampe049249c2014-08-19 22:31:31 -0700188 return false;
189 }
190
Andreas Gampe035bd752014-09-02 21:17:03 -0700191 if (nb_library_filename == nullptr || *nb_library_filename == 0) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100192 CloseNativeBridge(false);
193 return false;
Andreas Gampe035bd752014-09-02 21:17:03 -0700194 } else {
195 if (!NativeBridgeNameAcceptable(nb_library_filename)) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100196 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700197 } else {
198 // Try to open the library.
199 void* handle = dlopen(nb_library_filename, RTLD_LAZY);
200 if (handle != nullptr) {
201 callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
202 kNativeBridgeInterfaceSymbol));
203 if (callbacks != nullptr) {
jgu21ab0da5a2014-09-10 06:58:32 -0400204 if (VersionCheck(callbacks)) {
205 // Store the handle for later.
206 native_bridge_handle = handle;
207 } else {
208 callbacks = nullptr;
209 dlclose(handle);
210 ALOGW("Unsupported native bridge interface.");
211 }
Andreas Gampe035bd752014-09-02 21:17:03 -0700212 } else {
213 dlclose(handle);
214 }
215 }
216
217 // Two failure conditions: could not find library (dlopen failed), or could not find native
218 // bridge interface (dlsym failed). Both are an error and close the native bridge.
219 if (callbacks == nullptr) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100220 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700221 } else {
222 runtime_callbacks = runtime_cbs;
223 state = NativeBridgeState::kOpened;
224 }
225 }
226 return state == NativeBridgeState::kOpened;
227 }
228}
229
jgu21ab0da5a2014-09-10 06:58:32 -0400230#if defined(__arm__)
231static const char* kRuntimeISA = "arm";
232#elif defined(__aarch64__)
233static const char* kRuntimeISA = "arm64";
Douglas Leungd10e0172015-05-19 17:30:08 -0700234#elif defined(__mips__) && !defined(__LP64__)
jgu21ab0da5a2014-09-10 06:58:32 -0400235static const char* kRuntimeISA = "mips";
Douglas Leungd10e0172015-05-19 17:30:08 -0700236#elif defined(__mips__) && defined(__LP64__)
237static const char* kRuntimeISA = "mips64";
jgu21ab0da5a2014-09-10 06:58:32 -0400238#elif defined(__i386__)
239static const char* kRuntimeISA = "x86";
240#elif defined(__x86_64__)
241static const char* kRuntimeISA = "x86_64";
242#else
243static const char* kRuntimeISA = "unknown";
244#endif
245
246
247bool NeedsNativeBridge(const char* instruction_set) {
Andreas Gampe04054e22014-09-25 22:33:01 -0700248 if (instruction_set == nullptr) {
249 ALOGE("Null instruction set in NeedsNativeBridge.");
250 return false;
251 }
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700252 return strncmp(instruction_set, kRuntimeISA, strlen(kRuntimeISA) + 1) != 0;
jgu21ab0da5a2014-09-10 06:58:32 -0400253}
254
Andreas Gampe4390a632014-09-24 18:53:26 -0700255#ifdef __APPLE__
256template<typename T> void UNUSED(const T&) {}
257#endif
258
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100259bool PreInitializeNativeBridge(const char* app_data_dir_in, const char* instruction_set) {
260 if (state != NativeBridgeState::kOpened) {
261 ALOGE("Invalid state: native bridge is expected to be opened.");
262 CloseNativeBridge(true);
263 return false;
jgu21ab0da5a2014-09-10 06:58:32 -0400264 }
265
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100266 if (app_data_dir_in == nullptr) {
267 ALOGE("Application private directory cannot be null.");
268 CloseNativeBridge(true);
269 return false;
270 }
271
272 // Create the path to the application code cache directory.
273 // The memory will be release after Initialization or when the native bridge is closed.
274 const size_t len = strlen(app_data_dir_in) + strlen(kCodeCacheDir) + 2; // '\0' + '/'
275 app_code_cache_dir = new char[len];
276 snprintf(app_code_cache_dir, len, "%s/%s", app_data_dir_in, kCodeCacheDir);
277
278 // Bind-mount /system/lib{,64}/<isa>/cpuinfo to /proc/cpuinfo.
279 // Failure is not fatal and will keep the native bridge in kPreInitialized.
280 state = NativeBridgeState::kPreInitialized;
jgu21ab0da5a2014-09-10 06:58:32 -0400281
Andreas Gampe962eb402014-09-24 16:36:17 -0700282#ifndef __APPLE__
jgu21ab0da5a2014-09-10 06:58:32 -0400283 if (instruction_set == nullptr) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100284 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400285 }
286 size_t isa_len = strlen(instruction_set);
287 if (isa_len > 10) {
288 // 10 is a loose upper bound on the currently known instruction sets (a tight bound is 7 for
289 // x86_64 [including the trailing \0]). This is so we don't have to change here if there will
290 // be another instruction set in the future.
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700291 ALOGW("Instruction set %s is malformed, must be less than or equal to 10 characters.",
292 instruction_set);
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100293 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400294 }
295
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100296 // If the file does not exist, the mount command will fail,
297 // so we save the extra file existence check.
jgu21ab0da5a2014-09-10 06:58:32 -0400298 char cpuinfo_path[1024];
299
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700300#if defined(__ANDROID__)
Andreas Gampe04054e22014-09-25 22:33:01 -0700301 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/lib"
jgu21ab0da5a2014-09-10 06:58:32 -0400302#ifdef __LP64__
Andreas Gampe04054e22014-09-25 22:33:01 -0700303 "64"
304#endif // __LP64__
305 "/%s/cpuinfo", instruction_set);
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700306#else // !__ANDROID__
Andreas Gampe04054e22014-09-25 22:33:01 -0700307 // To be able to test on the host, we hardwire a relative path.
308 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "./cpuinfo");
jgu21ab0da5a2014-09-10 06:58:32 -0400309#endif
jgu21ab0da5a2014-09-10 06:58:32 -0400310
311 // Bind-mount.
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700312 if (TEMP_FAILURE_RETRY(mount(cpuinfo_path, // Source.
313 "/proc/cpuinfo", // Target.
314 nullptr, // FS type.
315 MS_BIND, // Mount flags: bind mount.
316 nullptr)) == -1) { // "Data."
Andreas Gampe04054e22014-09-25 22:33:01 -0700317 ALOGW("Failed to bind-mount %s as /proc/cpuinfo: %s", cpuinfo_path, strerror(errno));
jgu21ab0da5a2014-09-10 06:58:32 -0400318 }
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100319#else // __APPLE__
Andreas Gampe4390a632014-09-24 18:53:26 -0700320 UNUSED(instruction_set);
Andreas Gampe962eb402014-09-24 16:36:17 -0700321 ALOGW("Mac OS does not support bind-mounting. Host simulation of native bridge impossible.");
322#endif
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100323
324 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400325}
326
327static void SetCpuAbi(JNIEnv* env, jclass build_class, const char* field, const char* value) {
328 if (value != nullptr) {
329 jfieldID field_id = env->GetStaticFieldID(build_class, field, "Ljava/lang/String;");
330 if (field_id == nullptr) {
331 env->ExceptionClear();
332 ALOGW("Could not find %s field.", field);
333 return;
334 }
335
336 jstring str = env->NewStringUTF(value);
337 if (str == nullptr) {
338 env->ExceptionClear();
339 ALOGW("Could not create string %s.", value);
340 return;
341 }
342
343 env->SetStaticObjectField(build_class, field_id, str);
344 }
345}
346
jgu21ab0da5a2014-09-10 06:58:32 -0400347// Set up the environment for the bridged app.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700348static void SetupEnvironment(const NativeBridgeCallbacks* callbacks, JNIEnv* env, const char* isa) {
jgu21ab0da5a2014-09-10 06:58:32 -0400349 // Need a JNIEnv* to do anything.
350 if (env == nullptr) {
351 ALOGW("No JNIEnv* to set up app environment.");
352 return;
353 }
354
355 // Query the bridge for environment values.
356 const struct NativeBridgeRuntimeValues* env_values = callbacks->getAppEnv(isa);
357 if (env_values == nullptr) {
358 return;
359 }
360
361 // Keep the JNIEnv clean.
362 jint success = env->PushLocalFrame(16); // That should be small and large enough.
363 if (success < 0) {
364 // Out of memory, really borked.
365 ALOGW("Out of memory while setting up app environment.");
366 env->ExceptionClear();
367 return;
368 }
369
370 // Reset CPU_ABI & CPU_ABI2 to values required by the apps running with native bridge.
371 if (env_values->cpu_abi != nullptr || env_values->cpu_abi2 != nullptr ||
372 env_values->abi_count >= 0) {
373 jclass bclass_id = env->FindClass("android/os/Build");
374 if (bclass_id != nullptr) {
375 SetCpuAbi(env, bclass_id, "CPU_ABI", env_values->cpu_abi);
376 SetCpuAbi(env, bclass_id, "CPU_ABI2", env_values->cpu_abi2);
jgu21ab0da5a2014-09-10 06:58:32 -0400377 } else {
378 // For example in a host test environment.
379 env->ExceptionClear();
380 ALOGW("Could not find Build class.");
381 }
382 }
383
384 if (env_values->os_arch != nullptr) {
385 jclass sclass_id = env->FindClass("java/lang/System");
386 if (sclass_id != nullptr) {
Narayan Kamath484c55b2015-02-10 15:33:36 +0000387 jmethodID set_prop_id = env->GetStaticMethodID(sclass_id, "setUnchangeableSystemProperty",
Calin Juravlec3eb4312014-10-01 17:29:19 +0100388 "(Ljava/lang/String;Ljava/lang/String;)V");
jgu21ab0da5a2014-09-10 06:58:32 -0400389 if (set_prop_id != nullptr) {
Calin Juravlec3eb4312014-10-01 17:29:19 +0100390 // Init os.arch to the value reqired by the apps running with native bridge.
391 env->CallStaticVoidMethod(sclass_id, set_prop_id, env->NewStringUTF("os.arch"),
jgu21ab0da5a2014-09-10 06:58:32 -0400392 env->NewStringUTF(env_values->os_arch));
393 } else {
394 env->ExceptionClear();
Narayan Kamath484c55b2015-02-10 15:33:36 +0000395 ALOGW("Could not find System#setUnchangeableSystemProperty.");
jgu21ab0da5a2014-09-10 06:58:32 -0400396 }
397 } else {
398 env->ExceptionClear();
399 ALOGW("Could not find System class.");
400 }
401 }
402
403 // Make it pristine again.
404 env->PopLocalFrame(nullptr);
405}
406
407bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700408 // We expect only one place that calls InitializeNativeBridge: Runtime::DidForkFromZygote. At that
409 // point we are not multi-threaded, so we do not need locking here.
410
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100411 if (state == NativeBridgeState::kPreInitialized) {
412 // Check for code cache: if it doesn't exist try to create it.
413 struct stat st;
414 if (stat(app_code_cache_dir, &st) == -1) {
415 if (errno == ENOENT) {
416 if (mkdir(app_code_cache_dir, S_IRWXU | S_IRWXG | S_IXOTH) == -1) {
jgu21cef898f2015-07-02 12:02:11 +0800417 ALOGW("Cannot create code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
418 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100419 }
420 } else {
jgu21cef898f2015-07-02 12:02:11 +0800421 ALOGW("Cannot stat code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
422 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100423 }
424 } else if (!S_ISDIR(st.st_mode)) {
jgu21cef898f2015-07-02 12:02:11 +0800425 ALOGW("Code cache is not a directory %s.", app_code_cache_dir);
426 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100427 }
428
429 // If we're still PreInitialized (dind't fail the code cache checks) try to initialize.
430 if (state == NativeBridgeState::kPreInitialized) {
431 if (callbacks->initialize(runtime_callbacks, app_code_cache_dir, instruction_set)) {
432 SetupEnvironment(callbacks, env, instruction_set);
433 state = NativeBridgeState::kInitialized;
434 // We no longer need the code cache path, release the memory.
jgu21cef898f2015-07-02 12:02:11 +0800435 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100436 } else {
437 // Unload the library.
438 dlclose(native_bridge_handle);
439 CloseNativeBridge(true);
440 }
Calin Juravle961ae122014-08-11 16:11:59 +0100441 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700442 } else {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100443 CloseNativeBridge(true);
Calin Juravle961ae122014-08-11 16:11:59 +0100444 }
445
Andreas Gampe035bd752014-09-02 21:17:03 -0700446 return state == NativeBridgeState::kInitialized;
447}
Calin Juravle961ae122014-08-11 16:11:59 +0100448
Andreas Gampe035bd752014-09-02 21:17:03 -0700449void UnloadNativeBridge() {
450 // We expect only one place that calls UnloadNativeBridge: Runtime::DidForkFromZygote. At that
451 // point we are not multi-threaded, so we do not need locking here.
452
453 switch(state) {
454 case NativeBridgeState::kOpened:
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100455 case NativeBridgeState::kPreInitialized:
Andreas Gampe035bd752014-09-02 21:17:03 -0700456 case NativeBridgeState::kInitialized:
457 // Unload.
458 dlclose(native_bridge_handle);
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100459 CloseNativeBridge(false);
Andreas Gampe035bd752014-09-02 21:17:03 -0700460 break;
461
462 case NativeBridgeState::kNotSetup:
463 // Not even set up. Error.
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100464 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700465 break;
466
467 case NativeBridgeState::kClosed:
468 // Ignore.
469 break;
470 }
Calin Juravle961ae122014-08-11 16:11:59 +0100471}
472
Andreas Gampe049249c2014-08-19 22:31:31 -0700473bool NativeBridgeError() {
474 return had_error;
475}
476
477bool NativeBridgeAvailable() {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100478 return state == NativeBridgeState::kOpened
479 || state == NativeBridgeState::kPreInitialized
480 || state == NativeBridgeState::kInitialized;
Andreas Gampe035bd752014-09-02 21:17:03 -0700481}
482
483bool NativeBridgeInitialized() {
484 // Calls of this are supposed to happen in a state where the native bridge is stable, i.e., after
485 // Runtime::DidForkFromZygote. In that case we do not need a lock.
486 return state == NativeBridgeState::kInitialized;
Andreas Gampe049249c2014-08-19 22:31:31 -0700487}
488
Calin Juravle961ae122014-08-11 16:11:59 +0100489void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700490 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100491 return callbacks->loadLibrary(libpath, flag);
492 }
493 return nullptr;
494}
495
496void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty,
497 uint32_t len) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700498 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100499 return callbacks->getTrampoline(handle, name, shorty, len);
500 }
501 return nullptr;
502}
503
504bool NativeBridgeIsSupported(const char* libpath) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700505 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100506 return callbacks->isSupported(libpath);
507 }
508 return false;
509}
510
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700511uint32_t NativeBridgeGetVersion() {
512 if (NativeBridgeAvailable()) {
513 return callbacks->version;
514 }
515 return 0;
516}
517
518NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
519 if (NativeBridgeInitialized() && callbacks->version >= 2) {
520 return callbacks->getSignalHandler(signal);
521 }
522 return nullptr;
523}
524
Calin Juravle961ae122014-08-11 16:11:59 +0100525}; // namespace android