blob: a2d8d81efbd069fa8d2f705164c43fcf981294c6 [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 Geoffraye7de6162019-01-14 14:12:03 +000036#ifdef __APPLE__
37template <typename T>
38void UNUSED(const T&) {}
39#endif
40
Nicolas Geoffrayd9b4d9b2019-01-10 16:27:54 +000041extern "C" {
42
jgu21ab0da5a2014-09-10 06:58:32 -040043// Environment values required by the apps running with native bridge.
44struct NativeBridgeRuntimeValues {
45 const char* os_arch;
46 const char* cpu_abi;
47 const char* cpu_abi2;
48 const char* *supported_abis;
49 int32_t abi_count;
50};
51
Calin Juravle961ae122014-08-11 16:11:59 +010052// The symbol name exposed by native-bridge with the type of NativeBridgeCallbacks.
53static constexpr const char* kNativeBridgeInterfaceSymbol = "NativeBridgeItf";
54
Andreas Gampe035bd752014-09-02 21:17:03 -070055enum class NativeBridgeState {
56 kNotSetup, // Initial state.
57 kOpened, // After successful dlopen.
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010058 kPreInitialized, // After successful pre-initialization.
Andreas Gampe035bd752014-09-02 21:17:03 -070059 kInitialized, // After successful initialization.
60 kClosed // Closed or errors.
61};
Calin Juravle961ae122014-08-11 16:11:59 +010062
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010063static constexpr const char* kNotSetupString = "kNotSetup";
64static constexpr const char* kOpenedString = "kOpened";
65static constexpr const char* kPreInitializedString = "kPreInitialized";
66static constexpr const char* kInitializedString = "kInitialized";
67static constexpr const char* kClosedString = "kClosed";
Andreas Gampe035bd752014-09-02 21:17:03 -070068
69static const char* GetNativeBridgeStateString(NativeBridgeState state) {
70 switch (state) {
71 case NativeBridgeState::kNotSetup:
72 return kNotSetupString;
73
74 case NativeBridgeState::kOpened:
75 return kOpenedString;
76
Calin Juravlef9d9e2a2014-10-17 13:45:39 +010077 case NativeBridgeState::kPreInitialized:
78 return kPreInitializedString;
79
Andreas Gampe035bd752014-09-02 21:17:03 -070080 case NativeBridgeState::kInitialized:
81 return kInitializedString;
82
83 case NativeBridgeState::kClosed:
84 return kClosedString;
85 }
86}
87
88// Current state of the native bridge.
89static NativeBridgeState state = NativeBridgeState::kNotSetup;
90
Zhenhua WANGf2804e52016-05-30 11:16:08 +080091// The version of NativeBridge implementation.
92// Different Nativebridge interface needs the service of different version of
93// Nativebridge implementation.
94// Used by isCompatibleWith() which is introduced in v2.
95enum NativeBridgeImplementationVersion {
Dimitry Ivanovaf0264b2017-05-01 15:12:49 -070096 // first version, not used.
97 DEFAULT_VERSION = 1,
98 // The version which signal semantic is introduced.
99 SIGNAL_VERSION = 2,
100 // The version which namespace semantic is introduced.
101 NAMESPACE_VERSION = 3,
102 // The version with vendor namespaces
103 VENDOR_NAMESPACE_VERSION = 4,
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800104};
105
Andreas Gampe049249c2014-08-19 22:31:31 -0700106// Whether we had an error at some point.
107static bool had_error = false;
Calin Juravle961ae122014-08-11 16:11:59 +0100108
Andreas Gampe035bd752014-09-02 21:17:03 -0700109// Handle of the loaded library.
110static void* native_bridge_handle = nullptr;
111// Pointer to the callbacks. Available as soon as LoadNativeBridge succeeds, but only initialized
112// later.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700113static const NativeBridgeCallbacks* callbacks = nullptr;
Andreas Gampe035bd752014-09-02 21:17:03 -0700114// Callbacks provided by the environment to the bridge. Passed to LoadNativeBridge.
Calin Juravle961ae122014-08-11 16:11:59 +0100115static const NativeBridgeRuntimeCallbacks* runtime_callbacks = nullptr;
116
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100117// The app's code cache directory.
118static char* app_code_cache_dir = nullptr;
119
120// Code cache directory (relative to the application private directory)
121// Ideally we'd like to call into framework to retrieve this name. However that's considered an
122// implementation detail and will require either hacks or consistent refactorings. We compromise
123// and hard code the directory name again here.
124static constexpr const char* kCodeCacheDir = "code_cache";
jgu21ab0da5a2014-09-10 06:58:32 -0400125
Andreas Gampe049249c2014-08-19 22:31:31 -0700126// Characters allowed in a native bridge filename. The first character must
127// be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
128static bool CharacterAllowed(char c, bool first) {
129 if (first) {
130 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
131 } else {
132 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
133 (c == '.') || (c == '_') || (c == '-');
134 }
135}
136
jgu21cef898f2015-07-02 12:02:11 +0800137static void ReleaseAppCodeCacheDir() {
138 if (app_code_cache_dir != nullptr) {
139 delete[] app_code_cache_dir;
140 app_code_cache_dir = nullptr;
141 }
142}
143
Andreas Gampe049249c2014-08-19 22:31:31 -0700144// We only allow simple names for the library. It is supposed to be a file in
145// /system/lib or /vendor/lib. Only allow a small range of characters, that is
146// names consisting of [a-zA-Z0-9._-] and starting with [a-zA-Z].
147bool NativeBridgeNameAcceptable(const char* nb_library_filename) {
148 const char* ptr = nb_library_filename;
149 if (*ptr == 0) {
150 // Emptry string. Allowed, means no native bridge.
151 return true;
152 } else {
153 // First character must be [a-zA-Z].
154 if (!CharacterAllowed(*ptr, true)) {
155 // Found an invalid fist character, don't accept.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700156 ALOGE("Native bridge library %s has been rejected for first character %c",
157 nb_library_filename,
158 *ptr);
Andreas Gampe049249c2014-08-19 22:31:31 -0700159 return false;
160 } else {
161 // For the rest, be more liberal.
162 ptr++;
163 while (*ptr != 0) {
164 if (!CharacterAllowed(*ptr, false)) {
165 // Found an invalid character, don't accept.
166 ALOGE("Native bridge library %s has been rejected for %c", nb_library_filename, *ptr);
167 return false;
168 }
169 ptr++;
170 }
171 }
172 return true;
173 }
174}
175
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800176// The policy of invoking Nativebridge changed in v3 with/without namespace.
177// Suggest Nativebridge implementation not maintain backward-compatible.
178static bool isCompatibleWith(const uint32_t version) {
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700179 // Libnativebridge is now designed to be forward-compatible. So only "0" is an unsupported
180 // version.
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800181 if (callbacks == nullptr || callbacks->version == 0 || version == 0) {
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700182 return false;
183 }
184
185 // If this is a v2+ bridge, it may not be forwards- or backwards-compatible. Check.
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800186 if (callbacks->version >= SIGNAL_VERSION) {
187 return callbacks->isCompatibleWith(version);
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700188 }
189
190 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400191}
192
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100193static void CloseNativeBridge(bool with_error) {
194 state = NativeBridgeState::kClosed;
195 had_error |= with_error;
jgu21cef898f2015-07-02 12:02:11 +0800196 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100197}
198
Andreas Gampe035bd752014-09-02 21:17:03 -0700199bool LoadNativeBridge(const char* nb_library_filename,
200 const NativeBridgeRuntimeCallbacks* runtime_cbs) {
201 // We expect only one place that calls LoadNativeBridge: Runtime::Init. At that point we are not
202 // multi-threaded, so we do not need locking here.
Calin Juravle961ae122014-08-11 16:11:59 +0100203
Andreas Gampe035bd752014-09-02 21:17:03 -0700204 if (state != NativeBridgeState::kNotSetup) {
Andreas Gampe049249c2014-08-19 22:31:31 -0700205 // Setup has been called before. Ignore this call.
jgu21ab0da5a2014-09-10 06:58:32 -0400206 if (nb_library_filename != nullptr) { // Avoids some log-spam for dalvikvm.
207 ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
208 GetNativeBridgeStateString(state));
209 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700210 // Note: counts as an error, even though the bridge may be functional.
211 had_error = true;
Andreas Gampe049249c2014-08-19 22:31:31 -0700212 return false;
213 }
214
Andreas Gampe035bd752014-09-02 21:17:03 -0700215 if (nb_library_filename == nullptr || *nb_library_filename == 0) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100216 CloseNativeBridge(false);
217 return false;
Andreas Gampe035bd752014-09-02 21:17:03 -0700218 } else {
219 if (!NativeBridgeNameAcceptable(nb_library_filename)) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100220 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700221 } else {
222 // Try to open the library.
223 void* handle = dlopen(nb_library_filename, RTLD_LAZY);
224 if (handle != nullptr) {
225 callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
226 kNativeBridgeInterfaceSymbol));
227 if (callbacks != nullptr) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800228 if (isCompatibleWith(NAMESPACE_VERSION)) {
jgu21ab0da5a2014-09-10 06:58:32 -0400229 // Store the handle for later.
230 native_bridge_handle = handle;
231 } else {
232 callbacks = nullptr;
233 dlclose(handle);
234 ALOGW("Unsupported native bridge interface.");
235 }
Andreas Gampe035bd752014-09-02 21:17:03 -0700236 } else {
237 dlclose(handle);
238 }
239 }
240
241 // Two failure conditions: could not find library (dlopen failed), or could not find native
242 // bridge interface (dlsym failed). Both are an error and close the native bridge.
243 if (callbacks == nullptr) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100244 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700245 } else {
246 runtime_callbacks = runtime_cbs;
247 state = NativeBridgeState::kOpened;
248 }
249 }
250 return state == NativeBridgeState::kOpened;
251 }
252}
253
jgu21ab0da5a2014-09-10 06:58:32 -0400254bool NeedsNativeBridge(const char* instruction_set) {
Andreas Gampe04054e22014-09-25 22:33:01 -0700255 if (instruction_set == nullptr) {
256 ALOGE("Null instruction set in NeedsNativeBridge.");
257 return false;
258 }
dimitryb6ba8172017-08-23 10:25:22 +0200259 return strncmp(instruction_set, ABI_STRING, strlen(ABI_STRING) + 1) != 0;
jgu21ab0da5a2014-09-10 06:58:32 -0400260}
261
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100262bool PreInitializeNativeBridge(const char* app_data_dir_in, const char* instruction_set) {
263 if (state != NativeBridgeState::kOpened) {
264 ALOGE("Invalid state: native bridge is expected to be opened.");
265 CloseNativeBridge(true);
266 return false;
jgu21ab0da5a2014-09-10 06:58:32 -0400267 }
268
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100269 if (app_data_dir_in == nullptr) {
270 ALOGE("Application private directory cannot be null.");
271 CloseNativeBridge(true);
272 return false;
273 }
274
275 // Create the path to the application code cache directory.
276 // The memory will be release after Initialization or when the native bridge is closed.
277 const size_t len = strlen(app_data_dir_in) + strlen(kCodeCacheDir) + 2; // '\0' + '/'
278 app_code_cache_dir = new char[len];
279 snprintf(app_code_cache_dir, len, "%s/%s", app_data_dir_in, kCodeCacheDir);
280
281 // Bind-mount /system/lib{,64}/<isa>/cpuinfo to /proc/cpuinfo.
282 // Failure is not fatal and will keep the native bridge in kPreInitialized.
283 state = NativeBridgeState::kPreInitialized;
jgu21ab0da5a2014-09-10 06:58:32 -0400284
Andreas Gampe962eb402014-09-24 16:36:17 -0700285#ifndef __APPLE__
jgu21ab0da5a2014-09-10 06:58:32 -0400286 if (instruction_set == nullptr) {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100287 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400288 }
289 size_t isa_len = strlen(instruction_set);
290 if (isa_len > 10) {
291 // 10 is a loose upper bound on the currently known instruction sets (a tight bound is 7 for
292 // x86_64 [including the trailing \0]). This is so we don't have to change here if there will
293 // be another instruction set in the future.
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700294 ALOGW("Instruction set %s is malformed, must be less than or equal to 10 characters.",
295 instruction_set);
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100296 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400297 }
298
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100299 // If the file does not exist, the mount command will fail,
300 // so we save the extra file existence check.
jgu21ab0da5a2014-09-10 06:58:32 -0400301 char cpuinfo_path[1024];
302
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700303#if defined(__ANDROID__)
Andreas Gampe04054e22014-09-25 22:33:01 -0700304 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/lib"
jgu21ab0da5a2014-09-10 06:58:32 -0400305#ifdef __LP64__
Andreas Gampe04054e22014-09-25 22:33:01 -0700306 "64"
307#endif // __LP64__
308 "/%s/cpuinfo", instruction_set);
Elliott Hughes9b828ad2015-07-30 08:47:35 -0700309#else // !__ANDROID__
Andreas Gampe04054e22014-09-25 22:33:01 -0700310 // To be able to test on the host, we hardwire a relative path.
311 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "./cpuinfo");
jgu21ab0da5a2014-09-10 06:58:32 -0400312#endif
jgu21ab0da5a2014-09-10 06:58:32 -0400313
314 // Bind-mount.
Andreas Gampe2f71cb22014-09-25 21:34:25 -0700315 if (TEMP_FAILURE_RETRY(mount(cpuinfo_path, // Source.
316 "/proc/cpuinfo", // Target.
317 nullptr, // FS type.
318 MS_BIND, // Mount flags: bind mount.
319 nullptr)) == -1) { // "Data."
Andreas Gampe04054e22014-09-25 22:33:01 -0700320 ALOGW("Failed to bind-mount %s as /proc/cpuinfo: %s", cpuinfo_path, strerror(errno));
jgu21ab0da5a2014-09-10 06:58:32 -0400321 }
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100322#else // __APPLE__
Andreas Gampe4390a632014-09-24 18:53:26 -0700323 UNUSED(instruction_set);
Andreas Gampe962eb402014-09-24 16:36:17 -0700324 ALOGW("Mac OS does not support bind-mounting. Host simulation of native bridge impossible.");
325#endif
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100326
327 return true;
jgu21ab0da5a2014-09-10 06:58:32 -0400328}
329
330static void SetCpuAbi(JNIEnv* env, jclass build_class, const char* field, const char* value) {
331 if (value != nullptr) {
332 jfieldID field_id = env->GetStaticFieldID(build_class, field, "Ljava/lang/String;");
333 if (field_id == nullptr) {
334 env->ExceptionClear();
335 ALOGW("Could not find %s field.", field);
336 return;
337 }
338
339 jstring str = env->NewStringUTF(value);
340 if (str == nullptr) {
341 env->ExceptionClear();
342 ALOGW("Could not create string %s.", value);
343 return;
344 }
345
346 env->SetStaticObjectField(build_class, field_id, str);
347 }
348}
349
jgu21ab0da5a2014-09-10 06:58:32 -0400350// Set up the environment for the bridged app.
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700351static void SetupEnvironment(const NativeBridgeCallbacks* callbacks, JNIEnv* env, const char* isa) {
jgu21ab0da5a2014-09-10 06:58:32 -0400352 // Need a JNIEnv* to do anything.
353 if (env == nullptr) {
354 ALOGW("No JNIEnv* to set up app environment.");
355 return;
356 }
357
358 // Query the bridge for environment values.
359 const struct NativeBridgeRuntimeValues* env_values = callbacks->getAppEnv(isa);
360 if (env_values == nullptr) {
361 return;
362 }
363
364 // Keep the JNIEnv clean.
365 jint success = env->PushLocalFrame(16); // That should be small and large enough.
366 if (success < 0) {
367 // Out of memory, really borked.
368 ALOGW("Out of memory while setting up app environment.");
369 env->ExceptionClear();
370 return;
371 }
372
373 // Reset CPU_ABI & CPU_ABI2 to values required by the apps running with native bridge.
374 if (env_values->cpu_abi != nullptr || env_values->cpu_abi2 != nullptr ||
375 env_values->abi_count >= 0) {
376 jclass bclass_id = env->FindClass("android/os/Build");
377 if (bclass_id != nullptr) {
378 SetCpuAbi(env, bclass_id, "CPU_ABI", env_values->cpu_abi);
379 SetCpuAbi(env, bclass_id, "CPU_ABI2", env_values->cpu_abi2);
jgu21ab0da5a2014-09-10 06:58:32 -0400380 } else {
381 // For example in a host test environment.
382 env->ExceptionClear();
383 ALOGW("Could not find Build class.");
384 }
385 }
386
387 if (env_values->os_arch != nullptr) {
388 jclass sclass_id = env->FindClass("java/lang/System");
389 if (sclass_id != nullptr) {
Narayan Kamath484c55b2015-02-10 15:33:36 +0000390 jmethodID set_prop_id = env->GetStaticMethodID(sclass_id, "setUnchangeableSystemProperty",
Calin Juravlec3eb4312014-10-01 17:29:19 +0100391 "(Ljava/lang/String;Ljava/lang/String;)V");
jgu21ab0da5a2014-09-10 06:58:32 -0400392 if (set_prop_id != nullptr) {
Calin Juravlec3eb4312014-10-01 17:29:19 +0100393 // Init os.arch to the value reqired by the apps running with native bridge.
394 env->CallStaticVoidMethod(sclass_id, set_prop_id, env->NewStringUTF("os.arch"),
jgu21ab0da5a2014-09-10 06:58:32 -0400395 env->NewStringUTF(env_values->os_arch));
396 } else {
397 env->ExceptionClear();
Narayan Kamath484c55b2015-02-10 15:33:36 +0000398 ALOGW("Could not find System#setUnchangeableSystemProperty.");
jgu21ab0da5a2014-09-10 06:58:32 -0400399 }
400 } else {
401 env->ExceptionClear();
402 ALOGW("Could not find System class.");
403 }
404 }
405
406 // Make it pristine again.
407 env->PopLocalFrame(nullptr);
408}
409
410bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700411 // We expect only one place that calls InitializeNativeBridge: Runtime::DidForkFromZygote. At that
412 // point we are not multi-threaded, so we do not need locking here.
413
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100414 if (state == NativeBridgeState::kPreInitialized) {
415 // Check for code cache: if it doesn't exist try to create it.
416 struct stat st;
417 if (stat(app_code_cache_dir, &st) == -1) {
418 if (errno == ENOENT) {
419 if (mkdir(app_code_cache_dir, S_IRWXU | S_IRWXG | S_IXOTH) == -1) {
jgu21cef898f2015-07-02 12:02:11 +0800420 ALOGW("Cannot create code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
421 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100422 }
423 } else {
jgu21cef898f2015-07-02 12:02:11 +0800424 ALOGW("Cannot stat code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
425 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100426 }
427 } else if (!S_ISDIR(st.st_mode)) {
jgu21cef898f2015-07-02 12:02:11 +0800428 ALOGW("Code cache is not a directory %s.", app_code_cache_dir);
429 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100430 }
431
432 // If we're still PreInitialized (dind't fail the code cache checks) try to initialize.
433 if (state == NativeBridgeState::kPreInitialized) {
434 if (callbacks->initialize(runtime_callbacks, app_code_cache_dir, instruction_set)) {
435 SetupEnvironment(callbacks, env, instruction_set);
436 state = NativeBridgeState::kInitialized;
437 // We no longer need the code cache path, release the memory.
jgu21cef898f2015-07-02 12:02:11 +0800438 ReleaseAppCodeCacheDir();
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100439 } else {
440 // Unload the library.
441 dlclose(native_bridge_handle);
442 CloseNativeBridge(true);
443 }
Calin Juravle961ae122014-08-11 16:11:59 +0100444 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700445 } else {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100446 CloseNativeBridge(true);
Calin Juravle961ae122014-08-11 16:11:59 +0100447 }
448
Andreas Gampe035bd752014-09-02 21:17:03 -0700449 return state == NativeBridgeState::kInitialized;
450}
Calin Juravle961ae122014-08-11 16:11:59 +0100451
Andreas Gampe035bd752014-09-02 21:17:03 -0700452void UnloadNativeBridge() {
453 // We expect only one place that calls UnloadNativeBridge: Runtime::DidForkFromZygote. At that
454 // point we are not multi-threaded, so we do not need locking here.
455
456 switch(state) {
457 case NativeBridgeState::kOpened:
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100458 case NativeBridgeState::kPreInitialized:
Andreas Gampe035bd752014-09-02 21:17:03 -0700459 case NativeBridgeState::kInitialized:
460 // Unload.
461 dlclose(native_bridge_handle);
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100462 CloseNativeBridge(false);
Andreas Gampe035bd752014-09-02 21:17:03 -0700463 break;
464
465 case NativeBridgeState::kNotSetup:
466 // Not even set up. Error.
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100467 CloseNativeBridge(true);
Andreas Gampe035bd752014-09-02 21:17:03 -0700468 break;
469
470 case NativeBridgeState::kClosed:
471 // Ignore.
472 break;
473 }
Calin Juravle961ae122014-08-11 16:11:59 +0100474}
475
Andreas Gampe049249c2014-08-19 22:31:31 -0700476bool NativeBridgeError() {
477 return had_error;
478}
479
480bool NativeBridgeAvailable() {
Calin Juravlef9d9e2a2014-10-17 13:45:39 +0100481 return state == NativeBridgeState::kOpened
482 || state == NativeBridgeState::kPreInitialized
483 || state == NativeBridgeState::kInitialized;
Andreas Gampe035bd752014-09-02 21:17:03 -0700484}
485
486bool NativeBridgeInitialized() {
487 // Calls of this are supposed to happen in a state where the native bridge is stable, i.e., after
488 // Runtime::DidForkFromZygote. In that case we do not need a lock.
489 return state == NativeBridgeState::kInitialized;
Andreas Gampe049249c2014-08-19 22:31:31 -0700490}
491
Calin Juravle961ae122014-08-11 16:11:59 +0100492void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700493 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100494 return callbacks->loadLibrary(libpath, flag);
495 }
496 return nullptr;
497}
498
499void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty,
500 uint32_t len) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700501 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100502 return callbacks->getTrampoline(handle, name, shorty, len);
503 }
504 return nullptr;
505}
506
507bool NativeBridgeIsSupported(const char* libpath) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700508 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100509 return callbacks->isSupported(libpath);
510 }
511 return false;
512}
513
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700514uint32_t NativeBridgeGetVersion() {
515 if (NativeBridgeAvailable()) {
516 return callbacks->version;
517 }
518 return 0;
519}
520
521NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800522 if (NativeBridgeInitialized()) {
523 if (isCompatibleWith(SIGNAL_VERSION)) {
524 return callbacks->getSignalHandler(signal);
525 } else {
526 ALOGE("not compatible with version %d, cannot get signal handler", SIGNAL_VERSION);
527 }
528 }
529 return nullptr;
530}
531
532int NativeBridgeUnloadLibrary(void* handle) {
533 if (NativeBridgeInitialized()) {
534 if (isCompatibleWith(NAMESPACE_VERSION)) {
535 return callbacks->unloadLibrary(handle);
536 } else {
537 ALOGE("not compatible with version %d, cannot unload library", NAMESPACE_VERSION);
538 }
539 }
540 return -1;
541}
542
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700543const char* NativeBridgeGetError() {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800544 if (NativeBridgeInitialized()) {
545 if (isCompatibleWith(NAMESPACE_VERSION)) {
546 return callbacks->getError();
547 } else {
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700548 return "native bridge implementation is not compatible with version 3, cannot get message";
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800549 }
550 }
Dimitry Ivanovd836ab02016-11-02 18:03:10 -0700551 return "native bridge is not initialized";
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800552}
553
554bool NativeBridgeIsPathSupported(const char* path) {
555 if (NativeBridgeInitialized()) {
556 if (isCompatibleWith(NAMESPACE_VERSION)) {
557 return callbacks->isPathSupported(path);
558 } else {
559 ALOGE("not compatible with version %d, cannot check via library path", NAMESPACE_VERSION);
560 }
561 }
562 return false;
563}
564
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800565bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
566 const char* anon_ns_library_path) {
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800567 if (NativeBridgeInitialized()) {
568 if (isCompatibleWith(NAMESPACE_VERSION)) {
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800569 return callbacks->initAnonymousNamespace(public_ns_sonames, anon_ns_library_path);
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800570 } else {
571 ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
572 }
573 }
574
575 return false;
576}
577
578native_bridge_namespace_t* NativeBridgeCreateNamespace(const char* name,
579 const char* ld_library_path,
580 const char* default_library_path,
581 uint64_t type,
582 const char* permitted_when_isolated_path,
583 native_bridge_namespace_t* parent_ns) {
584 if (NativeBridgeInitialized()) {
585 if (isCompatibleWith(NAMESPACE_VERSION)) {
586 return callbacks->createNamespace(name,
587 ld_library_path,
588 default_library_path,
589 type,
590 permitted_when_isolated_path,
591 parent_ns);
592 } else {
593 ALOGE("not compatible with version %d, cannot create namespace %s", NAMESPACE_VERSION, name);
594 }
595 }
596
597 return nullptr;
598}
599
Zhenhua WANGe8fb11d2017-02-27 10:14:45 +0800600bool NativeBridgeLinkNamespaces(native_bridge_namespace_t* from, native_bridge_namespace_t* to,
601 const char* shared_libs_sonames) {
602 if (NativeBridgeInitialized()) {
603 if (isCompatibleWith(NAMESPACE_VERSION)) {
604 return callbacks->linkNamespaces(from, to, shared_libs_sonames);
605 } else {
606 ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
607 }
608 }
609
610 return false;
611}
612
Dimitry Ivanovaf0264b2017-05-01 15:12:49 -0700613native_bridge_namespace_t* NativeBridgeGetVendorNamespace() {
614 if (!NativeBridgeInitialized() || !isCompatibleWith(VENDOR_NAMESPACE_VERSION)) {
615 return nullptr;
616 }
617
618 return callbacks->getVendorNamespace();
619}
620
Zhenhua WANGf2804e52016-05-30 11:16:08 +0800621void* NativeBridgeLoadLibraryExt(const char* libpath, int flag, native_bridge_namespace_t* ns) {
622 if (NativeBridgeInitialized()) {
623 if (isCompatibleWith(NAMESPACE_VERSION)) {
624 return callbacks->loadLibraryExt(libpath, flag, ns);
625 } else {
626 ALOGE("not compatible with version %d, cannot load library in namespace", NAMESPACE_VERSION);
627 }
Andreas Gampea6ac9ce2015-04-30 20:39:12 -0700628 }
629 return nullptr;
630}
631
Nicolas Geoffrayd9b4d9b2019-01-10 16:27:54 +0000632} // extern "C"
633
634} // namespace android