1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "nativebridge/native_bridge.h"
18 #define LOG_TAG "nativebridge"
19 
20 #include <dlfcn.h>
21 #include <errno.h>
22 #include <string.h>
23 
24 #include <log/log.h>
25 
26 namespace android {
27 
28 namespace {
29 
GetLibHandle()30 void* GetLibHandle() {
31   static void* handle = dlopen("libnativebridge.so", RTLD_NOW);
32   LOG_FATAL_IF(handle == nullptr, "Failed to load libnativebridge.so: %s", dlerror());
33   return handle;
34 }
35 
36 template <typename FuncPtr>
GetFuncPtr(const char * function_name)37 FuncPtr GetFuncPtr(const char* function_name) {
38   auto f = reinterpret_cast<FuncPtr>(dlsym(GetLibHandle(), function_name));
39   LOG_FATAL_IF(f == nullptr, "Failed to get address of %s: %s", function_name, dlerror());
40   return f;
41 }
42 
43 #define GET_FUNC_PTR(name) GetFuncPtr<decltype(&(name))>(#name)
44 
45 }  // namespace
46 
NeedsNativeBridge(const char * instruction_set)47 bool NeedsNativeBridge(const char* instruction_set) {
48   static auto f = GET_FUNC_PTR(NeedsNativeBridge);
49   return f(instruction_set);
50 }
51 
PreInitializeNativeBridge(const char * app_data_dir,const char * instruction_set)52 bool PreInitializeNativeBridge(const char* app_data_dir, const char* instruction_set) {
53   static auto f = GET_FUNC_PTR(PreInitializeNativeBridge);
54   return f(app_data_dir, instruction_set);
55 }
56 
NativeBridgeAvailable()57 bool NativeBridgeAvailable() {
58   static auto f = GET_FUNC_PTR(NativeBridgeAvailable);
59   return f();
60 }
61 
NativeBridgeInitialized()62 bool NativeBridgeInitialized() {
63   static auto f = GET_FUNC_PTR(NativeBridgeInitialized);
64   return f();
65 }
66 
NativeBridgeGetTrampoline(void * handle,const char * name,const char * shorty,uint32_t len)67 void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty, uint32_t len) {
68   static auto f = GET_FUNC_PTR(NativeBridgeGetTrampoline);
69   return f(handle, name, shorty, len);
70 }
71 
NativeBridgeGetError()72 const char* NativeBridgeGetError() {
73   static auto f = GET_FUNC_PTR(NativeBridgeGetError);
74   return f();
75 }
76 
77 #undef GET_FUNC_PTR
78 
79 }  // namespace android
80