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 "java_internal.h"
17
18 #include <core/log.h>
19
20 namespace java_internal {
21 namespace {
22 JavaVM* sJavaVM = nullptr;
23
24 extern "C" {
JNI_OnLoad(JavaVM * vm,void * reserved)25 JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved)
26 {
27 CORE_LOG_V("JNI_OnLoad");
28 sJavaVM = vm;
29 return JNI_VERSION_1_6;
30 }
31 }
32 } // unnamed namespace
33
GetJavaVM()34 JavaVM* GetJavaVM()
35 {
36 return sJavaVM;
37 }
38
SetJavaVM(JavaVM * jvm)39 void SetJavaVM(JavaVM* jvm)
40 {
41 CORE_ASSERT(jvm);
42 sJavaVM = jvm;
43 }
44
GetJavaEnv()45 JNIEnv* GetJavaEnv()
46 {
47 CORE_ASSERT(java_internal::sJavaVM);
48 if (!java_internal::sJavaVM) {
49 CORE_ASSERT_MSG(true, "JNI ERROR: sJavaVM not initialized.");
50 return nullptr;
51 }
52
53 JNIEnv* env = nullptr;
54 jint result = sJavaVM->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6);
55
56 switch (result) {
57 case JNI_OK: {
58 return env;
59 }
60
61 case JNI_EDETACHED: {
62 CORE_ASSERT_MSG(true, "JNI ERROR: Thread not attached.");
63 return nullptr;
64 }
65
66 case JNI_EVERSION: {
67 CORE_ASSERT_MSG(true, "JNI ERROR: Invalid version.");
68 return nullptr;
69 }
70
71 default: {
72 CORE_ASSERT(true);
73 return nullptr;
74 }
75 }
76 }
77 } // namespace java_internal
78