Elliott Hughes | c5bfa8f | 2011-08-30 14:32:49 -0700 | [diff] [blame] | 1 | // Copyright 2011 Google Inc. All Rights Reserved. |
| 2 | // Author: enh@google.com (Elliott Hughes) |
| 3 | |
| 4 | #include "jni_internal.h" |
| 5 | |
| 6 | namespace 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. |
| 13 | class ScopedJniThreadState { |
| 14 | public: |
| 15 | explicit ScopedJniThreadState(JNIEnv* env) |
| 16 | : env_(reinterpret_cast<JNIEnvExt*>(env)) { |
| 17 | self_ = ThreadForEnv(env); |
Elliott Hughes | ad7c2a3 | 2011-08-31 11:58:10 -0700 | [diff] [blame] | 18 | old_thread_state_ = self_->SetState(Thread::kRunnable); |
Elliott Hughes | c5bfa8f | 2011-08-30 14:32:49 -0700 | [diff] [blame] | 19 | } |
| 20 | |
| 21 | ~ScopedJniThreadState() { |
Elliott Hughes | ad7c2a3 | 2011-08-31 11:58:10 -0700 | [diff] [blame] | 22 | self_->SetState(old_thread_state_); |
Elliott Hughes | c5bfa8f | 2011-08-30 14:32:49 -0700 | [diff] [blame] | 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_; |
Elliott Hughes | ad7c2a3 | 2011-08-31 11:58:10 -0700 | [diff] [blame] | 52 | Thread::State old_thread_state_; |
Elliott Hughes | c5bfa8f | 2011-08-30 14:32:49 -0700 | [diff] [blame] | 53 | DISALLOW_COPY_AND_ASSIGN(ScopedJniThreadState); |
| 54 | }; |
| 55 | |
| 56 | } // namespace art |