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