-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathjvm_ref.h
More file actions
255 lines (223 loc) · 8.8 KB
/
jvm_ref.h
File metadata and controls
255 lines (223 loc) · 8.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef JNI_BIND_JVM_REF_H_
#define JNI_BIND_JVM_REF_H_
// IWYU pragma: private, include "third_party/jni_wrapper/jni_bind.h"
#include <cstddef>
#include <memory>
#include <utility>
#include "class_defs/android/activity_thread.h"
#include "class_defs/android/application.h"
#include "class_defs/java_lang_classes.h"
#include "implementation/class_ref.h"
#include "implementation/configuration.h"
#include "implementation/default_class_loader.h"
#include "implementation/field_ref.h"
#include "implementation/forward_declarations.h"
#include "implementation/global_class_loader.h"
#include "implementation/jni_helper/invoke_static.h" // NOLINT
#include "implementation/jni_helper/jni_env.h"
#include "implementation/jni_helper/jni_helper.h"
#include "implementation/jni_helper/lifecycle.h"
#include "implementation/jni_helper/lifecycle_object.h"
#include "implementation/jni_type.h"
#include "implementation/jvm.h"
#include "implementation/jvm_ref_base.h"
#include "implementation/local_object.h"
#include "implementation/no_class_specified.h"
#include "implementation/promotion_mechanics_tags.h"
#include "implementation/ref_storage.h"
#include "implementation/static_ref.h"
#include "implementation/thread_guard.h"
#include "jni_dep.h"
#include "metaprogramming/double_locked_value.h"
namespace jni {
// Represents a runtime instance of a Java Virtual Machine.
// The caller is responsible for dropping this object from scope when
// JNI_OnUnload is called.
//
// For any new thread spawned, a ThreadGuard must be held. The caller is
// responsible for ensuring all ThreadGuards fall from scope before JvmRef falls
// from scope.
//
// The caller is also responsible for thread safety of all objects that have
// been built during the lifetime of the JVM. i.e If any objects have been
// built, they must fall from scope prior to JvmRef falling from scope.
//
// There should only be one instance of JvmRef created at a time. If the
// lifetimes of multiple JvmRef overlap, then one instance may get an invalid
// JavaVM after the first instance is destroyed.
template <const auto& jvm_v_>
class JvmRef : public JvmRefBase {
public:
template <size_t ClassLoaderIdx>
struct TeardownClassesHelper {
template <size_t... Is>
static constexpr void TeardownClass(
std::index_sequence<Is...> index_sequence) {
(ClassRef_t<JniT<jobject, kNoClassSpecified, kDefaultClassLoader, jvm_v_,
0, Is, ClassLoaderIdx>
>::MaybeReleaseClassRef(),
...);
}
};
template <size_t... Is>
constexpr void TeardownClassloadersHelper(
std::index_sequence<Is...> index_sequence) {
(TeardownClassesHelper<Is>::TeardownClass(
std::make_index_sequence<
std::tuple_size_v<decltype(std::get<Is>(jvm_v_.class_loaders_)
.supported_classes_)>>()),
...);
}
JavaVM* BuildJavaVMFromEnv(JNIEnv* env) {
JavaVM* vm = nullptr;
// 0 Is success.
if (env->GetJavaVM(&vm) == 0) {
return vm;
} else {
return nullptr;
}
}
explicit JvmRef(JNIEnv* env, const Configuration& configuration = {})
: JvmRefBase(BuildJavaVMFromEnv(env), configuration) {
ScrapeAndroidFallbackLoader(env);
}
explicit JvmRef(JavaVM* vm, const Configuration& configuration = {})
: JvmRefBase(vm, configuration) {
ScrapeAndroidFallbackLoader(JniEnv::GetEnv());
}
~JvmRef() {
if (kConfiguration.release_class_ids_on_teardown_) {
TeardownClassloadersHelper(
std::make_index_sequence<
std::tuple_size_v<decltype(jvm_v_.class_loaders_)>>());
auto& default_loaded_class_list = DefaultRefs<jclass>();
for (metaprogramming::DoubleLockedValue<jclass>* maybe_loaded_class_id :
default_loaded_class_list) {
maybe_loaded_class_id->Reset([](jclass clazz) {
LifecycleHelper<jobject, LifecycleType::GLOBAL>::Delete(clazz);
});
}
default_loaded_class_list.clear();
}
if (kConfiguration.release_method_ids_on_teardown_) {
// Methods do not need to be released, just forgotten.
auto& default_loaded_method_ref_list = DefaultRefs<jmethodID>();
for (metaprogramming::DoubleLockedValue<jmethodID>* cached_method_id :
default_loaded_method_ref_list) {
cached_method_id->Reset();
}
default_loaded_method_ref_list.clear();
}
if (kConfiguration.release_field_ids_on_teardown_) {
// Fields do not need to be released, just forgotten.
auto& default_loaded_field_ref_list = GetDefaultLoadedFieldList();
for (metaprogramming::DoubleLockedValue<jfieldID>* cached_field_id :
default_loaded_field_ref_list) {
cached_field_id->Reset();
}
default_loaded_field_ref_list.clear();
}
}
// Deleted in order to make various threading guarantees (see class_ref.h).
JvmRef(const JvmRef&) = delete;
JvmRef(JvmRef&&) = delete;
// All new threads MUST create a guard by calling |BuildThreadGuard|.
// If a JNIEnv does not exist, this will DetachCurrentThread when done.
[[nodiscard]] ThreadGuard BuildThreadGuard() const { return {}; }
// Sets a "fallback" loader for use when default Jvm classes fail to load.
// This is useful for first use of classes on secondary threads where the
// jclass is not yet cached and the classloader isn't available directly.
void SetFallbackClassLoader(
jni::GlobalClassLoader<kDefaultClassLoader, kDefaultJvm>&& loader) {
fallback_loader_.reset(
new jni::GlobalClassLoader<kDefaultClassLoader, kDefaultJvm>(
AdoptGlobal{}, loader.Release()));
FallbackLoader() = static_cast<jobject>(*fallback_loader_);
}
// Sets a "fallback" loader for use when default Jvm classes fail to load.
// `host_object *must* be local and will *not* be released.
void SetFallbackClassLoaderFromJObject(jobject host_object) {
#if __cplusplus >= 202002L
SetFallbackClassLoader(LocalObject<kJavaLangObject>{host_object}
.Call<"getClass">()
.Call<"getClassLoader">());
#elif __clang__
SetFallbackClassLoader(LocalObject<kJavaLangObject>{host_object}(
"getClass")("getClassLoader"));
#else
static_assert(false,
"JNI Bind requires C++20 (or later) or C++17 with clang.");
#endif
}
private:
// This function attempts to find an Android application class loader
// by scraping it from the current ActivityThread.
// It only has an effect on Android where ActivityThread is available.
void ScrapeAndroidFallbackLoader(JNIEnv* env) {
if (JniHelper::FindClass(kActivityThreadClass.name_) == nullptr) {
env->ExceptionClear();
return;
}
#if __cplusplus >= 202002L
LocalObject<kActivityThreadClass> activity_thread =
StaticRef<kActivityThreadClass>{}.Call<"currentActivityThread">();
if (jobject{activity_thread} == nullptr) {
return;
}
LocalObject<kApplicationClass> application =
activity_thread.Call<"getApplication">();
if (jobject{application} == nullptr) {
return;
}
LocalObject<kJavaLangClassLoader> class_loader =
application.Call<"getClassLoader">();
if (jobject{class_loader} == nullptr) {
return;
}
SetFallbackClassLoader(std::move(class_loader));
#elif __clang__
LocalObject<kActivityThreadClass> activity_thread =
StaticRef<kActivityThreadClass>{}("currentActivityThread");
if (jobject{activity_thread} == nullptr) {
return;
}
LocalObject<kApplicationClass> application =
activity_thread("getApplication");
if (jobject{application} == nullptr) {
return;
}
LocalObject<kJavaLangClassLoader> class_loader =
application("getClassLoader");
if (jobject{class_loader} == nullptr) {
return;
}
SetFallbackClassLoader(std::move(class_loader));
#else
static_assert(false,
"JNI Bind requires C++20 (or later) or C++17 with clang.");
#endif
}
// Main thread has a JNIEnv just like every other thread.
const ThreadGuard thread_guard_ = {};
std::unique_ptr<jni::GlobalClassLoader<kDefaultClassLoader, kDefaultJvm>>
fallback_loader_;
};
JvmRef(JNIEnv*) -> JvmRef<kDefaultJvm>;
JvmRef(JavaVM*) -> JvmRef<kDefaultJvm>;
} // namespace jni
#endif // JNI_BIND_JVM_REF_H_