blob: 2db04fcddedbb5ed8be7212b5d1499f45f749453 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -070016
17#include "jni_internal.h"
18
19namespace art {
20
21// Entry/exit processing for all JNI calls.
22//
23// This performs the necessary thread state switching, lets us amortize the
24// cost of working out the current thread, and lets us check (and repair) apps
25// that are using a JNIEnv on the wrong thread.
26class ScopedJniThreadState {
27 public:
28 explicit ScopedJniThreadState(JNIEnv* env)
29 : env_(reinterpret_cast<JNIEnvExt*>(env)) {
30 self_ = ThreadForEnv(env);
Elliott Hughesad7c2a32011-08-31 11:58:10 -070031 old_thread_state_ = self_->SetState(Thread::kRunnable);
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -070032 }
33
34 ~ScopedJniThreadState() {
Elliott Hughesad7c2a32011-08-31 11:58:10 -070035 self_->SetState(old_thread_state_);
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -070036 }
37
38 JNIEnvExt* Env() {
39 return env_;
40 }
41
42 Thread* Self() {
43 return self_;
44 }
45
46 JavaVMExt* Vm() {
47 return env_->vm;
48 }
49
50 private:
51 static Thread* ThreadForEnv(JNIEnv* env) {
52 JNIEnvExt* full_env(reinterpret_cast<JNIEnvExt*>(env));
53 Thread* env_self = full_env->self;
Elliott Hughesc2dc62d2012-01-17 20:06:12 -080054 Thread* self = full_env->vm->work_around_app_jni_bugs ? Thread::Current() : env_self;
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -070055 if (self != env_self) {
56 LOG(ERROR) << "JNI ERROR: JNIEnv for " << *env_self
57 << " used on " << *self;
58 // TODO: dump stack
59 }
60 return self;
61 }
62
63 JNIEnvExt* env_;
64 Thread* self_;
Elliott Hughesad7c2a32011-08-31 11:58:10 -070065 Thread::State old_thread_state_;
Elliott Hughesc5bfa8f2011-08-30 14:32:49 -070066 DISALLOW_COPY_AND_ASSIGN(ScopedJniThreadState);
67};
68
69} // namespace art