blob: 9997b2a1b96c447b7cc5dce85a697c7a5e866f6d [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
dimitryb6ba8172017-08-23 10:25:22 +020031#include <android-base/macros.h>
Mark Salyzyn30f991f2017-01-10 13:19:54 -080032#include <log/log.h>
Calin Juravle961ae122014-08-11 16:11:59 +010033
34namespace android {
35
Nicolas Geoffrayd9b4d9b2019-01-10 16:27:54 +000036extern "C" {
37
jgu21ab0da5a2014-09-10 06:58:32 -040038// Environment values required by the apps running with native bridge.
39struct NativeBridgeRuntimeValues {
40 const char* os_arch;
41 const char* cpu_abi;
42 const char* cpu_abi2;
43 const char* *supported_abis;
44 int32_t abi_count;
45};
46
Calin Juravle961ae122014-08-11 16:11:59 +010047// The symbol name exposed by native-bridge with the type of NativeBridgeCallbacks.
48static constexpr const char* kNativeBridgeInterfaceSymbol = "NativeBridgeItf";
49
Andreas Gampe035bd752014-09-02 21:17:03 -070050enum class NativeBridgeState {
51 kNotSetup, // Initial state.
52 kOpened, // After successful dlopen.
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010053 kPreInitialized, // After successful pre-initialization.
Andreas Gampe035bd752014-09-02 21:17:03 -070054 kInitialized, // After successful initialization.
55 kClosed // Closed or errors.
56};
Calin Juravle961ae122014-08-11 16:11:59 +010057
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010058static constexpr const char* kNotSetupString = "kNotSetup";
59static constexpr const char* kOpenedString = "kOpened";
60static constexpr const char* kPreInitializedString = "kPreInitialized";
61static constexpr const char* kInitializedString = "kInitialized";
62static constexpr const char* kClosedString = "kClosed";
Andreas Gampe035bd752014-09-02 21:17:03 -070063
64static const char* GetNativeBridgeStateString(NativeBridgeState state) {
65 switch (state) {
66 case NativeBridgeState::kNotSetup:
67 return kNotSetupString;
68
69 case NativeBridgeState::kOpened:
70 return kOpenedString;
71
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010072 case NativeBridgeState::kPreInitialized:
73 return kPreInitializedString;
74
Andreas Gampe035bd752014-09-02 21:17:03 -070075 case NativeBridgeState::kInitialized:
76 return kInitializedString;
77
78 case NativeBridgeState::kClosed:
79 return kClosedString;
80 }
81}
82
83// Current state of the native bridge.
84static NativeBridgeState state = NativeBridgeState::kNotSetup;
85
Zhenhua WANGf2804e52016-05-30 11:16:08 +080086// The version of NativeBridge implementation.
87// Different Nativebridge interface needs the service of different version of
88// Nativebridge implementation.
89// Used by isCompatibleWith() which is introduced in v2.
90enum NativeBridgeImplementationVersion {
Dimitry Ivanovaf0264b2017-05-01 15:12:49 -070091 // first version, not used.
92 DEFAULT_VERSION = 1,
93 // The version which signal semantic is introduced.
94 SIGNAL_VERSION = 2,
95 // The version which namespace semantic is introduced.
96 NAMESPACE_VERSION = 3,
97 // The version with vendor namespaces
98 VENDOR_NAMESPACE_VERSION = 4,
Zhenhua WANGf2804e52016-05-30 11:16:08 +080099};
100
Andreas Gampe049249c2014-08-19 22:31:31 -0700101// Whether we had an error at some point.
102static bool had_error = false;
Calin Juravle961ae122014-08-11 16:11:59 +0100103
Andreas Gampe035bd752014-09-02 21:17:03 -0700104// Handle of the loaded library.
105static void* native_bridge_handle = nullptr;
106// Pointer to the callbacks. Available as soon as LoadNativeBridge succeeds, but only initialized
107// later.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700108static const NativeBridgeCallbacks* callbacks = nullptr;
Andreas Gampe035bd752014-09-02 21:17:03 -0700109// Callbacks provided by the environment to the bridge. Passed to LoadNativeBridge.
Calin Juravle961ae122014-08-11 16:11:59 +0100110static const NativeBridgeRuntimeCallbacks* runtime_callbacks = nullptr;
111
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100112// The app's code cache directory.
113static char* app_code_cache_dir = nullptr;
114
115// Code cache directory (relative to the application private directory)
116// Ideally we'd like to call into framework to retrieve this name. However that's considered an
117// implementation detail and will require either hacks or consistent refactorings. We compromise
118// and hard code the directory name again here.
119static constexpr const char* kCodeCacheDir = "code_cache";
jgu21ab0da5a2014-09-10 06:58:32 -0400120
Andreas Gampe049249c2014-08-19 22:31:31 -0700121// Characters allowed in a native bridge filename. The first character must
122// be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
123static bool CharacterAllowed(char c, bool first) {
124 if (first) {
125 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
126 } else {
127 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
128 (c == '.') || (c == '_') || (c == '-');
129 }
130}
131
jgu21cef898f2015-07-02 12:02:11 +0800132static void ReleaseAppCodeCacheDir() {
133 if (app_code_cache_dir != nullptr) {
134 delete[] app_code_cache_dir;
135 app_code_cache_dir = nullptr;
136 }
137}
138
Andreas Gampe049249c2014-08-19 22:31:31 -0700139// We only allow simple names for the library. It is supposed to be a file in
140// /system/lib or /vendor/lib. Only allow a small range of characters, that is
141// names consisting of [a-zA-Z0-9._-] and starting with [a-zA-Z].
142bool NativeBridgeNameAcceptable(const char* nb_library_filename) {
143 const char* ptr = nb_library_filename;
144 if (*ptr == 0) {
145 // Emptry string. Allowed, means no native bridge.
146 return true;
147 } else {
148 // First character must be [a-zA-Z].
149 if (!CharacterAllowed(*ptr, true)) {
150 // Found an invalid fist character, don't accept.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700151 ALOGE("Native bridge library %s has been rejected for first character %c",
152 nb_library_filename,
153 *ptr);
Andreas Gampe049249c2014-08-19 22:31:31 -0700154 return false;
155 } else {
156 // For the rest, be more liberal.
157 ptr++;
158 while (*ptr != 0) {
159 if (!CharacterAllowed(*ptr, false)) {
160 // Found an invalid character, don't accept.
161 ALOGE("Native bridge library %s has been rejected for %c", nb_library_filename, *ptr);
162 return false;
163 }
164 ptr++;
165 }
166 }
167 return true;
168 }
169}
170
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800171// The policy of invoking Nativebridge changed in v3 with/without namespace.
172// Suggest Nativebridge implementation not maintain backward-compatible.
173static bool isCompatibleWith(const uint32_t version) {
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700174 // Libnativebridge is now designed to be forward-compatible. So only "0" is an unsupported
175 // version.
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800176 if (callbacks == nullptr || callbacks->version == 0 || version == 0) {
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700177 return false;
178 }
179
180 // If this is a v2+ bridge, it may not be forwards- or backwards-compatible. Check.
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800181 if (callbacks->version >= SIGNAL_VERSION) {
182 return callbacks->isCompatibleWith(version);
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700183 }
184
185 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400186}
187
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100188static void CloseNativeBridge(bool with_error) {
189 state = NativeBridgeState::kClosed;
190 had_error |= with_error;
jgu21cef898f2015-07-02 12:02:11 +0800191 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100192}
193
Andreas Gampe035bd752014-09-02 21:17:03 -0700194bool LoadNativeBridge(const char* nb_library_filename,
195 const NativeBridgeRuntimeCallbacks* runtime_cbs) {
196 // We expect only one place that calls LoadNativeBridge: Runtime::Init. At that point we are not
197 // multi-threaded, so we do not need locking here.
Calin Juravle961ae122014-08-11 16:11:59 +0100198
Andreas Gampe035bd752014-09-02 21:17:03 -0700199 if (state != NativeBridgeState::kNotSetup) {
Andreas Gampe049249c2014-08-19 22:31:31 -0700200 // Setup has been called before. Ignore this call.
jgu21ab0da5a2014-09-10 06:58:32 -0400201 if (nb_library_filename != nullptr) { // Avoids some log-spam for dalvikvm.
202 ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
203 GetNativeBridgeStateString(state));
204 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700205 // Note: counts as an error, even though the bridge may be functional.
206 had_error = true;
Andreas Gampe049249c2014-08-19 22:31:31 -0700207 return false;
208 }
209
Andreas Gampe035bd752014-09-02 21:17:03 -0700210 if (nb_library_filename == nullptr || *nb_library_filename == 0) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100211 CloseNativeBridge(false);
212 return false;
Andreas Gampe035bd752014-09-02 21:17:03 -0700213 } else {
214 if (!NativeBridgeNameAcceptable(nb_library_filename)) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100215 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700216 } else {
217 // Try to open the library.
218 void* handle = dlopen(nb_library_filename, RTLD_LAZY);
219 if (handle != nullptr) {
220 callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
221 kNativeBridgeInterfaceSymbol));
222 if (callbacks != nullptr) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800223 if (isCompatibleWith(NAMESPACE_VERSION)) {
jgu21ab0da5a2014-09-10 06:58:32 -0400224 // Store the handle for later.
225 native_bridge_handle = handle;
226 } else {
227 callbacks = nullptr;
228 dlclose(handle);
229 ALOGW("Unsupported native bridge interface.");
230 }
Andreas Gampe035bd752014-09-02 21:17:03 -0700231 } else {
232 dlclose(handle);
233 }
234 }
235
236 // Two failure conditions: could not find library (dlopen failed), or could not find native
237 // bridge interface (dlsym failed). Both are an error and close the native bridge.
238 if (callbacks == nullptr) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100239 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700240 } else {
241 runtime_callbacks = runtime_cbs;
242 state = NativeBridgeState::kOpened;
243 }
244 }
245 return state == NativeBridgeState::kOpened;
246 }
247}
248
jgu21ab0da5a2014-09-10 06:58:32 -0400249bool NeedsNativeBridge(const char* instruction_set) {
Andreas Gampe04054e22014-09-25 22:33:01 -0700250 if (instruction_set == nullptr) {
251 ALOGE("Null instruction set in NeedsNativeBridge.");
252 return false;
253 }
dimitryb6ba8172017-08-23 10:25:22 +0200254 return strncmp(instruction_set, ABI_STRING, strlen(ABI_STRING) + 1) != 0;
jgu21ab0da5a2014-09-10 06:58:32 -0400255}
256
Andreas Gampe4390a632014-09-24 18:53:26 -0700257#ifdef __APPLE__
258template<typename T> void UNUSED(const T&) {}
259#endif
260
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100261bool PreInitializeNativeBridge(const char* app_data_dir_in, const char* instruction_set) {
262 if (state != NativeBridgeState::kOpened) {
263 ALOGE("Invalid state: native bridge is expected to be opened.");
264 CloseNativeBridge(true);
265 return false;
jgu21ab0da5a2014-09-10 06:58:32 -0400266 }
267
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100268 if (app_data_dir_in == nullptr) {
269 ALOGE("Application private directory cannot be null.");
270 CloseNativeBridge(true);
271 return false;
272 }
273
274 // Create the path to the application code cache directory.
275 // The memory will be release after Initialization or when the native bridge is closed.
276 const size_t len = strlen(app_data_dir_in) + strlen(kCodeCacheDir) + 2; // '\0' + '/'
277 app_code_cache_dir = new char[len];
278 snprintf(app_code_cache_dir, len, "%s/%s", app_data_dir_in, kCodeCacheDir);
279
280 // Bind-mount /system/lib{,64}/<isa>/cpuinfo to /proc/cpuinfo.
281 // Failure is not fatal and will keep the native bridge in kPreInitialized.
282 state = NativeBridgeState::kPreInitialized;
jgu21ab0da5a2014-09-10 06:58:32 -0400283
Andreas Gampe962eb402014-09-24 16:36:17 -0700284#ifndef __APPLE__
jgu21ab0da5a2014-09-10 06:58:32 -0400285 if (instruction_set == nullptr) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100286 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400287 }
288 size_t isa_len = strlen(instruction_set);
289 if (isa_len > 10) {
290 // 10 is a loose upper bound on the currently known instruction sets (a tight bound is 7 for
291 // x86_64 [including the trailing \0]). This is so we don't have to change here if there will
292 // be another instruction set in the future.
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700293 ALOGW("Instruction set %s is malformed, must be less than or equal to 10 characters.",
294 instruction_set);
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100295 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400296 }
297
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100298 // If the file does not exist, the mount command will fail,
299 // so we save the extra file existence check.
jgu21ab0da5a2014-09-10 06:58:32 -0400300 char cpuinfo_path[1024];
301
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700302#if defined(__ANDROID__)
Andreas Gampe04054e22014-09-25 22:33:01 -0700303 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/lib"
jgu21ab0da5a2014-09-10 06:58:32 -0400304#ifdef __LP64__
Andreas Gampe04054e22014-09-25 22:33:01 -0700305 "64"
306#endif // __LP64__
307 "/%s/cpuinfo", instruction_set);
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700308#else // !__ANDROID__
Andreas Gampe04054e22014-09-25 22:33:01 -0700309 // To be able to test on the host, we hardwire a relative path.
310 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "./cpuinfo");
jgu21ab0da5a2014-09-10 06:58:32 -0400311#endif
jgu21ab0da5a2014-09-10 06:58:32 -0400312
313 // Bind-mount.
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700314 if (TEMP_FAILURE_RETRY(mount(cpuinfo_path, // Source.
315 "/proc/cpuinfo", // Target.
316 nullptr, // FS type.
317 MS_BIND, // Mount flags: bind mount.
318 nullptr)) == -1) { // "Data."
Andreas Gampe04054e22014-09-25 22:33:01 -0700319 ALOGW("Failed to bind-mount %s as /proc/cpuinfo: %s", cpuinfo_path, strerror(errno));
jgu21ab0da5a2014-09-10 06:58:32 -0400320 }
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100321#else // __APPLE__
Andreas Gampe4390a632014-09-24 18:53:26 -0700322 UNUSED(instruction_set);
Andreas Gampe962eb402014-09-24 16:36:17 -0700323 ALOGW("Mac OS does not support bind-mounting. Host simulation of native bridge impossible.");
324#endif
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100325
326 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400327}
328
329static void SetCpuAbi(JNIEnv* env, jclass build_class, const char* field, const char* value) {
330 if (value != nullptr) {
331 jfieldID field_id = env->GetStaticFieldID(build_class, field, "Ljava/lang/String;");
332 if (field_id == nullptr) {
333 env->ExceptionClear();
334 ALOGW("Could not find %s field.", field);
335 return;
336 }
337
338 jstring str = env->NewStringUTF(value);
339 if (str == nullptr) {
340 env->ExceptionClear();
341 ALOGW("Could not create string %s.", value);
342 return;
343 }
344
345 env->SetStaticObjectField(build_class, field_id, str);
346 }
347}
348
jgu21ab0da5a2014-09-10 06:58:32 -0400349// Set up the environment for the bridged app.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700350static void SetupEnvironment(const NativeBridgeCallbacks* callbacks, JNIEnv* env, const char* isa) {
jgu21ab0da5a2014-09-10 06:58:32 -0400351 // Need a JNIEnv* to do anything.
352 if (env == nullptr) {
353 ALOGW("No JNIEnv* to set up app environment.");
354 return;
355 }
356
357 // Query the bridge for environment values.
358 const struct NativeBridgeRuntimeValues* env_values = callbacks->getAppEnv(isa);
359 if (env_values == nullptr) {
360 return;
361 }
362
363 // Keep the JNIEnv clean.
364 jint success = env->PushLocalFrame(16); // That should be small and large enough.
365 if (success < 0) {
366 // Out of memory, really borked.
367 ALOGW("Out of memory while setting up app environment.");
368 env->ExceptionClear();
369 return;
370 }
371
372 // Reset CPU_ABI & CPU_ABI2 to values required by the apps running with native bridge.
373 if (env_values->cpu_abi != nullptr || env_values->cpu_abi2 != nullptr ||
374 env_values->abi_count >= 0) {
375 jclass bclass_id = env->FindClass("android/os/Build");
376 if (bclass_id != nullptr) {
377 SetCpuAbi(env, bclass_id, "CPU_ABI", env_values->cpu_abi);
378 SetCpuAbi(env, bclass_id, "CPU_ABI2", env_values->cpu_abi2);
jgu21ab0da5a2014-09-10 06:58:32 -0400379 } else {
380 // For example in a host test environment.
381 env->ExceptionClear();
382 ALOGW("Could not find Build class.");
383 }
384 }
385
386 if (env_values->os_arch != nullptr) {
387 jclass sclass_id = env->FindClass("java/lang/System");
388 if (sclass_id != nullptr) {
Narayan Kamath484c55b2015-02-10 15:33:36 +0000389 jmethodID set_prop_id = env->GetStaticMethodID(sclass_id, "setUnchangeableSystemProperty",
Calin Juravlec3eb4312014-10-01 17:29:19 +0100390 "(Ljava/lang/String;Ljava/lang/String;)V");
jgu21ab0da5a2014-09-10 06:58:32 -0400391 if (set_prop_id != nullptr) {
Calin Juravlec3eb4312014-10-01 17:29:19 +0100392 // Init os.arch to the value reqired by the apps running with native bridge.
393 env->CallStaticVoidMethod(sclass_id, set_prop_id, env->NewStringUTF("os.arch"),
jgu21ab0da5a2014-09-10 06:58:32 -0400394 env->NewStringUTF(env_values->os_arch));
395 } else {
396 env->ExceptionClear();
Narayan Kamath484c55b2015-02-10 15:33:36 +0000397 ALOGW("Could not find System#setUnchangeableSystemProperty.");
jgu21ab0da5a2014-09-10 06:58:32 -0400398 }
399 } else {
400 env->ExceptionClear();
401 ALOGW("Could not find System class.");
402 }
403 }
404
405 // Make it pristine again.
406 env->PopLocalFrame(nullptr);
407}
408
409bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700410 // We expect only one place that calls InitializeNativeBridge: Runtime::DidForkFromZygote. At that
411 // point we are not multi-threaded, so we do not need locking here.
412
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100413 if (state == NativeBridgeState::kPreInitialized) {
414 // Check for code cache: if it doesn't exist try to create it.
415 struct stat st;
416 if (stat(app_code_cache_dir, &st) == -1) {
417 if (errno == ENOENT) {
418 if (mkdir(app_code_cache_dir, S_IRWXU | S_IRWXG | S_IXOTH) == -1) {
jgu21cef898f2015-07-02 12:02:11 +0800419 ALOGW("Cannot create code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
420 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100421 }
422 } else {
jgu21cef898f2015-07-02 12:02:11 +0800423 ALOGW("Cannot stat code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
424 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100425 }
426 } else if (!S_ISDIR(st.st_mode)) {
jgu21cef898f2015-07-02 12:02:11 +0800427 ALOGW("Code cache is not a directory %s.", app_code_cache_dir);
428 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100429 }
430
431 // If we're still PreInitialized (dind't fail the code cache checks) try to initialize.
432 if (state == NativeBridgeState::kPreInitialized) {
433 if (callbacks->initialize(runtime_callbacks, app_code_cache_dir, instruction_set)) {
434 SetupEnvironment(callbacks, env, instruction_set);
435 state = NativeBridgeState::kInitialized;
436 // We no longer need the code cache path, release the memory.
jgu21cef898f2015-07-02 12:02:11 +0800437 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100438 } else {
439 // Unload the library.
440 dlclose(native_bridge_handle);
441 CloseNativeBridge(true);
442 }
Calin Juravle961ae122014-08-11 16:11:59 +0100443 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700444 } else {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100445 CloseNativeBridge(true);
Calin Juravle961ae122014-08-11 16:11:59 +0100446 }
447
Andreas Gampe035bd752014-09-02 21:17:03 -0700448 return state == NativeBridgeState::kInitialized;
449}
Calin Juravle961ae122014-08-11 16:11:59 +0100450
Andreas Gampe035bd752014-09-02 21:17:03 -0700451void UnloadNativeBridge() {
452 // We expect only one place that calls UnloadNativeBridge: Runtime::DidForkFromZygote. At that
453 // point we are not multi-threaded, so we do not need locking here.
454
455 switch(state) {
456 case NativeBridgeState::kOpened:
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100457 case NativeBridgeState::kPreInitialized:
Andreas Gampe035bd752014-09-02 21:17:03 -0700458 case NativeBridgeState::kInitialized:
459 // Unload.
460 dlclose(native_bridge_handle);
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100461 CloseNativeBridge(false);
Andreas Gampe035bd752014-09-02 21:17:03 -0700462 break;
463
464 case NativeBridgeState::kNotSetup:
465 // Not even set up. Error.
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100466 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700467 break;
468
469 case NativeBridgeState::kClosed:
470 // Ignore.
471 break;
472 }
Calin Juravle961ae122014-08-11 16:11:59 +0100473}
474
Andreas Gampe049249c2014-08-19 22:31:31 -0700475bool NativeBridgeError() {
476 return had_error;
477}
478
479bool NativeBridgeAvailable() {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100480 return state == NativeBridgeState::kOpened
481 || state == NativeBridgeState::kPreInitialized
482 || state == NativeBridgeState::kInitialized;
Andreas Gampe035bd752014-09-02 21:17:03 -0700483}
484
485bool NativeBridgeInitialized() {
486 // Calls of this are supposed to happen in a state where the native bridge is stable, i.e., after
487 // Runtime::DidForkFromZygote. In that case we do not need a lock.
488 return state == NativeBridgeState::kInitialized;
Andreas Gampe049249c2014-08-19 22:31:31 -0700489}
490
Calin Juravle961ae122014-08-11 16:11:59 +0100491void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700492 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100493 return callbacks->loadLibrary(libpath, flag);
494 }
495 return nullptr;
496}
497
498void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty,
499 uint32_t len) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700500 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100501 return callbacks->getTrampoline(handle, name, shorty, len);
502 }
503 return nullptr;
504}
505
506bool NativeBridgeIsSupported(const char* libpath) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700507 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100508 return callbacks->isSupported(libpath);
509 }
510 return false;
511}
512
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700513uint32_t NativeBridgeGetVersion() {
514 if (NativeBridgeAvailable()) {
515 return callbacks->version;
516 }
517 return 0;
518}
519
520NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800521 if (NativeBridgeInitialized()) {
522 if (isCompatibleWith(SIGNAL_VERSION)) {
523 return callbacks->getSignalHandler(signal);
524 } else {
525 ALOGE("not compatible with version %d, cannot get signal handler", SIGNAL_VERSION);
526 }
527 }
528 return nullptr;
529}
530
531int NativeBridgeUnloadLibrary(void* handle) {
532 if (NativeBridgeInitialized()) {
533 if (isCompatibleWith(NAMESPACE_VERSION)) {
534 return callbacks->unloadLibrary(handle);
535 } else {
536 ALOGE("not compatible with version %d, cannot unload library", NAMESPACE_VERSION);
537 }
538 }
539 return -1;
540}
541
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700542const char* NativeBridgeGetError() {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800543 if (NativeBridgeInitialized()) {
544 if (isCompatibleWith(NAMESPACE_VERSION)) {
545 return callbacks->getError();
546 } else {
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700547 return "native bridge implementation is not compatible with version 3, cannot get message";
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800548 }
549 }
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700550 return "native bridge is not initialized";
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800551}
552
553bool NativeBridgeIsPathSupported(const char* path) {
554 if (NativeBridgeInitialized()) {
555 if (isCompatibleWith(NAMESPACE_VERSION)) {
556 return callbacks->isPathSupported(path);
557 } else {
558 ALOGE("not compatible with version %d, cannot check via library path", NAMESPACE_VERSION);
559 }
560 }
561 return false;
562}
563
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800564bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
565 const char* anon_ns_library_path) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800566 if (NativeBridgeInitialized()) {
567 if (isCompatibleWith(NAMESPACE_VERSION)) {
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800568 return callbacks->initAnonymousNamespace(public_ns_sonames, anon_ns_library_path);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800569 } else {
570 ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
571 }
572 }
573
574 return false;
575}
576
577native_bridge_namespace_t* NativeBridgeCreateNamespace(const char* name,
578 const char* ld_library_path,
579 const char* default_library_path,
580 uint64_t type,
581 const char* permitted_when_isolated_path,
582 native_bridge_namespace_t* parent_ns) {
583 if (NativeBridgeInitialized()) {
584 if (isCompatibleWith(NAMESPACE_VERSION)) {
585 return callbacks->createNamespace(name,
586 ld_library_path,
587 default_library_path,
588 type,
589 permitted_when_isolated_path,
590 parent_ns);
591 } else {
592 ALOGE("not compatible with version %d, cannot create namespace %s", NAMESPACE_VERSION, name);
593 }
594 }
595
596 return nullptr;
597}
598
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800599bool NativeBridgeLinkNamespaces(native_bridge_namespace_t* from, native_bridge_namespace_t* to,
600 const char* shared_libs_sonames) {
601 if (NativeBridgeInitialized()) {
602 if (isCompatibleWith(NAMESPACE_VERSION)) {
603 return callbacks->linkNamespaces(from, to, shared_libs_sonames);
604 } else {
605 ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
606 }
607 }
608
609 return false;
610}
611
Dimitry Ivanovaf0264b2017-05-01 15:12:49 -0700612native_bridge_namespace_t* NativeBridgeGetVendorNamespace() {
613 if (!NativeBridgeInitialized() || !isCompatibleWith(VENDOR_NAMESPACE_VERSION)) {
614 return nullptr;
615 }
616
617 return callbacks->getVendorNamespace();
618}
619
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800620void* NativeBridgeLoadLibraryExt(const char* libpath, int flag, native_bridge_namespace_t* ns) {
621 if (NativeBridgeInitialized()) {
622 if (isCompatibleWith(NAMESPACE_VERSION)) {
623 return callbacks->loadLibraryExt(libpath, flag, ns);
624 } else {
625 ALOGE("not compatible with version %d, cannot load library in namespace", NAMESPACE_VERSION);
626 }
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700627 }
628 return nullptr;
629}
630
Nicolas Geoffrayd9b4d9b2019-01-10 16:27:54 +0000631} // extern "C"
632
633} // namespace android