1 /*
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 #include <android-base/logging.h>
18
19 #include "art_method-inl.h"
20 #include "base/casts.h"
21 #include "entrypoints/entrypoint_utils-inl.h"
22 #include "indirect_reference_table.h"
23 #include "mirror/object-inl.h"
24 #include "palette/palette.h"
25 #include "thread-inl.h"
26 #include "verify_object.h"
27
28 // For methods that monitor JNI invocations and report their begin/end to
29 // palette hooks.
30 #define MONITOR_JNI(kind) \
31 { \
32 bool should_report = false; \
33 PaletteShouldReportJniInvocations(&should_report); \
34 if (should_report) { \
35 kind(self->GetJniEnv()); \
36 } \
37 }
38
39 namespace art {
40
41 static_assert(sizeof(IRTSegmentState) == sizeof(uint32_t), "IRTSegmentState size unexpected");
42 static_assert(std::is_trivial<IRTSegmentState>::value, "IRTSegmentState not trivial");
43
artJniReadBarrier(ArtMethod * method)44 extern "C" void artJniReadBarrier(ArtMethod* method) {
45 DCHECK(kUseReadBarrier);
46 mirror::CompressedReference<mirror::Object>* declaring_class =
47 method->GetDeclaringClassAddressWithoutBarrier();
48 if (kUseBakerReadBarrier) {
49 DCHECK(declaring_class->AsMirrorPtr() != nullptr)
50 << "The class of a static jni call must not be null";
51 // Check the mark bit and return early if it's already marked.
52 if (LIKELY(declaring_class->AsMirrorPtr()->GetMarkBit() != 0)) {
53 return;
54 }
55 }
56 // Call the read barrier and update the handle.
57 mirror::Object* to_ref = ReadBarrier::BarrierForRoot(declaring_class);
58 declaring_class->Assign(to_ref);
59 }
60
61 // Called on entry to JNI, transition out of Runnable and release share of mutator_lock_.
artJniMethodStart(Thread * self)62 extern "C" void artJniMethodStart(Thread* self) {
63 if (kIsDebugBuild) {
64 ArtMethod* native_method = *self->GetManagedStack()->GetTopQuickFrame();
65 CHECK(!native_method->IsFastNative()) << native_method->PrettyMethod();
66 CHECK(!native_method->IsCriticalNative()) << native_method->PrettyMethod();
67 }
68
69 // Transition out of runnable.
70 self->TransitionFromRunnableToSuspended(ThreadState::kNative);
71 }
72
PopLocalReferences(uint32_t saved_local_ref_cookie,Thread * self)73 static void PopLocalReferences(uint32_t saved_local_ref_cookie, Thread* self)
74 REQUIRES_SHARED(Locks::mutator_lock_) {
75 JNIEnvExt* env = self->GetJniEnv();
76 if (UNLIKELY(env->IsCheckJniEnabled())) {
77 env->CheckNoHeldMonitors();
78 }
79 env->SetLocalSegmentState(env->GetLocalRefCookie());
80 env->SetLocalRefCookie(bit_cast<IRTSegmentState>(saved_local_ref_cookie));
81 }
82
83 // TODO: annotalysis disabled as monitor semantics are maintained in Java code.
artJniUnlockObject(mirror::Object * locked,Thread * self)84 extern "C" void artJniUnlockObject(mirror::Object* locked, Thread* self)
85 NO_THREAD_SAFETY_ANALYSIS REQUIRES(!Roles::uninterruptible_) {
86 // Note: No thread suspension is allowed for successful unlocking, otherwise plain
87 // `mirror::Object*` return value saved by the assembly stub would need to be updated.
88 uintptr_t old_poison_object_cookie = kIsDebugBuild ? self->GetPoisonObjectCookie() : 0u;
89 // Save any pending exception over monitor exit call.
90 ObjPtr<mirror::Throwable> saved_exception = nullptr;
91 if (UNLIKELY(self->IsExceptionPending())) {
92 saved_exception = self->GetException();
93 self->ClearException();
94 }
95 // Decode locked object and unlock, before popping local references.
96 locked->MonitorExit(self);
97 if (UNLIKELY(self->IsExceptionPending())) {
98 LOG(FATAL) << "Exception during implicit MonitorExit for synchronized native method:\n"
99 << self->GetException()->Dump()
100 << (saved_exception != nullptr
101 ? "\nAn exception was already pending:\n" + saved_exception->Dump()
102 : "");
103 UNREACHABLE();
104 }
105 // Restore pending exception.
106 if (saved_exception != nullptr) {
107 self->SetException(saved_exception);
108 }
109 if (kIsDebugBuild) {
110 DCHECK_EQ(old_poison_object_cookie, self->GetPoisonObjectCookie());
111 }
112 }
113
114 // TODO: These should probably be templatized or macro-ized.
115 // Otherwise there's just too much repetitive boilerplate.
116
artJniMethodEnd(Thread * self)117 extern "C" void artJniMethodEnd(Thread* self) {
118 self->TransitionFromSuspendedToRunnable();
119
120 if (kIsDebugBuild) {
121 ArtMethod* native_method = *self->GetManagedStack()->GetTopQuickFrame();
122 CHECK(!native_method->IsFastNative()) << native_method->PrettyMethod();
123 CHECK(!native_method->IsCriticalNative()) << native_method->PrettyMethod();
124 }
125 }
126
JniDecodeReferenceResult(jobject result,Thread * self)127 extern mirror::Object* JniDecodeReferenceResult(jobject result, Thread* self)
128 REQUIRES_SHARED(Locks::mutator_lock_) {
129 DCHECK(!self->IsExceptionPending());
130 ObjPtr<mirror::Object> o = self->DecodeJObject(result);
131 // Process result.
132 if (UNLIKELY(self->GetJniEnv()->IsCheckJniEnabled())) {
133 // CheckReferenceResult can resolve types.
134 StackHandleScope<1> hs(self);
135 HandleWrapperObjPtr<mirror::Object> h_obj(hs.NewHandleWrapper(&o));
136 CheckReferenceResult(h_obj, self);
137 }
138 VerifyObject(o);
139 return o.Ptr();
140 }
141
GenericJniMethodEnd(Thread * self,uint32_t saved_local_ref_cookie,jvalue result,uint64_t result_f,ArtMethod * called)142 extern uint64_t GenericJniMethodEnd(Thread* self,
143 uint32_t saved_local_ref_cookie,
144 jvalue result,
145 uint64_t result_f,
146 ArtMethod* called)
147 // NO_THREAD_SAFETY_ANALYSIS because we can enter this function with the mutator lock
148 // unlocked for normal JNI, or locked for @FastNative and @CriticalNative.
149 NO_THREAD_SAFETY_ANALYSIS {
150 bool critical_native = called->IsCriticalNative();
151 bool fast_native = called->IsFastNative();
152 bool normal_native = !critical_native && !fast_native;
153
154 // @CriticalNative does not do a state transition. @FastNative usually does not do a state
155 // transition either but it performs a suspend check that may do state transitions.
156 if (LIKELY(normal_native)) {
157 if (UNLIKELY(self->ReadFlag(ThreadFlag::kMonitorJniEntryExit))) {
158 artJniMonitoredMethodEnd(self);
159 } else {
160 artJniMethodEnd(self);
161 }
162 } else if (fast_native) {
163 // When we are in @FastNative, we are already Runnable.
164 DCHECK(Locks::mutator_lock_->IsSharedHeld(self));
165 // Only do a suspend check on the way out of JNI just like compiled stubs.
166 self->CheckSuspend();
167 }
168 // We need the mutator lock (i.e., calling `artJniMethodEnd()`) before accessing
169 // the shorty or the locked object.
170 if (called->IsSynchronized()) {
171 DCHECK(normal_native) << "@FastNative/@CriticalNative and synchronize is not supported";
172 ObjPtr<mirror::Object> lock = GetGenericJniSynchronizationObject(self, called);
173 DCHECK(lock != nullptr);
174 artJniUnlockObject(lock.Ptr(), self);
175 }
176 char return_shorty_char = called->GetShorty()[0];
177 if (return_shorty_char == 'L') {
178 uint64_t ret = reinterpret_cast<uint64_t>(
179 UNLIKELY(self->IsExceptionPending()) ? nullptr : JniDecodeReferenceResult(result.l, self));
180 PopLocalReferences(saved_local_ref_cookie, self);
181 return ret;
182 } else {
183 if (LIKELY(!critical_native)) {
184 PopLocalReferences(saved_local_ref_cookie, self);
185 }
186 switch (return_shorty_char) {
187 case 'F': {
188 if (kRuntimeISA == InstructionSet::kX86) {
189 // Convert back the result to float.
190 double d = bit_cast<double, uint64_t>(result_f);
191 return bit_cast<uint32_t, float>(static_cast<float>(d));
192 } else {
193 return result_f;
194 }
195 }
196 case 'D':
197 return result_f;
198 case 'Z':
199 return result.z;
200 case 'B':
201 return result.b;
202 case 'C':
203 return result.c;
204 case 'S':
205 return result.s;
206 case 'I':
207 return result.i;
208 case 'J':
209 return result.j;
210 case 'V':
211 return 0;
212 default:
213 LOG(FATAL) << "Unexpected return shorty character " << return_shorty_char;
214 UNREACHABLE();
215 }
216 }
217 }
218
artJniMonitoredMethodStart(Thread * self)219 extern "C" void artJniMonitoredMethodStart(Thread* self) {
220 artJniMethodStart(self);
221 MONITOR_JNI(PaletteNotifyBeginJniInvocation);
222 }
223
artJniMonitoredMethodEnd(Thread * self)224 extern "C" void artJniMonitoredMethodEnd(Thread* self) {
225 MONITOR_JNI(PaletteNotifyEndJniInvocation);
226 artJniMethodEnd(self);
227 }
228
229 } // namespace art
230