blob: eafc53d8d344ae2534c4d700621e3f371a8b9447 [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
Mark Salyzyncfd5b082016-10-17 14:28:00 -070017#define LOG_TAG "nativebridge"
18
Calin Juravle961ae122014-08-11 16:11:59 +010019#include "nativebridge/native_bridge.h"
20
21#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>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070027#include <unistd.h>
Calin Juravle961ae122014-08-11 16:11:59 +010028
Mark Salyzyn66ce3e02016-09-28 10:07:20 -070029#include <cstring>
30
31#include <android/log.h>
Calin Juravle961ae122014-08-11 16:11:59 +010032
33namespace android {
34
jgu21ab0da5a2014-09-10 06:58:32 -040035// Environment values required by the apps running with native bridge.
36struct NativeBridgeRuntimeValues {
37 const char* os_arch;
38 const char* cpu_abi;
39 const char* cpu_abi2;
40 const char* *supported_abis;
41 int32_t abi_count;
42};
43
Calin Juravle961ae122014-08-11 16:11:59 +010044// The symbol name exposed by native-bridge with the type of NativeBridgeCallbacks.
45static constexpr const char* kNativeBridgeInterfaceSymbol = "NativeBridgeItf";
46
Andreas Gampe035bd752014-09-02 21:17:03 -070047enum class NativeBridgeState {
48 kNotSetup, // Initial state.
49 kOpened, // After successful dlopen.
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010050 kPreInitialized, // After successful pre-initialization.
Andreas Gampe035bd752014-09-02 21:17:03 -070051 kInitialized, // After successful initialization.
52 kClosed // Closed or errors.
53};
Calin Juravle961ae122014-08-11 16:11:59 +010054
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010055static constexpr const char* kNotSetupString = "kNotSetup";
56static constexpr const char* kOpenedString = "kOpened";
57static constexpr const char* kPreInitializedString = "kPreInitialized";
58static constexpr const char* kInitializedString = "kInitialized";
59static constexpr const char* kClosedString = "kClosed";
Andreas Gampe035bd752014-09-02 21:17:03 -070060
61static const char* GetNativeBridgeStateString(NativeBridgeState state) {
62 switch (state) {
63 case NativeBridgeState::kNotSetup:
64 return kNotSetupString;
65
66 case NativeBridgeState::kOpened:
67 return kOpenedString;
68
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010069 case NativeBridgeState::kPreInitialized:
70 return kPreInitializedString;
71
Andreas Gampe035bd752014-09-02 21:17:03 -070072 case NativeBridgeState::kInitialized:
73 return kInitializedString;
74
75 case NativeBridgeState::kClosed:
76 return kClosedString;
77 }
78}
79
80// Current state of the native bridge.
81static NativeBridgeState state = NativeBridgeState::kNotSetup;
82
Zhenhua WANGf2804e52016-05-30 11:16:08 +080083// The version of NativeBridge implementation.
84// Different Nativebridge interface needs the service of different version of
85// Nativebridge implementation.
86// Used by isCompatibleWith() which is introduced in v2.
87enum NativeBridgeImplementationVersion {
88 // first version, not used.
89 DEFAULT_VERSION = 1,
90 // The version which signal semantic is introduced.
91 SIGNAL_VERSION = 2,
92 // The version which namespace semantic is introduced.
93 NAMESPACE_VERSION = 3,
94};
95
Andreas Gampe049249c2014-08-19 22:31:31 -070096// Whether we had an error at some point.
97static bool had_error = false;
Calin Juravle961ae122014-08-11 16:11:59 +010098
Andreas Gampe035bd752014-09-02 21:17:03 -070099// Handle of the loaded library.
100static void* native_bridge_handle = nullptr;
101// Pointer to the callbacks. Available as soon as LoadNativeBridge succeeds, but only initialized
102// later.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700103static const NativeBridgeCallbacks* callbacks = nullptr;
Andreas Gampe035bd752014-09-02 21:17:03 -0700104// Callbacks provided by the environment to the bridge. Passed to LoadNativeBridge.
Calin Juravle961ae122014-08-11 16:11:59 +0100105static const NativeBridgeRuntimeCallbacks* runtime_callbacks = nullptr;
106
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100107// The app's code cache directory.
108static char* app_code_cache_dir = nullptr;
109
110// Code cache directory (relative to the application private directory)
111// Ideally we'd like to call into framework to retrieve this name. However that's considered an
112// implementation detail and will require either hacks or consistent refactorings. We compromise
113// and hard code the directory name again here.
114static constexpr const char* kCodeCacheDir = "code_cache";
jgu21ab0da5a2014-09-10 06:58:32 -0400115
Andreas Gampe049249c2014-08-19 22:31:31 -0700116// Characters allowed in a native bridge filename. The first character must
117// be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
118static bool CharacterAllowed(char c, bool first) {
119 if (first) {
120 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
121 } else {
122 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
123 (c == '.') || (c == '_') || (c == '-');
124 }
125}
126
jgu21cef898f2015-07-02 12:02:11 +0800127static void ReleaseAppCodeCacheDir() {
128 if (app_code_cache_dir != nullptr) {
129 delete[] app_code_cache_dir;
130 app_code_cache_dir = nullptr;
131 }
132}
133
Andreas Gampe049249c2014-08-19 22:31:31 -0700134// We only allow simple names for the library. It is supposed to be a file in
135// /system/lib or /vendor/lib. Only allow a small range of characters, that is
136// names consisting of [a-zA-Z0-9._-] and starting with [a-zA-Z].
137bool NativeBridgeNameAcceptable(const char* nb_library_filename) {
138 const char* ptr = nb_library_filename;
139 if (*ptr == 0) {
140 // Emptry string. Allowed, means no native bridge.
141 return true;
142 } else {
143 // First character must be [a-zA-Z].
144 if (!CharacterAllowed(*ptr, true)) {
145 // Found an invalid fist character, don't accept.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700146 ALOGE("Native bridge library %s has been rejected for first character %c",
147 nb_library_filename,
148 *ptr);
Andreas Gampe049249c2014-08-19 22:31:31 -0700149 return false;
150 } else {
151 // For the rest, be more liberal.
152 ptr++;
153 while (*ptr != 0) {
154 if (!CharacterAllowed(*ptr, false)) {
155 // Found an invalid character, don't accept.
156 ALOGE("Native bridge library %s has been rejected for %c", nb_library_filename, *ptr);
157 return false;
158 }
159 ptr++;
160 }
161 }
162 return true;
163 }
164}
165
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800166// The policy of invoking Nativebridge changed in v3 with/without namespace.
167// Suggest Nativebridge implementation not maintain backward-compatible.
168static bool isCompatibleWith(const uint32_t version) {
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700169 // Libnativebridge is now designed to be forward-compatible. So only "0" is an unsupported
170 // version.
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800171 if (callbacks == nullptr || callbacks->version == 0 || version == 0) {
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700172 return false;
173 }
174
175 // If this is a v2+ bridge, it may not be forwards- or backwards-compatible. Check.
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800176 if (callbacks->version >= SIGNAL_VERSION) {
177 return callbacks->isCompatibleWith(version);
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700178 }
179
180 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400181}
182
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100183static void CloseNativeBridge(bool with_error) {
184 state = NativeBridgeState::kClosed;
185 had_error |= with_error;
jgu21cef898f2015-07-02 12:02:11 +0800186 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100187}
188
Andreas Gampe035bd752014-09-02 21:17:03 -0700189bool LoadNativeBridge(const char* nb_library_filename,
190 const NativeBridgeRuntimeCallbacks* runtime_cbs) {
191 // We expect only one place that calls LoadNativeBridge: Runtime::Init. At that point we are not
192 // multi-threaded, so we do not need locking here.
Calin Juravle961ae122014-08-11 16:11:59 +0100193
Andreas Gampe035bd752014-09-02 21:17:03 -0700194 if (state != NativeBridgeState::kNotSetup) {
Andreas Gampe049249c2014-08-19 22:31:31 -0700195 // Setup has been called before. Ignore this call.
jgu21ab0da5a2014-09-10 06:58:32 -0400196 if (nb_library_filename != nullptr) { // Avoids some log-spam for dalvikvm.
197 ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
198 GetNativeBridgeStateString(state));
199 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700200 // Note: counts as an error, even though the bridge may be functional.
201 had_error = true;
Andreas Gampe049249c2014-08-19 22:31:31 -0700202 return false;
203 }
204
Andreas Gampe035bd752014-09-02 21:17:03 -0700205 if (nb_library_filename == nullptr || *nb_library_filename == 0) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100206 CloseNativeBridge(false);
207 return false;
Andreas Gampe035bd752014-09-02 21:17:03 -0700208 } else {
209 if (!NativeBridgeNameAcceptable(nb_library_filename)) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100210 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700211 } else {
212 // Try to open the library.
213 void* handle = dlopen(nb_library_filename, RTLD_LAZY);
214 if (handle != nullptr) {
215 callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
216 kNativeBridgeInterfaceSymbol));
217 if (callbacks != nullptr) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800218 if (isCompatibleWith(NAMESPACE_VERSION)) {
jgu21ab0da5a2014-09-10 06:58:32 -0400219 // Store the handle for later.
220 native_bridge_handle = handle;
221 } else {
222 callbacks = nullptr;
223 dlclose(handle);
224 ALOGW("Unsupported native bridge interface.");
225 }
Andreas Gampe035bd752014-09-02 21:17:03 -0700226 } else {
227 dlclose(handle);
228 }
229 }
230
231 // Two failure conditions: could not find library (dlopen failed), or could not find native
232 // bridge interface (dlsym failed). Both are an error and close the native bridge.
233 if (callbacks == nullptr) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100234 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700235 } else {
236 runtime_callbacks = runtime_cbs;
237 state = NativeBridgeState::kOpened;
238 }
239 }
240 return state == NativeBridgeState::kOpened;
241 }
242}
243
jgu21ab0da5a2014-09-10 06:58:32 -0400244#if defined(__arm__)
245static const char* kRuntimeISA = "arm";
246#elif defined(__aarch64__)
247static const char* kRuntimeISA = "arm64";
Douglas Leungd10e0172015-05-19 17:30:08 -0700248#elif defined(__mips__) && !defined(__LP64__)
jgu21ab0da5a2014-09-10 06:58:32 -0400249static const char* kRuntimeISA = "mips";
Douglas Leungd10e0172015-05-19 17:30:08 -0700250#elif defined(__mips__) && defined(__LP64__)
251static const char* kRuntimeISA = "mips64";
jgu21ab0da5a2014-09-10 06:58:32 -0400252#elif defined(__i386__)
253static const char* kRuntimeISA = "x86";
254#elif defined(__x86_64__)
255static const char* kRuntimeISA = "x86_64";
256#else
257static const char* kRuntimeISA = "unknown";
258#endif
259
260
261bool NeedsNativeBridge(const char* instruction_set) {
Andreas Gampe04054e22014-09-25 22:33:01 -0700262 if (instruction_set == nullptr) {
263 ALOGE("Null instruction set in NeedsNativeBridge.");
264 return false;
265 }
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700266 return strncmp(instruction_set, kRuntimeISA, strlen(kRuntimeISA) + 1) != 0;
jgu21ab0da5a2014-09-10 06:58:32 -0400267}
268
Andreas Gampe4390a632014-09-24 18:53:26 -0700269#ifdef __APPLE__
270template<typename T> void UNUSED(const T&) {}
271#endif
272
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100273bool PreInitializeNativeBridge(const char* app_data_dir_in, const char* instruction_set) {
274 if (state != NativeBridgeState::kOpened) {
275 ALOGE("Invalid state: native bridge is expected to be opened.");
276 CloseNativeBridge(true);
277 return false;
jgu21ab0da5a2014-09-10 06:58:32 -0400278 }
279
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100280 if (app_data_dir_in == nullptr) {
281 ALOGE("Application private directory cannot be null.");
282 CloseNativeBridge(true);
283 return false;
284 }
285
286 // Create the path to the application code cache directory.
287 // The memory will be release after Initialization or when the native bridge is closed.
288 const size_t len = strlen(app_data_dir_in) + strlen(kCodeCacheDir) + 2; // '\0' + '/'
289 app_code_cache_dir = new char[len];
290 snprintf(app_code_cache_dir, len, "%s/%s", app_data_dir_in, kCodeCacheDir);
291
292 // Bind-mount /system/lib{,64}/<isa>/cpuinfo to /proc/cpuinfo.
293 // Failure is not fatal and will keep the native bridge in kPreInitialized.
294 state = NativeBridgeState::kPreInitialized;
jgu21ab0da5a2014-09-10 06:58:32 -0400295
Andreas Gampe962eb402014-09-24 16:36:17 -0700296#ifndef __APPLE__
jgu21ab0da5a2014-09-10 06:58:32 -0400297 if (instruction_set == nullptr) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100298 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400299 }
300 size_t isa_len = strlen(instruction_set);
301 if (isa_len > 10) {
302 // 10 is a loose upper bound on the currently known instruction sets (a tight bound is 7 for
303 // x86_64 [including the trailing \0]). This is so we don't have to change here if there will
304 // be another instruction set in the future.
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700305 ALOGW("Instruction set %s is malformed, must be less than or equal to 10 characters.",
306 instruction_set);
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100307 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400308 }
309
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100310 // If the file does not exist, the mount command will fail,
311 // so we save the extra file existence check.
jgu21ab0da5a2014-09-10 06:58:32 -0400312 char cpuinfo_path[1024];
313
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700314#if defined(__ANDROID__)
Andreas Gampe04054e22014-09-25 22:33:01 -0700315 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/lib"
jgu21ab0da5a2014-09-10 06:58:32 -0400316#ifdef __LP64__
Andreas Gampe04054e22014-09-25 22:33:01 -0700317 "64"
318#endif // __LP64__
319 "/%s/cpuinfo", instruction_set);
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700320#else // !__ANDROID__
Andreas Gampe04054e22014-09-25 22:33:01 -0700321 // To be able to test on the host, we hardwire a relative path.
322 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "./cpuinfo");
jgu21ab0da5a2014-09-10 06:58:32 -0400323#endif
jgu21ab0da5a2014-09-10 06:58:32 -0400324
325 // Bind-mount.
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700326 if (TEMP_FAILURE_RETRY(mount(cpuinfo_path, // Source.
327 "/proc/cpuinfo", // Target.
328 nullptr, // FS type.
329 MS_BIND, // Mount flags: bind mount.
330 nullptr)) == -1) { // "Data."
Andreas Gampe04054e22014-09-25 22:33:01 -0700331 ALOGW("Failed to bind-mount %s as /proc/cpuinfo: %s", cpuinfo_path, strerror(errno));
jgu21ab0da5a2014-09-10 06:58:32 -0400332 }
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100333#else // __APPLE__
Andreas Gampe4390a632014-09-24 18:53:26 -0700334 UNUSED(instruction_set);
Andreas Gampe962eb402014-09-24 16:36:17 -0700335 ALOGW("Mac OS does not support bind-mounting. Host simulation of native bridge impossible.");
336#endif
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100337
338 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400339}
340
341static void SetCpuAbi(JNIEnv* env, jclass build_class, const char* field, const char* value) {
342 if (value != nullptr) {
343 jfieldID field_id = env->GetStaticFieldID(build_class, field, "Ljava/lang/String;");
344 if (field_id == nullptr) {
345 env->ExceptionClear();
346 ALOGW("Could not find %s field.", field);
347 return;
348 }
349
350 jstring str = env->NewStringUTF(value);
351 if (str == nullptr) {
352 env->ExceptionClear();
353 ALOGW("Could not create string %s.", value);
354 return;
355 }
356
357 env->SetStaticObjectField(build_class, field_id, str);
358 }
359}
360
jgu21ab0da5a2014-09-10 06:58:32 -0400361// Set up the environment for the bridged app.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700362static void SetupEnvironment(const NativeBridgeCallbacks* callbacks, JNIEnv* env, const char* isa) {
jgu21ab0da5a2014-09-10 06:58:32 -0400363 // Need a JNIEnv* to do anything.
364 if (env == nullptr) {
365 ALOGW("No JNIEnv* to set up app environment.");
366 return;
367 }
368
369 // Query the bridge for environment values.
370 const struct NativeBridgeRuntimeValues* env_values = callbacks->getAppEnv(isa);
371 if (env_values == nullptr) {
372 return;
373 }
374
375 // Keep the JNIEnv clean.
376 jint success = env->PushLocalFrame(16); // That should be small and large enough.
377 if (success < 0) {
378 // Out of memory, really borked.
379 ALOGW("Out of memory while setting up app environment.");
380 env->ExceptionClear();
381 return;
382 }
383
384 // Reset CPU_ABI & CPU_ABI2 to values required by the apps running with native bridge.
385 if (env_values->cpu_abi != nullptr || env_values->cpu_abi2 != nullptr ||
386 env_values->abi_count >= 0) {
387 jclass bclass_id = env->FindClass("android/os/Build");
388 if (bclass_id != nullptr) {
389 SetCpuAbi(env, bclass_id, "CPU_ABI", env_values->cpu_abi);
390 SetCpuAbi(env, bclass_id, "CPU_ABI2", env_values->cpu_abi2);
jgu21ab0da5a2014-09-10 06:58:32 -0400391 } else {
392 // For example in a host test environment.
393 env->ExceptionClear();
394 ALOGW("Could not find Build class.");
395 }
396 }
397
398 if (env_values->os_arch != nullptr) {
399 jclass sclass_id = env->FindClass("java/lang/System");
400 if (sclass_id != nullptr) {
Narayan Kamath484c55b2015-02-10 15:33:36 +0000401 jmethodID set_prop_id = env->GetStaticMethodID(sclass_id, "setUnchangeableSystemProperty",
Calin Juravlec3eb4312014-10-01 17:29:19 +0100402 "(Ljava/lang/String;Ljava/lang/String;)V");
jgu21ab0da5a2014-09-10 06:58:32 -0400403 if (set_prop_id != nullptr) {
Calin Juravlec3eb4312014-10-01 17:29:19 +0100404 // Init os.arch to the value reqired by the apps running with native bridge.
405 env->CallStaticVoidMethod(sclass_id, set_prop_id, env->NewStringUTF("os.arch"),
jgu21ab0da5a2014-09-10 06:58:32 -0400406 env->NewStringUTF(env_values->os_arch));
407 } else {
408 env->ExceptionClear();
Narayan Kamath484c55b2015-02-10 15:33:36 +0000409 ALOGW("Could not find System#setUnchangeableSystemProperty.");
jgu21ab0da5a2014-09-10 06:58:32 -0400410 }
411 } else {
412 env->ExceptionClear();
413 ALOGW("Could not find System class.");
414 }
415 }
416
417 // Make it pristine again.
418 env->PopLocalFrame(nullptr);
419}
420
421bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700422 // We expect only one place that calls InitializeNativeBridge: Runtime::DidForkFromZygote. At that
423 // point we are not multi-threaded, so we do not need locking here.
424
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100425 if (state == NativeBridgeState::kPreInitialized) {
426 // Check for code cache: if it doesn't exist try to create it.
427 struct stat st;
428 if (stat(app_code_cache_dir, &st) == -1) {
429 if (errno == ENOENT) {
430 if (mkdir(app_code_cache_dir, S_IRWXU | S_IRWXG | S_IXOTH) == -1) {
jgu21cef898f2015-07-02 12:02:11 +0800431 ALOGW("Cannot create code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
432 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100433 }
434 } else {
jgu21cef898f2015-07-02 12:02:11 +0800435 ALOGW("Cannot stat code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
436 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100437 }
438 } else if (!S_ISDIR(st.st_mode)) {
jgu21cef898f2015-07-02 12:02:11 +0800439 ALOGW("Code cache is not a directory %s.", app_code_cache_dir);
440 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100441 }
442
443 // If we're still PreInitialized (dind't fail the code cache checks) try to initialize.
444 if (state == NativeBridgeState::kPreInitialized) {
445 if (callbacks->initialize(runtime_callbacks, app_code_cache_dir, instruction_set)) {
446 SetupEnvironment(callbacks, env, instruction_set);
447 state = NativeBridgeState::kInitialized;
448 // We no longer need the code cache path, release the memory.
jgu21cef898f2015-07-02 12:02:11 +0800449 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100450 } else {
451 // Unload the library.
452 dlclose(native_bridge_handle);
453 CloseNativeBridge(true);
454 }
Calin Juravle961ae122014-08-11 16:11:59 +0100455 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700456 } else {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100457 CloseNativeBridge(true);
Calin Juravle961ae122014-08-11 16:11:59 +0100458 }
459
Andreas Gampe035bd752014-09-02 21:17:03 -0700460 return state == NativeBridgeState::kInitialized;
461}
Calin Juravle961ae122014-08-11 16:11:59 +0100462
Andreas Gampe035bd752014-09-02 21:17:03 -0700463void UnloadNativeBridge() {
464 // We expect only one place that calls UnloadNativeBridge: Runtime::DidForkFromZygote. At that
465 // point we are not multi-threaded, so we do not need locking here.
466
467 switch(state) {
468 case NativeBridgeState::kOpened:
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100469 case NativeBridgeState::kPreInitialized:
Andreas Gampe035bd752014-09-02 21:17:03 -0700470 case NativeBridgeState::kInitialized:
471 // Unload.
472 dlclose(native_bridge_handle);
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100473 CloseNativeBridge(false);
Andreas Gampe035bd752014-09-02 21:17:03 -0700474 break;
475
476 case NativeBridgeState::kNotSetup:
477 // Not even set up. Error.
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100478 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700479 break;
480
481 case NativeBridgeState::kClosed:
482 // Ignore.
483 break;
484 }
Calin Juravle961ae122014-08-11 16:11:59 +0100485}
486
Andreas Gampe049249c2014-08-19 22:31:31 -0700487bool NativeBridgeError() {
488 return had_error;
489}
490
491bool NativeBridgeAvailable() {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100492 return state == NativeBridgeState::kOpened
493 || state == NativeBridgeState::kPreInitialized
494 || state == NativeBridgeState::kInitialized;
Andreas Gampe035bd752014-09-02 21:17:03 -0700495}
496
497bool NativeBridgeInitialized() {
498 // Calls of this are supposed to happen in a state where the native bridge is stable, i.e., after
499 // Runtime::DidForkFromZygote. In that case we do not need a lock.
500 return state == NativeBridgeState::kInitialized;
Andreas Gampe049249c2014-08-19 22:31:31 -0700501}
502
Calin Juravle961ae122014-08-11 16:11:59 +0100503void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700504 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100505 return callbacks->loadLibrary(libpath, flag);
506 }
507 return nullptr;
508}
509
510void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty,
511 uint32_t len) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700512 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100513 return callbacks->getTrampoline(handle, name, shorty, len);
514 }
515 return nullptr;
516}
517
518bool NativeBridgeIsSupported(const char* libpath) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700519 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100520 return callbacks->isSupported(libpath);
521 }
522 return false;
523}
524
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700525uint32_t NativeBridgeGetVersion() {
526 if (NativeBridgeAvailable()) {
527 return callbacks->version;
528 }
529 return 0;
530}
531
532NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800533 if (NativeBridgeInitialized()) {
534 if (isCompatibleWith(SIGNAL_VERSION)) {
535 return callbacks->getSignalHandler(signal);
536 } else {
537 ALOGE("not compatible with version %d, cannot get signal handler", SIGNAL_VERSION);
538 }
539 }
540 return nullptr;
541}
542
543int NativeBridgeUnloadLibrary(void* handle) {
544 if (NativeBridgeInitialized()) {
545 if (isCompatibleWith(NAMESPACE_VERSION)) {
546 return callbacks->unloadLibrary(handle);
547 } else {
548 ALOGE("not compatible with version %d, cannot unload library", NAMESPACE_VERSION);
549 }
550 }
551 return -1;
552}
553
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700554const char* NativeBridgeGetError() {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800555 if (NativeBridgeInitialized()) {
556 if (isCompatibleWith(NAMESPACE_VERSION)) {
557 return callbacks->getError();
558 } else {
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700559 return "native bridge implementation is not compatible with version 3, cannot get message";
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800560 }
561 }
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700562 return "native bridge is not initialized";
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800563}
564
565bool NativeBridgeIsPathSupported(const char* path) {
566 if (NativeBridgeInitialized()) {
567 if (isCompatibleWith(NAMESPACE_VERSION)) {
568 return callbacks->isPathSupported(path);
569 } else {
570 ALOGE("not compatible with version %d, cannot check via library path", NAMESPACE_VERSION);
571 }
572 }
573 return false;
574}
575
576bool NativeBridgeInitNamespace(const char* public_ns_sonames,
577 const char* anon_ns_library_path) {
578 if (NativeBridgeInitialized()) {
579 if (isCompatibleWith(NAMESPACE_VERSION)) {
580 return callbacks->initNamespace(public_ns_sonames, anon_ns_library_path);
581 } else {
582 ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
583 }
584 }
585
586 return false;
587}
588
589native_bridge_namespace_t* NativeBridgeCreateNamespace(const char* name,
590 const char* ld_library_path,
591 const char* default_library_path,
592 uint64_t type,
593 const char* permitted_when_isolated_path,
594 native_bridge_namespace_t* parent_ns) {
595 if (NativeBridgeInitialized()) {
596 if (isCompatibleWith(NAMESPACE_VERSION)) {
597 return callbacks->createNamespace(name,
598 ld_library_path,
599 default_library_path,
600 type,
601 permitted_when_isolated_path,
602 parent_ns);
603 } else {
604 ALOGE("not compatible with version %d, cannot create namespace %s", NAMESPACE_VERSION, name);
605 }
606 }
607
608 return nullptr;
609}
610
611void* NativeBridgeLoadLibraryExt(const char* libpath, int flag, native_bridge_namespace_t* ns) {
612 if (NativeBridgeInitialized()) {
613 if (isCompatibleWith(NAMESPACE_VERSION)) {
614 return callbacks->loadLibraryExt(libpath, flag, ns);
615 } else {
616 ALOGE("not compatible with version %d, cannot load library in namespace", NAMESPACE_VERSION);
617 }
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700618 }
619 return nullptr;
620}
621
Calin Juravle961ae122014-08-11 16:11:59 +0100622}; // namespace android