1 /*
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 #define LOG_TAG "nativebridge"
18 
19 #include "nativebridge/native_bridge.h"
20 
21 #include <dlfcn.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <stdio.h>
25 #include <sys/mount.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 
29 #include <cstring>
30 
31 #include <android-base/macros.h>
32 #include <log/log.h>
33 
34 #ifdef ART_TARGET_ANDROID
35 #include "nativeloader/dlext_namespaces.h"
36 #endif
37 
38 namespace android {
39 
40 #ifdef __APPLE__
41 template <typename T>
UNUSED(const T &)42 void UNUSED(const T&) {}
43 #endif
44 
45 extern "C" {
46 
OpenSystemLibrary(const char * path,int flags)47 void* OpenSystemLibrary(const char* path, int flags) {
48 #ifdef ART_TARGET_ANDROID
49   // The system namespace is called "default" for binaries in /system and
50   // "system" for those in the Runtime APEX. Try "system" first since
51   // "default" always exists.
52   // TODO(b/185587109): Get rid of this error prone logic.
53   android_namespace_t* system_ns = android_get_exported_namespace("system");
54   if (system_ns == nullptr) {
55     system_ns = android_get_exported_namespace("default");
56     LOG_ALWAYS_FATAL_IF(system_ns == nullptr,
57                         "Failed to get system namespace for loading %s", path);
58   }
59   const android_dlextinfo dlextinfo = {
60       .flags = ANDROID_DLEXT_USE_NAMESPACE,
61       .library_namespace = system_ns,
62   };
63   return android_dlopen_ext(path, flags, &dlextinfo);
64 #else
65   return dlopen(path, flags);
66 #endif
67 }
68 
69 // Environment values required by the apps running with native bridge.
70 struct NativeBridgeRuntimeValues {
71     const char* os_arch;
72     const char* cpu_abi;
73     const char* cpu_abi2;
74     const char* *supported_abis;
75     int32_t abi_count;
76 };
77 
78 // The symbol name exposed by native-bridge with the type of NativeBridgeCallbacks.
79 static constexpr const char* kNativeBridgeInterfaceSymbol = "NativeBridgeItf";
80 
81 enum class NativeBridgeState {
82   kNotSetup,                        // Initial state.
83   kOpened,                          // After successful dlopen.
84   kPreInitialized,                  // After successful pre-initialization.
85   kInitialized,                     // After successful initialization.
86   kClosed                           // Closed or errors.
87 };
88 
89 static constexpr const char* kNotSetupString = "kNotSetup";
90 static constexpr const char* kOpenedString = "kOpened";
91 static constexpr const char* kPreInitializedString = "kPreInitialized";
92 static constexpr const char* kInitializedString = "kInitialized";
93 static constexpr const char* kClosedString = "kClosed";
94 
GetNativeBridgeStateString(NativeBridgeState state)95 static const char* GetNativeBridgeStateString(NativeBridgeState state) {
96   switch (state) {
97     case NativeBridgeState::kNotSetup:
98       return kNotSetupString;
99 
100     case NativeBridgeState::kOpened:
101       return kOpenedString;
102 
103     case NativeBridgeState::kPreInitialized:
104       return kPreInitializedString;
105 
106     case NativeBridgeState::kInitialized:
107       return kInitializedString;
108 
109     case NativeBridgeState::kClosed:
110       return kClosedString;
111   }
112 }
113 
114 // Current state of the native bridge.
115 static NativeBridgeState state = NativeBridgeState::kNotSetup;
116 
117 // The version of NativeBridge implementation.
118 // Different Nativebridge interface needs the service of different version of
119 // Nativebridge implementation.
120 // Used by isCompatibleWith() which is introduced in v2.
121 enum NativeBridgeImplementationVersion {
122   // first version, not used.
123   DEFAULT_VERSION = 1,
124   // The version which signal semantic is introduced.
125   SIGNAL_VERSION = 2,
126   // The version which namespace semantic is introduced.
127   NAMESPACE_VERSION = 3,
128   // The version with vendor namespaces
129   VENDOR_NAMESPACE_VERSION = 4,
130   // The version with runtime namespaces
131   RUNTIME_NAMESPACE_VERSION = 5,
132   // The version with pre-zygote-fork hook to support app-zygotes.
133   PRE_ZYGOTE_FORK_VERSION = 6,
134   // The version with critical_native support
135   CRITICAL_NATIVE_SUPPORT_VERSION = 7,
136 };
137 
138 // Whether we had an error at some point.
139 static bool had_error = false;
140 
141 // Handle of the loaded library.
142 static void* native_bridge_handle = nullptr;
143 // Pointer to the callbacks. Available as soon as LoadNativeBridge succeeds, but only initialized
144 // later.
145 static const NativeBridgeCallbacks* callbacks = nullptr;
146 // Callbacks provided by the environment to the bridge. Passed to LoadNativeBridge.
147 static const NativeBridgeRuntimeCallbacks* runtime_callbacks = nullptr;
148 
149 // The app's code cache directory.
150 static char* app_code_cache_dir = nullptr;
151 
152 // Code cache directory (relative to the application private directory)
153 // Ideally we'd like to call into framework to retrieve this name. However that's considered an
154 // implementation detail and will require either hacks or consistent refactorings. We compromise
155 // and hard code the directory name again here.
156 static constexpr const char* kCodeCacheDir = "code_cache";
157 
158 // Characters allowed in a native bridge filename. The first character must
159 // be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
CharacterAllowed(char c,bool first)160 static bool CharacterAllowed(char c, bool first) {
161   if (first) {
162     return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
163   } else {
164     return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
165            (c == '.') || (c == '_') || (c == '-');
166   }
167 }
168 
ReleaseAppCodeCacheDir()169 static void ReleaseAppCodeCacheDir() {
170   if (app_code_cache_dir != nullptr) {
171     delete[] app_code_cache_dir;
172     app_code_cache_dir = nullptr;
173   }
174 }
175 
176 // We only allow simple names for the library. It is supposed to be a file in
177 // /system/lib or /vendor/lib. Only allow a small range of characters, that is
178 // names consisting of [a-zA-Z0-9._-] and starting with [a-zA-Z].
NativeBridgeNameAcceptable(const char * nb_library_filename)179 bool NativeBridgeNameAcceptable(const char* nb_library_filename) {
180   const char* ptr = nb_library_filename;
181   if (*ptr == 0) {
182     // Emptry string. Allowed, means no native bridge.
183     return true;
184   } else {
185     // First character must be [a-zA-Z].
186     if (!CharacterAllowed(*ptr, true))  {
187       // Found an invalid fist character, don't accept.
188       ALOGE("Native bridge library %s has been rejected for first character %c",
189             nb_library_filename,
190             *ptr);
191       return false;
192     } else {
193       // For the rest, be more liberal.
194       ptr++;
195       while (*ptr != 0) {
196         if (!CharacterAllowed(*ptr, false)) {
197           // Found an invalid character, don't accept.
198           ALOGE("Native bridge library %s has been rejected for %c", nb_library_filename, *ptr);
199           return false;
200         }
201         ptr++;
202       }
203     }
204     return true;
205   }
206 }
207 
208 // The policy of invoking Nativebridge changed in v3 with/without namespace.
209 // Suggest Nativebridge implementation not maintain backward-compatible.
isCompatibleWith(const uint32_t version)210 static bool isCompatibleWith(const uint32_t version) {
211   // Libnativebridge is now designed to be forward-compatible. So only "0" is an unsupported
212   // version.
213   if (callbacks == nullptr || callbacks->version == 0 || version == 0) {
214     return false;
215   }
216 
217   // If this is a v2+ bridge, it may not be forwards- or backwards-compatible. Check.
218   if (callbacks->version >= SIGNAL_VERSION) {
219     return callbacks->isCompatibleWith(version);
220   }
221 
222   return true;
223 }
224 
CloseNativeBridge(bool with_error)225 static void CloseNativeBridge(bool with_error) {
226   state = NativeBridgeState::kClosed;
227   had_error |= with_error;
228   ReleaseAppCodeCacheDir();
229 }
230 
LoadNativeBridge(const char * nb_library_filename,const NativeBridgeRuntimeCallbacks * runtime_cbs)231 bool LoadNativeBridge(const char* nb_library_filename,
232                       const NativeBridgeRuntimeCallbacks* runtime_cbs) {
233   // We expect only one place that calls LoadNativeBridge: Runtime::Init. At that point we are not
234   // multi-threaded, so we do not need locking here.
235 
236   if (state != NativeBridgeState::kNotSetup) {
237     // Setup has been called before. Ignore this call.
238     if (nb_library_filename != nullptr) {  // Avoids some log-spam for dalvikvm.
239       ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
240             GetNativeBridgeStateString(state));
241     }
242     // Note: counts as an error, even though the bridge may be functional.
243     had_error = true;
244     return false;
245   }
246 
247   if (nb_library_filename == nullptr || *nb_library_filename == 0) {
248     CloseNativeBridge(false);
249     return false;
250   } else {
251     if (!NativeBridgeNameAcceptable(nb_library_filename)) {
252       CloseNativeBridge(true);
253     } else {
254       // Try to open the library. We assume this library is provided by the
255       // platform rather than the ART APEX itself, so use the system namespace
256       // to avoid requiring a static linker config link to it from the
257       // com_android_art namespace.
258       void* handle = OpenSystemLibrary(nb_library_filename, RTLD_LAZY);
259 
260       if (handle != nullptr) {
261         callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
262                                                                    kNativeBridgeInterfaceSymbol));
263         if (callbacks != nullptr) {
264           if (isCompatibleWith(NAMESPACE_VERSION)) {
265             // Store the handle for later.
266             native_bridge_handle = handle;
267           } else {
268             ALOGW("Unsupported native bridge API in %s (is version %d not compatible with %d)",
269                   nb_library_filename, callbacks->version, NAMESPACE_VERSION);
270             callbacks = nullptr;
271             dlclose(handle);
272           }
273         } else {
274           dlclose(handle);
275           ALOGW("Unsupported native bridge API in %s: %s not found",
276                 nb_library_filename, kNativeBridgeInterfaceSymbol);
277         }
278       } else {
279         ALOGW("Failed to load native bridge implementation: %s", dlerror());
280       }
281 
282       // Two failure conditions: could not find library (dlopen failed), or could not find native
283       // bridge interface (dlsym failed). Both are an error and close the native bridge.
284       if (callbacks == nullptr) {
285         CloseNativeBridge(true);
286       } else {
287         runtime_callbacks = runtime_cbs;
288         state = NativeBridgeState::kOpened;
289       }
290     }
291     return state == NativeBridgeState::kOpened;
292   }
293 }
294 
NeedsNativeBridge(const char * instruction_set)295 bool NeedsNativeBridge(const char* instruction_set) {
296   if (instruction_set == nullptr) {
297     ALOGE("Null instruction set in NeedsNativeBridge.");
298     return false;
299   }
300   return strncmp(instruction_set, ABI_STRING, strlen(ABI_STRING) + 1) != 0;
301 }
302 
303 #ifndef __APPLE__
MountCpuinfo(const char * cpuinfo_path)304 static bool MountCpuinfo(const char* cpuinfo_path) {
305   // If the file does not exist, the mount command will fail,
306   // so we save the extra file existence check.
307   if (TEMP_FAILURE_RETRY(mount(cpuinfo_path,        // Source.
308                                "/proc/cpuinfo",     // Target.
309                                nullptr,             // FS type.
310                                MS_BIND,             // Mount flags: bind mount.
311                                nullptr)) == -1) {   // "Data."
312     ALOGW("Failed to bind-mount %s as /proc/cpuinfo: %s", cpuinfo_path, strerror(errno));
313     return false;
314   }
315   return true;
316 }
317 #endif
318 
MountCpuinfoForInstructionSet(const char * instruction_set)319 static void MountCpuinfoForInstructionSet(const char* instruction_set) {
320   if (instruction_set == nullptr) {
321     return;
322   }
323 
324   size_t isa_len = strlen(instruction_set);
325   if (isa_len > 10) {
326     // 10 is a loose upper bound on the currently known instruction sets (a tight bound is 7 for
327     // x86_64 [including the trailing \0]). This is so we don't have to change here if there will
328     // be another instruction set in the future.
329     ALOGW("Instruction set %s is malformed, must be less than or equal to 10 characters.",
330           instruction_set);
331     return;
332   }
333 
334 #if defined(__APPLE__)
335   ALOGW("Mac OS does not support bind-mounting. Host simulation of native bridge impossible.");
336 
337 #elif !defined(__ANDROID__)
338   // To be able to test on the host, we hardwire a relative path.
339   MountCpuinfo("./cpuinfo");
340 
341 #else  // __ANDROID__
342   char cpuinfo_path[1024];
343 
344   // Bind-mount /system/etc/cpuinfo.<isa>.txt to /proc/cpuinfo.
345   snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/etc/cpuinfo.%s.txt", instruction_set);
346   if (MountCpuinfo(cpuinfo_path)) {
347     return;
348   }
349 
350   // Bind-mount /system/lib{,64}/<isa>/cpuinfo to /proc/cpuinfo.
351   // TODO(b/179753190): remove when all implementations migrate to system/etc!
352 #ifdef __LP64__
353   snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/lib64/%s/cpuinfo", instruction_set);
354 #else
355   snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/lib/%s/cpuinfo", instruction_set);
356 #endif  // __LP64__
357   MountCpuinfo(cpuinfo_path);
358 
359 #endif
360 }
361 
PreInitializeNativeBridge(const char * app_data_dir_in,const char * instruction_set)362 bool PreInitializeNativeBridge(const char* app_data_dir_in, const char* instruction_set) {
363   if (state != NativeBridgeState::kOpened) {
364     ALOGE("Invalid state: native bridge is expected to be opened.");
365     CloseNativeBridge(true);
366     return false;
367   }
368 
369   if (app_data_dir_in != nullptr) {
370     // Create the path to the application code cache directory.
371     // The memory will be release after Initialization or when the native bridge is closed.
372     const size_t len = strlen(app_data_dir_in) + strlen(kCodeCacheDir) + 2;  // '\0' + '/'
373     app_code_cache_dir = new char[len];
374     snprintf(app_code_cache_dir, len, "%s/%s", app_data_dir_in, kCodeCacheDir);
375   } else {
376     ALOGW("Application private directory isn't available.");
377     app_code_cache_dir = nullptr;
378   }
379 
380   // Mount cpuinfo that corresponds to the instruction set.
381   // Failure is not fatal.
382   MountCpuinfoForInstructionSet(instruction_set);
383 
384   state = NativeBridgeState::kPreInitialized;
385   return true;
386 }
387 
PreZygoteForkNativeBridge()388 void PreZygoteForkNativeBridge() {
389   if (NativeBridgeInitialized()) {
390     if (isCompatibleWith(PRE_ZYGOTE_FORK_VERSION)) {
391       return callbacks->preZygoteFork();
392     } else {
393       ALOGE("not compatible with version %d, preZygoteFork() isn't invoked",
394             PRE_ZYGOTE_FORK_VERSION);
395     }
396   }
397 }
398 
SetCpuAbi(JNIEnv * env,jclass build_class,const char * field,const char * value)399 static void SetCpuAbi(JNIEnv* env, jclass build_class, const char* field, const char* value) {
400   if (value != nullptr) {
401     jfieldID field_id = env->GetStaticFieldID(build_class, field, "Ljava/lang/String;");
402     if (field_id == nullptr) {
403       env->ExceptionClear();
404       ALOGW("Could not find %s field.", field);
405       return;
406     }
407 
408     jstring str = env->NewStringUTF(value);
409     if (str == nullptr) {
410       env->ExceptionClear();
411       ALOGW("Could not create string %s.", value);
412       return;
413     }
414 
415     env->SetStaticObjectField(build_class, field_id, str);
416   }
417 }
418 
419 // Set up the environment for the bridged app.
SetupEnvironment(const NativeBridgeCallbacks * cbs,JNIEnv * env,const char * isa)420 static void SetupEnvironment(const NativeBridgeCallbacks* cbs, JNIEnv* env, const char* isa) {
421   // Need a JNIEnv* to do anything.
422   if (env == nullptr) {
423     ALOGW("No JNIEnv* to set up app environment.");
424     return;
425   }
426 
427   // Query the bridge for environment values.
428   const struct NativeBridgeRuntimeValues* env_values = cbs->getAppEnv(isa);
429   if (env_values == nullptr) {
430     return;
431   }
432 
433   // Keep the JNIEnv clean.
434   jint success = env->PushLocalFrame(16);  // That should be small and large enough.
435   if (success < 0) {
436     // Out of memory, really borked.
437     ALOGW("Out of memory while setting up app environment.");
438     env->ExceptionClear();
439     return;
440   }
441 
442   // Reset CPU_ABI & CPU_ABI2 to values required by the apps running with native bridge.
443   if (env_values->cpu_abi != nullptr || env_values->cpu_abi2 != nullptr ||
444       env_values->abi_count >= 0) {
445     jclass bclass_id = env->FindClass("android/os/Build");
446     if (bclass_id != nullptr) {
447       SetCpuAbi(env, bclass_id, "CPU_ABI", env_values->cpu_abi);
448       SetCpuAbi(env, bclass_id, "CPU_ABI2", env_values->cpu_abi2);
449     } else {
450       // For example in a host test environment.
451       env->ExceptionClear();
452       ALOGW("Could not find Build class.");
453     }
454   }
455 
456   if (env_values->os_arch != nullptr) {
457     jclass sclass_id = env->FindClass("java/lang/System");
458     if (sclass_id != nullptr) {
459       jmethodID set_prop_id = env->GetStaticMethodID(sclass_id, "setUnchangeableSystemProperty",
460           "(Ljava/lang/String;Ljava/lang/String;)V");
461       if (set_prop_id != nullptr) {
462         // Init os.arch to the value reqired by the apps running with native bridge.
463         env->CallStaticVoidMethod(sclass_id, set_prop_id, env->NewStringUTF("os.arch"),
464             env->NewStringUTF(env_values->os_arch));
465       } else {
466         env->ExceptionClear();
467         ALOGW("Could not find System#setUnchangeableSystemProperty.");
468       }
469     } else {
470       env->ExceptionClear();
471       ALOGW("Could not find System class.");
472     }
473   }
474 
475   // Make it pristine again.
476   env->PopLocalFrame(nullptr);
477 }
478 
InitializeNativeBridge(JNIEnv * env,const char * instruction_set)479 bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
480   // We expect only one place that calls InitializeNativeBridge: Runtime::DidForkFromZygote. At that
481   // point we are not multi-threaded, so we do not need locking here.
482 
483   if (state == NativeBridgeState::kPreInitialized) {
484     if (app_code_cache_dir != nullptr) {
485       // Check for code cache: if it doesn't exist try to create it.
486       struct stat st;
487       if (stat(app_code_cache_dir, &st) == -1) {
488         if (errno == ENOENT) {
489           if (mkdir(app_code_cache_dir, S_IRWXU | S_IRWXG | S_IXOTH) == -1) {
490             ALOGW("Cannot create code cache directory %s: %s.",
491                   app_code_cache_dir, strerror(errno));
492             ReleaseAppCodeCacheDir();
493           }
494         } else {
495           ALOGW("Cannot stat code cache directory %s: %s.",
496                 app_code_cache_dir, strerror(errno));
497           ReleaseAppCodeCacheDir();
498         }
499       } else if (!S_ISDIR(st.st_mode)) {
500         ALOGW("Code cache is not a directory %s.", app_code_cache_dir);
501         ReleaseAppCodeCacheDir();
502       }
503     }
504 
505     // If we're still PreInitialized (didn't fail the code cache checks) try to initialize.
506     if (state == NativeBridgeState::kPreInitialized) {
507       if (callbacks->initialize(runtime_callbacks, app_code_cache_dir, instruction_set)) {
508         SetupEnvironment(callbacks, env, instruction_set);
509         state = NativeBridgeState::kInitialized;
510         // We no longer need the code cache path, release the memory.
511         ReleaseAppCodeCacheDir();
512       } else {
513         // Unload the library.
514         dlclose(native_bridge_handle);
515         CloseNativeBridge(true);
516       }
517     }
518   } else {
519     CloseNativeBridge(true);
520   }
521 
522   return state == NativeBridgeState::kInitialized;
523 }
524 
UnloadNativeBridge()525 void UnloadNativeBridge() {
526   // We expect only one place that calls UnloadNativeBridge: Runtime::DidForkFromZygote. At that
527   // point we are not multi-threaded, so we do not need locking here.
528 
529   switch (state) {
530     case NativeBridgeState::kOpened:
531     case NativeBridgeState::kPreInitialized:
532     case NativeBridgeState::kInitialized:
533       // Unload.
534       dlclose(native_bridge_handle);
535       CloseNativeBridge(false);
536       break;
537 
538     case NativeBridgeState::kNotSetup:
539       // Not even set up. Error.
540       CloseNativeBridge(true);
541       break;
542 
543     case NativeBridgeState::kClosed:
544       // Ignore.
545       break;
546   }
547 }
548 
NativeBridgeError()549 bool NativeBridgeError() {
550   return had_error;
551 }
552 
NativeBridgeAvailable()553 bool NativeBridgeAvailable() {
554   return state == NativeBridgeState::kOpened
555       || state == NativeBridgeState::kPreInitialized
556       || state == NativeBridgeState::kInitialized;
557 }
558 
NativeBridgeInitialized()559 bool NativeBridgeInitialized() {
560   // Calls of this are supposed to happen in a state where the native bridge is stable, i.e., after
561   // Runtime::DidForkFromZygote. In that case we do not need a lock.
562   return state == NativeBridgeState::kInitialized;
563 }
564 
NativeBridgeLoadLibrary(const char * libpath,int flag)565 void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
566   if (NativeBridgeInitialized()) {
567     return callbacks->loadLibrary(libpath, flag);
568   }
569   return nullptr;
570 }
571 
NativeBridgeGetTrampoline(void * handle,const char * name,const char * shorty,uint32_t len)572 void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty,
573                                 uint32_t len) {
574   return NativeBridgeGetTrampoline2(handle, name, shorty, len, kJNICallTypeRegular);
575 }
576 
NativeBridgeGetTrampoline2(void * handle,const char * name,const char * shorty,uint32_t len,JNICallType jni_call_type)577 void* NativeBridgeGetTrampoline2(
578     void* handle, const char* name, const char* shorty, uint32_t len, JNICallType jni_call_type) {
579   if (!NativeBridgeInitialized()) {
580     return nullptr;
581   }
582 
583   // For version 1 isCompatibleWith is always true, even though the extensions
584   // are not supported, so we need to handle it separately.
585   if (callbacks != nullptr && callbacks->version == DEFAULT_VERSION) {
586     return callbacks->getTrampoline(handle, name, shorty, len);
587   }
588 
589   if (isCompatibleWith(CRITICAL_NATIVE_SUPPORT_VERSION)) {
590     return callbacks->getTrampolineWithJNICallType(handle, name, shorty, len, jni_call_type);
591   }
592 
593   return callbacks->getTrampoline(handle, name, shorty, len);
594 }
595 
NativeBridgeGetTrampolineForFunctionPointer(const void * method,const char * shorty,uint32_t len,JNICallType jni_call_type)596 void* NativeBridgeGetTrampolineForFunctionPointer(const void* method,
597                                                   const char* shorty,
598                                                   uint32_t len,
599                                                   JNICallType jni_call_type) {
600   if (!NativeBridgeInitialized()) {
601     return nullptr;
602   }
603 
604   if (isCompatibleWith(CRITICAL_NATIVE_SUPPORT_VERSION)) {
605     return callbacks->getTrampolineForFunctionPointer(method, shorty, len, jni_call_type);
606   } else {
607     ALOGE("not compatible with version %d, getTrampolineFnPtrWithJNICallType() isn't invoked",
608           CRITICAL_NATIVE_SUPPORT_VERSION);
609     return nullptr;
610   }
611 }
612 
NativeBridgeIsSupported(const char * libpath)613 bool NativeBridgeIsSupported(const char* libpath) {
614   if (NativeBridgeInitialized()) {
615     return callbacks->isSupported(libpath);
616   }
617   return false;
618 }
619 
NativeBridgeGetVersion()620 uint32_t NativeBridgeGetVersion() {
621   if (NativeBridgeAvailable()) {
622     return callbacks->version;
623   }
624   return 0;
625 }
626 
NativeBridgeGetSignalHandler(int signal)627 NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
628   if (NativeBridgeInitialized()) {
629     if (isCompatibleWith(SIGNAL_VERSION)) {
630       return callbacks->getSignalHandler(signal);
631     } else {
632       ALOGE("not compatible with version %d, cannot get signal handler", SIGNAL_VERSION);
633     }
634   }
635   return nullptr;
636 }
637 
NativeBridgeUnloadLibrary(void * handle)638 int NativeBridgeUnloadLibrary(void* handle) {
639   if (NativeBridgeInitialized()) {
640     if (isCompatibleWith(NAMESPACE_VERSION)) {
641       return callbacks->unloadLibrary(handle);
642     } else {
643       ALOGE("not compatible with version %d, cannot unload library", NAMESPACE_VERSION);
644     }
645   }
646   return -1;
647 }
648 
NativeBridgeGetError()649 const char* NativeBridgeGetError() {
650   if (NativeBridgeInitialized()) {
651     if (isCompatibleWith(NAMESPACE_VERSION)) {
652       return callbacks->getError();
653     } else {
654       return "native bridge implementation is not compatible with version 3, cannot get message";
655     }
656   }
657   return "native bridge is not initialized";
658 }
659 
NativeBridgeIsPathSupported(const char * path)660 bool NativeBridgeIsPathSupported(const char* path) {
661   if (NativeBridgeInitialized()) {
662     if (isCompatibleWith(NAMESPACE_VERSION)) {
663       return callbacks->isPathSupported(path);
664     } else {
665       ALOGE("not compatible with version %d, cannot check via library path", NAMESPACE_VERSION);
666     }
667   }
668   return false;
669 }
670 
NativeBridgeInitAnonymousNamespace(const char * public_ns_sonames,const char * anon_ns_library_path)671 bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
672                                         const char* anon_ns_library_path) {
673   if (NativeBridgeInitialized()) {
674     if (isCompatibleWith(NAMESPACE_VERSION)) {
675       return callbacks->initAnonymousNamespace(public_ns_sonames, anon_ns_library_path);
676     } else {
677       ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
678     }
679   }
680 
681   return false;
682 }
683 
NativeBridgeCreateNamespace(const char * name,const char * ld_library_path,const char * default_library_path,uint64_t type,const char * permitted_when_isolated_path,native_bridge_namespace_t * parent_ns)684 native_bridge_namespace_t* NativeBridgeCreateNamespace(const char* name,
685                                                        const char* ld_library_path,
686                                                        const char* default_library_path,
687                                                        uint64_t type,
688                                                        const char* permitted_when_isolated_path,
689                                                        native_bridge_namespace_t* parent_ns) {
690   if (NativeBridgeInitialized()) {
691     if (isCompatibleWith(NAMESPACE_VERSION)) {
692       return callbacks->createNamespace(name,
693                                         ld_library_path,
694                                         default_library_path,
695                                         type,
696                                         permitted_when_isolated_path,
697                                         parent_ns);
698     } else {
699       ALOGE("not compatible with version %d, cannot create namespace %s", NAMESPACE_VERSION, name);
700     }
701   }
702 
703   return nullptr;
704 }
705 
NativeBridgeLinkNamespaces(native_bridge_namespace_t * from,native_bridge_namespace_t * to,const char * shared_libs_sonames)706 bool NativeBridgeLinkNamespaces(native_bridge_namespace_t* from, native_bridge_namespace_t* to,
707                                 const char* shared_libs_sonames) {
708   if (NativeBridgeInitialized()) {
709     if (isCompatibleWith(NAMESPACE_VERSION)) {
710       return callbacks->linkNamespaces(from, to, shared_libs_sonames);
711     } else {
712       ALOGE("not compatible with version %d, cannot init namespace", NAMESPACE_VERSION);
713     }
714   }
715 
716   return false;
717 }
718 
NativeBridgeGetExportedNamespace(const char * name)719 native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
720   if (!NativeBridgeInitialized()) {
721     return nullptr;
722   }
723 
724   if (isCompatibleWith(RUNTIME_NAMESPACE_VERSION)) {
725     return callbacks->getExportedNamespace(name);
726   }
727 
728   // sphal is vendor namespace name -> use v4 callback in the case NB callbacks
729   // are not compatible with v5
730   if (isCompatibleWith(VENDOR_NAMESPACE_VERSION) && name != nullptr && strcmp("sphal", name) == 0) {
731     return callbacks->getVendorNamespace();
732   }
733 
734   return nullptr;
735 }
736 
NativeBridgeLoadLibraryExt(const char * libpath,int flag,native_bridge_namespace_t * ns)737 void* NativeBridgeLoadLibraryExt(const char* libpath, int flag, native_bridge_namespace_t* ns) {
738   if (NativeBridgeInitialized()) {
739     if (isCompatibleWith(NAMESPACE_VERSION)) {
740       return callbacks->loadLibraryExt(libpath, flag, ns);
741     } else {
742       ALOGE("not compatible with version %d, cannot load library in namespace", NAMESPACE_VERSION);
743     }
744   }
745   return nullptr;
746 }
747 
748 }  // extern "C"
749 
750 }  // namespace android
751