blob: dd39cc33194771d5708e21d9d27601eece433e10 [file] [log] [blame]
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2// Author: enh@google.com (Elliott Hughes)
3
4#include "jni_internal.h"
5
6namespace art {
7
8// Entry/exit processing for all JNI calls.
9//
10// This performs the necessary thread state switching, lets us amortize the
11// cost of working out the current thread, and lets us check (and repair) apps
12// that are using a JNIEnv on the wrong thread.
13class ScopedJniThreadState {
14 public:
15 explicit ScopedJniThreadState(JNIEnv* env)
16 : env_(reinterpret_cast<JNIEnvExt*>(env)) {
17 self_ = ThreadForEnv(env);
18 self_->SetState(Thread::kRunnable);
19 }
20
21 ~ScopedJniThreadState() {
22 self_->SetState(Thread::kNative);
23 }
24
25 JNIEnvExt* Env() {
26 return env_;
27 }
28
29 Thread* Self() {
30 return self_;
31 }
32
33 JavaVMExt* Vm() {
34 return env_->vm;
35 }
36
37 private:
38 static Thread* ThreadForEnv(JNIEnv* env) {
39 JNIEnvExt* full_env(reinterpret_cast<JNIEnvExt*>(env));
40 Thread* env_self = full_env->self;
41 Thread* self = full_env->work_around_app_jni_bugs ? Thread::Current() : env_self;
42 if (self != env_self) {
43 LOG(ERROR) << "JNI ERROR: JNIEnv for " << *env_self
44 << " used on " << *self;
45 // TODO: dump stack
46 }
47 return self;
48 }
49
50 JNIEnvExt* env_;
51 Thread* self_;
52 DISALLOW_COPY_AND_ASSIGN(ScopedJniThreadState);
53};
54
55} // namespace art