1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "cj_envsetup.h"
17
18 #ifdef __LINUX__
19 #include <dlfcn.h>
OpenLib(const char * name)20 static void* OpenLib(const char* name)
21 {
22 return dlopen(name, RTLD_NOW);
23 }
FindSym(void * handle,const char * name)24 static void* FindSym(void* handle, const char* name)
25 {
26 return dlsym(handle, name);
27 }
28 #ifndef __OHOS__
29 #define LIB_NAME "libcj_environment.so"
30 #else
31 #define LIB_NAME "libcj_environment.z.so"
32 #endif
33 #elif defined(__WINDOWS__)
34 #include <libloaderapi.h>
OpenLib(const char * name)35 static void* OpenLib(const char* name)
36 {
37 return LoadLibraryA(name);
38 }
FindSym(void * handle,const char * name)39 static void* FindSym(void* handle, const char* name)
40 {
41 return reinterpret_cast<void*>(GetProcAddress(reinterpret_cast<HMODULE>(handle), name));
42 }
43 #define LIB_NAME "libcj_environment.dll"
44 #else
45 #error "unsupported platform"
46 #endif
47 #define GET_ENV_INS_NAME "OHOS_GetCJEnvInstance"
48
49 namespace OHOS {
LoadInstance()50 CJEnvMethods* CJEnv::LoadInstance()
51 {
52 auto handle = OpenLib(LIB_NAME);
53 if (!handle) {
54 return nullptr;
55 }
56 auto symbol = FindSym(handle, GET_ENV_INS_NAME);
57 if (!symbol) {
58 return nullptr;
59 }
60 auto func = reinterpret_cast<CJEnvMethods* (*)()>(symbol);
61 return func();
62 }
63
64 } // OHOS