blob: 0da03d66a49e7ff8a9de08c7be1998e2ffeb33dc [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);
Elliott Hughesad7c2a32011-08-31 11:58:10 -070018 old_thread_state_ = self_->SetState(Thread::kRunnable);
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -070019 }
20
21 ~ScopedJniThreadState() {
Elliott Hughesad7c2a32011-08-31 11:58:10 -070022 self_->SetState(old_thread_state_);
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -070023 }
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_;
Elliott Hughesad7c2a32011-08-31 11:58:10 -070052 Thread::State old_thread_state_;
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -070053 DISALLOW_COPY_AND_ASSIGN(ScopedJniThreadState);
54};
55
56} // namespace art