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