blob: 39f5c3fe8acf27318db4232367b654f33c28ebb5 [file] [log] [blame]
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001/*
2 * Copyright (C) 2012 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 */
16
17#ifndef ART_SRC_SCOPED_THREAD_STATE_CHANGE_H_
18#define ART_SRC_SCOPED_THREAD_STATE_CHANGE_H_
19
20#include "casts.h"
Ian Rogers81d425b2012-09-27 16:03:43 -070021#include "jni_internal.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070022#include "thread.h"
23
24namespace art {
25
26// Scoped change into and out of a particular state. Handles Runnable transitions that require
27// more complicated suspension checking. The subclasses ScopedObjectAccessUnchecked and
28// ScopedObjectAccess are used to handle the change into Runnable to get direct access to objects,
29// the unchecked variant doesn't aid annotalysis.
30class ScopedThreadStateChange {
31 public:
32 ScopedThreadStateChange(Thread* self, ThreadState new_thread_state)
Ian Rogersb726dcb2012-09-05 08:57:23 -070033 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
Ian Rogers00f7d0e2012-07-19 15:28:27 -070034 : self_(self), thread_state_(new_thread_state), expected_has_no_thread_(false) {
35 if (self_ == NULL) {
36 // Value chosen arbitrarily and won't be used in the destructor since thread_ == NULL.
37 old_thread_state_ = kTerminated;
Ian Rogers50b35e22012-10-04 10:09:15 -070038 MutexLock mu(NULL, *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -070039 Runtime* runtime = Runtime::Current();
40 CHECK(runtime == NULL || !runtime->IsStarted() || runtime->IsShuttingDown());
Ian Rogers00f7d0e2012-07-19 15:28:27 -070041 } else {
42 bool runnable_transition;
Ian Rogers22f454c2012-09-08 11:06:29 -070043 DCHECK_EQ(self, Thread::Current());
44 // Read state without locks, ok as state is effectively thread local and we're not interested
45 // in the suspend count (this will be handled in the runnable transitions).
Ian Rogers474b6da2012-09-25 00:20:38 -070046 old_thread_state_ = self->GetState();
Ian Rogers22f454c2012-09-08 11:06:29 -070047 runnable_transition = old_thread_state_ == kRunnable || new_thread_state == kRunnable;
48 if (!runnable_transition) {
49 // A suspended transition to another effectively suspended transition, ok to use Unsafe.
Ian Rogers474b6da2012-09-25 00:20:38 -070050 self_->SetState(new_thread_state);
Ian Rogers00f7d0e2012-07-19 15:28:27 -070051 }
Mathieu Chartier858f1c52012-10-17 17:45:55 -070052
Ian Rogers00f7d0e2012-07-19 15:28:27 -070053 if (runnable_transition && old_thread_state_ != new_thread_state) {
54 if (new_thread_state == kRunnable) {
55 self_->TransitionFromSuspendedToRunnable();
56 } else {
57 DCHECK_EQ(old_thread_state_, kRunnable);
58 self_->TransitionFromRunnableToSuspended(new_thread_state);
59 }
60 }
61 }
62 }
63
Ian Rogersb726dcb2012-09-05 08:57:23 -070064 ~ScopedThreadStateChange() LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -070065 if (self_ == NULL) {
66 if (!expected_has_no_thread_) {
Ian Rogers50b35e22012-10-04 10:09:15 -070067 MutexLock mu(NULL, *Locks::runtime_shutdown_lock_);
Ian Rogers120f1c72012-09-28 17:17:10 -070068 Runtime* runtime = Runtime::Current();
69 bool shutting_down = (runtime == NULL) || runtime->IsShuttingDown();
70 CHECK(shutting_down);
Ian Rogers00f7d0e2012-07-19 15:28:27 -070071 }
72 } else {
73 if (old_thread_state_ != thread_state_) {
74 if (old_thread_state_ == kRunnable) {
75 self_->TransitionFromSuspendedToRunnable();
76 } else if (thread_state_ == kRunnable) {
77 self_->TransitionFromRunnableToSuspended(old_thread_state_);
78 } else {
Ian Rogers22f454c2012-09-08 11:06:29 -070079 // A suspended transition to another effectively suspended transition, ok to use Unsafe.
Ian Rogers474b6da2012-09-25 00:20:38 -070080 self_->SetState(old_thread_state_);
Ian Rogers00f7d0e2012-07-19 15:28:27 -070081 }
82 }
83 }
84 }
85
86 Thread* Self() const {
87 return self_;
88 }
89
90 protected:
91 // Constructor used by ScopedJniThreadState for an unattached thread that has access to the VM*.
92 ScopedThreadStateChange()
93 : self_(NULL), thread_state_(kTerminated), old_thread_state_(kTerminated),
94 expected_has_no_thread_(true) {}
95
96 Thread* const self_;
97 const ThreadState thread_state_;
98
99 private:
100 ThreadState old_thread_state_;
101 const bool expected_has_no_thread_;
102
103 DISALLOW_COPY_AND_ASSIGN(ScopedThreadStateChange);
104};
105
106// Entry/exit processing for transitions from Native to Runnable (ie within JNI functions).
107//
108// This class performs the necessary thread state switching to and from Runnable and lets us
109// amortize the cost of working out the current thread. Additionally it lets us check (and repair)
110// apps that are using a JNIEnv on the wrong thread. The class also decodes and encodes Objects
111// into jobjects via methods of this class. Performing this here enforces the Runnable thread state
112// for use of Object, thereby inhibiting the Object being modified by GC whilst native or VM code
113// is also manipulating the Object.
114//
115// The destructor transitions back to the previous thread state, typically Native. In this state
116// GC and thread suspension may occur.
117//
118// For annotalysis the subclass ScopedObjectAccess (below) makes it explicit that a shared of
119// the mutator_lock_ will be acquired on construction.
120class ScopedObjectAccessUnchecked : public ScopedThreadStateChange {
121 public:
122 explicit ScopedObjectAccessUnchecked(JNIEnv* env)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700123 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700124 : ScopedThreadStateChange(ThreadForEnv(env), kRunnable),
125 env_(reinterpret_cast<JNIEnvExt*>(env)), vm_(env_->vm) {
126 self_->VerifyStack();
127 }
128
129 explicit ScopedObjectAccessUnchecked(Thread* self)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700130 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700131 : ScopedThreadStateChange(self, kRunnable),
132 env_(reinterpret_cast<JNIEnvExt*>(self->GetJniEnv())),
133 vm_(env_ != NULL ? env_->vm : NULL) {
134 if (Vm() != NULL && !Vm()->work_around_app_jni_bugs && self != Thread::Current()) {
135 UnexpectedThreads(self, Thread::Current());
136 }
137 self_->VerifyStack();
138 }
139
140 // Used when we want a scoped JNI thread state but have no thread/JNIEnv. Consequently doesn't
141 // change into Runnable or acquire a share on the mutator_lock_.
142 explicit ScopedObjectAccessUnchecked(JavaVM* vm)
143 : ScopedThreadStateChange(), env_(NULL), vm_(reinterpret_cast<JavaVMExt*>(vm)) {}
144
145 JNIEnvExt* Env() const {
146 return env_;
147 }
148
149 JavaVMExt* Vm() const {
150 return vm_;
151 }
152
153 /*
154 * Add a local reference for an object to the indirect reference table associated with the
155 * current stack frame. When the native function returns, the reference will be discarded.
156 * Part of the ScopedJniThreadState as native code shouldn't be working on raw Object* without
157 * having transitioned its state.
158 *
159 * We need to allow the same reference to be added multiple times.
160 *
161 * This will be called on otherwise unreferenced objects. We cannot do GC allocations here, and
162 * it's best if we don't grab a mutex.
163 *
164 * Returns the local reference (currently just the same pointer that was
165 * passed in), or NULL on failure.
166 */
167 template<typename T>
168 T AddLocalReference(Object* obj) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700169 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700170 DCHECK_EQ(thread_state_, kRunnable); // Don't work with raw objects in non-runnable states.
171 if (obj == NULL) {
172 return NULL;
173 }
174
175 DCHECK_NE((reinterpret_cast<uintptr_t>(obj) & 0xffff0000), 0xebad0000);
176
177 IndirectReferenceTable& locals = Env()->locals;
178
179 uint32_t cookie = Env()->local_ref_cookie;
180 IndirectRef ref = locals.Add(cookie, obj);
181
182#if 0 // TODO: fix this to understand PushLocalFrame, so we can turn it on.
183 if (Env()->check_jni) {
184 size_t entry_count = locals.Capacity();
185 if (entry_count > 16) {
186 LOG(WARNING) << "Warning: more than 16 JNI local references: "
187 << entry_count << " (most recent was a " << PrettyTypeOf(obj) << ")\n"
188 << Dumpable<IndirectReferenceTable>(locals);
189 // TODO: LOG(FATAL) in a later release?
190 }
191 }
192#endif
193
194 if (Vm()->work_around_app_jni_bugs) {
195 // Hand out direct pointers to support broken old apps.
196 return reinterpret_cast<T>(obj);
197 }
198
199 return reinterpret_cast<T>(ref);
200 }
201
202 template<typename T>
203 T Decode(jobject obj) const
204 LOCKS_EXCLUDED(JavaVMExt::globals_lock,
205 JavaVMExt::weak_globals_lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700206 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700207 Locks::mutator_lock_->AssertSharedHeld(Self());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700208 DCHECK_EQ(thread_state_, kRunnable); // Don't work with raw objects in non-runnable states.
209 return down_cast<T>(Self()->DecodeJObject(obj));
210 }
211
212 Field* DecodeField(jfieldID fid) const
213 LOCKS_EXCLUDED(JavaVMExt::globals_lock,
214 JavaVMExt::weak_globals_lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700215 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700216 Locks::mutator_lock_->AssertSharedHeld(Self());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700217 DCHECK_EQ(thread_state_, kRunnable); // Don't work with raw objects in non-runnable states.
218#ifdef MOVING_GARBAGE_COLLECTOR
219 // TODO: we should make these unique weak globals if Field instances can ever move.
220 UNIMPLEMENTED(WARNING);
221#endif
222 return reinterpret_cast<Field*>(fid);
223 }
224
225 jfieldID EncodeField(Field* field) const
226 LOCKS_EXCLUDED(JavaVMExt::globals_lock,
227 JavaVMExt::weak_globals_lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700228 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700229 Locks::mutator_lock_->AssertSharedHeld(Self());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700230 DCHECK_EQ(thread_state_, kRunnable); // Don't work with raw objects in non-runnable states.
231#ifdef MOVING_GARBAGE_COLLECTOR
232 UNIMPLEMENTED(WARNING);
233#endif
234 return reinterpret_cast<jfieldID>(field);
235 }
236
Mathieu Chartier66f19252012-09-18 08:57:04 -0700237 AbstractMethod* DecodeMethod(jmethodID mid) const
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700238 LOCKS_EXCLUDED(JavaVMExt::globals_lock,
239 JavaVMExt::weak_globals_lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700240 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700241 Locks::mutator_lock_->AssertSharedHeld(Self());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700242 DCHECK_EQ(thread_state_, kRunnable); // Don't work with raw objects in non-runnable states.
243#ifdef MOVING_GARBAGE_COLLECTOR
244 // TODO: we should make these unique weak globals if Method instances can ever move.
245 UNIMPLEMENTED(WARNING);
246#endif
Mathieu Chartier66f19252012-09-18 08:57:04 -0700247 return reinterpret_cast<AbstractMethod*>(mid);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700248 }
249
Mathieu Chartier66f19252012-09-18 08:57:04 -0700250 jmethodID EncodeMethod(AbstractMethod* method) const
Ian Rogersb726dcb2012-09-05 08:57:23 -0700251 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700252 Locks::mutator_lock_->AssertSharedHeld(Self());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700253 DCHECK_EQ(thread_state_, kRunnable); // Don't work with raw objects in non-runnable states.
254#ifdef MOVING_GARBAGE_COLLECTOR
255 UNIMPLEMENTED(WARNING);
256#endif
257 return reinterpret_cast<jmethodID>(method);
258 }
259
260 private:
261 static Thread* ThreadForEnv(JNIEnv* env) {
262 JNIEnvExt* full_env(reinterpret_cast<JNIEnvExt*>(env));
263 bool work_around_app_jni_bugs = full_env->vm->work_around_app_jni_bugs;
264 Thread* env_self = full_env->self;
265 Thread* self = work_around_app_jni_bugs ? Thread::Current() : env_self;
266 if (!work_around_app_jni_bugs && self != env_self) {
267 UnexpectedThreads(env_self, self);
268 }
269 return self;
270 }
271
272 static void UnexpectedThreads(Thread* found_self, Thread* expected_self) {
273 // TODO: pass through function name so we can use it here instead of NULL...
274 JniAbortF(NULL, "JNIEnv for %s used on %s",
275 found_self != NULL ? ToStr<Thread>(*found_self).c_str() : "NULL",
276 expected_self != NULL ? ToStr<Thread>(*expected_self).c_str() : "NULL");
277
278 }
279
280 // The full JNIEnv.
281 JNIEnvExt* const env_;
282 // The full JavaVM.
283 JavaVMExt* const vm_;
284
285 DISALLOW_COPY_AND_ASSIGN(ScopedObjectAccessUnchecked);
286};
287
288// Annotalysis helping variant of the above.
289class ScopedObjectAccess : public ScopedObjectAccessUnchecked {
290 public:
291 explicit ScopedObjectAccess(JNIEnv* env)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700292 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
293 SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700294 : ScopedObjectAccessUnchecked(env) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700295 Locks::mutator_lock_->AssertSharedHeld(Self());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700296 }
297
298 explicit ScopedObjectAccess(Thread* self)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700299 LOCKS_EXCLUDED(Locks::thread_suspend_count_lock_)
300 SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700301 : ScopedObjectAccessUnchecked(self) {
Ian Rogers81d425b2012-09-27 16:03:43 -0700302 Locks::mutator_lock_->AssertSharedHeld(Self());
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700303 }
304
Ian Rogersb726dcb2012-09-05 08:57:23 -0700305 ~ScopedObjectAccess() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700306 // Base class will release share of lock. Invoked after this destructor.
307 }
308
309 private:
310 // TODO: remove this constructor. It is used by check JNI's ScopedCheck to make it believe that
311 // routines operating with just a VM are sound, they are not, but when you have just a VM
312 // you cannot call the unsound routines.
313 explicit ScopedObjectAccess(JavaVM* vm)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700314 SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700315 : ScopedObjectAccessUnchecked(vm) {}
316
317 friend class ScopedCheck;
318 DISALLOW_COPY_AND_ASSIGN(ScopedObjectAccess);
319};
320
321} // namespace art
322
323#endif // ART_SRC_SCOPED_THREAD_STATE_CHANGE_H_