/
Environment.cpp
386 lines (324 loc) · 9.04 KB
/
Environment.cpp
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
#include <fbjni/fbjni.h>
#ifdef __ANDROID__
#include <sys/prctl.h>
#endif // __ANDROID__
#include <functional>
#include <vector>
#ifndef _WIN32
#include <pthread.h>
#else
#include <windows.h>
#endif
namespace facebook {
namespace jni {
namespace {
JavaVM* g_vm = nullptr;
struct EnvironmentInitializer {
EnvironmentInitializer(JavaVM* vm) {
FBJNI_ASSERT(!g_vm);
FBJNI_ASSERT(vm);
g_vm = vm;
}
};
int getEnv(JNIEnv** env) {
FBJNI_ASSERT(g_vm);
// g_vm->GetEnv() might not clear the env* in failure cases.
*env = nullptr;
jint ret = g_vm->GetEnv((void**)env, JNI_VERSION_1_6);
// Other possibilites are that JNI_VERSION_1_6 is invalid, or some
// unknown return was received.
FBJNI_ASSERT(ret == JNI_OK || ret == JNI_EDETACHED);
return ret;
}
// Some jni.h define the first arg to AttachCurrentThread as void**,
// and some as JNIEnv**. This hack allows both to work.
template <typename>
struct AttachTraits;
template <>
struct AttachTraits<jint (JavaVM::*)(JNIEnv**, void*)> {
using EnvType = JNIEnv*;
};
template <>
struct AttachTraits<jint (JavaVM::*)(void**, void*)> {
using EnvType = void*;
};
std::string getThreadName() {
#ifdef _WIN32
return "";
#else // _WIN32
constexpr int kMaxThreadNameSize = 100;
int ret = 0;
char threadName[kMaxThreadNameSize];
#ifdef __ANDROID__
ret = prctl(PR_GET_NAME, threadName);
#else
ret = pthread_getname_np(pthread_self(), threadName, sizeof(threadName));
#endif
if (ret != 0) {
return "";
}
return threadName;
#endif // _WIN32
}
JNIEnv* attachCurrentThread() {
JavaVMAttachArgs args{JNI_VERSION_1_6, nullptr, nullptr};
const auto threadName = getThreadName();
std::vector<char> nameBuf;
if (threadName.size()) {
const char* cName = threadName.c_str();
nameBuf.assign(cName, cName + threadName.size() + 1);
args.name = nameBuf.data();
}
using AttachEnvType =
typename AttachTraits<decltype(&JavaVM::AttachCurrentThread)>::EnvType;
AttachEnvType env;
auto result = g_vm->AttachCurrentThread(&env, &args);
FBJNI_ASSERT(result == JNI_OK);
return reinterpret_cast<JNIEnv*>(env);
}
} // namespace
/* static */
void Environment::initialize(JavaVM* vm) {
static EnvironmentInitializer init(vm);
}
namespace {
#ifndef _WIN32
typedef pthread_key_t tls_key_t;
#else
typedef DWORD tls_key_t;
#endif
tls_key_t makeKey() {
tls_key_t key;
#ifndef _WIN32
int ret = pthread_key_create(&key, nullptr);
if (ret != 0) {
FBJNI_LOGF("pthread_key_create failed: %d", ret);
}
#else
key = TlsAlloc();
if (key == TLS_OUT_OF_INDEXES) {
FBJNI_LOGF("TlsAlloc failed");
}
#endif
return key;
}
tls_key_t getTLKey() {
static tls_key_t key = makeKey();
return key;
}
inline detail::TLData* getTLData(tls_key_t key) {
#ifndef _WIN32
void* raw_data = pthread_getspecific(key);
#else
LPVOID raw_data = TlsGetValue(key);
// TODO: Maybe check for errors here?
#endif
return reinterpret_cast<detail::TLData*>(raw_data);
}
inline void setTLData(tls_key_t key, detail::TLData* data) {
#ifndef _WIN32
int ret = pthread_setspecific(key, data);
if (ret != 0) {
(void)ret;
FBJNI_LOGF("pthread_setspecific failed: %d", ret);
}
#else
BOOL ret = TlsSetValue(key, data);
if (!ret) {
FBJNI_LOGF("TlsSetValue failed: %d", GetLastError());
}
#endif
}
// This returns non-nullptr iff the env was cached from java. So it
// can return nullptr for a thread which has been registered.
inline JNIEnv* cachedOrNull() {
detail::TLData* pdata = getTLData(getTLKey());
return (pdata ? pdata->env : nullptr);
}
} // namespace
namespace detail {
JNIEnv* cachedWithAttachmentState(bool& isAttaching) {
isAttaching = false;
detail::TLData* pdata = getTLData(getTLKey());
if (!pdata) {
return nullptr;
}
if (!pdata->env && !pdata->attached) {
isAttaching = true;
}
return pdata->env;
}
// This will return a cached env if there is one, or get one from JNI
// if the thread has already been attached some other way. If it
// returns nullptr, then the thread has never been registered, or the
// VM has never been set up for fbjni.
JNIEnv* currentOrNull() {
if (!g_vm) {
return nullptr;
}
detail::TLData* pdata = getTLData(getTLKey());
if (pdata && pdata->env) {
return pdata->env;
}
JNIEnv* env;
if (getEnv(&env) != JNI_OK) {
// If there's a ThreadScope on the stack, we should have gotten a
// JNIEnv and not ended up here.
FBJNI_ASSERT(!pdata || !pdata->attached);
}
return env;
}
// To understand JniEnvCacher and ThreadScope, it is helpful to
// realize that if a flagged JniEnvCacher is on the stack, then a
// flagged ThreadScope cannot be after it. If a flagged ThreadCacher
// is on the stack, then a JniEnvCacher *can* be after it. So,
// ThreadScope's setup and teardown can both assume they are the
// first/last interesting objects, but this is not true of
// JniEnvCacher.
JniEnvCacher::JniEnvCacher(JNIEnv* env) : thisCached_(false) {
FBJNI_ASSERT(env);
tls_key_t key = getTLKey();
detail::TLData* pdata = getTLData(key);
if (pdata && pdata->env) {
return;
}
if (!pdata) {
pdata = &data_;
setTLData(key, pdata);
pdata->attached = false;
} else {
FBJNI_ASSERT(!pdata->env);
}
pdata->env = env;
thisCached_ = true;
}
JniEnvCacher::~JniEnvCacher() {
if (!thisCached_) {
return;
}
tls_key_t key = getTLKey();
TLData* pdata = getTLData(key);
FBJNI_ASSERT(pdata);
FBJNI_ASSERT(pdata->env != nullptr);
pdata->env = nullptr;
if (!pdata->attached) {
setTLData(key, nullptr);
}
}
} // namespace detail
ThreadScope::ThreadScope() : thisAttached_(false) {
if (g_vm == nullptr) {
throw std::runtime_error(
"fbjni is uninitialized; no thread can be attached.");
}
JNIEnv* env;
// Check if the thread is attached somehow.
auto result = getEnv(&env);
if (result == JNI_OK) {
return;
}
// At this point, it appears there's no thread attached and no env is
// cached, or we would have returned already. So there better not
// be TLData.
tls_key_t key = getTLKey();
detail::TLData* pdata = getTLData(key);
FBJNI_ASSERT(pdata == nullptr);
setTLData(key, &data_);
data_.env = nullptr;
data_.attached = false;
attachCurrentThread();
data_.attached = true;
thisAttached_ = true;
}
ThreadScope::~ThreadScope() {
if (!thisAttached_) {
return;
}
tls_key_t key = getTLKey();
detail::TLData* pdata = getTLData(key);
FBJNI_ASSERT(pdata);
FBJNI_ASSERT(pdata->env == nullptr);
FBJNI_ASSERT(pdata->attached);
FBJNI_ASSERT(g_vm);
g_vm->DetachCurrentThread();
setTLData(key, nullptr);
}
/* static */
JNIEnv* Environment::current() {
FBJNI_ASSERT(g_vm);
JNIEnv* env = detail::currentOrNull();
if (env == nullptr) {
throw std::runtime_error(
"Unable to retrieve jni environment. Is the thread attached?");
}
return env;
}
/* static */
JNIEnv* Environment::ensureCurrentThreadIsAttached() {
FBJNI_ASSERT(g_vm);
JNIEnv* env = detail::currentOrNull();
if (env == nullptr) {
env = attachCurrentThread();
FBJNI_ASSERT(env);
}
return env;
}
/* static */
bool Environment::isGlobalJvmAvailable() {
return g_vm != nullptr;
}
namespace {
struct JThreadScopeSupport : JavaClass<JThreadScopeSupport> {
static auto constexpr kJavaDescriptor =
"Lcom/facebook/jni/ThreadScopeSupport;";
// These reinterpret_casts are a totally dangerous pattern. Don't use them.
// Use HybridData instead.
static void runStdFunction(std::function<void()>&& func) {
static const auto method =
javaClassStatic()->getStaticMethod<void(jlong)>("runStdFunction");
method(javaClassStatic(), reinterpret_cast<jlong>(&func));
}
static void runStdFunctionImpl(alias_ref<JClass>, jlong ptr) {
(*reinterpret_cast<std::function<void()>*>(ptr))();
}
static void OnLoad() {
// We need the javaClassStatic so that the class lookup is cached and that
// runStdFunction can be called from a ThreadScope-attached thread.
javaClassStatic()->registerNatives({
makeNativeMethod("runStdFunctionImpl", runStdFunctionImpl),
});
}
};
} // namespace
/* static */
void ThreadScope::OnLoad() {
// These classes are required for ScopeWithClassLoader. Ensure they are looked
// up when loading.
JThreadScopeSupport::OnLoad();
}
/* static */
void ThreadScope::WithClassLoader(std::function<void()>&& runnable) {
if (cachedOrNull() == nullptr) {
ThreadScope ts;
JThreadScopeSupport::runStdFunction(std::move(runnable));
} else {
runnable();
}
}
} // namespace jni
} // namespace facebook