blob: db6cbf06e229a25d3d9ec34b760fbb5fad508637 [file] [log] [blame]
Shih-wei Liao2d831012011-09-28 22:06:53 -07001/*
2 * Copyright 2011 Google Inc. All Rights Reserved.
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 "runtime_support.h"
18
Elliott Hughes6c8867d2011-10-03 16:34:05 -070019#include "dex_verifier.h"
20
Shih-wei Liao2d831012011-09-28 22:06:53 -070021namespace art {
22
Ian Rogers4f0d07c2011-10-06 23:38:47 -070023// Place a special frame at the TOS that will save the callee saves for the given type
24static void FinishCalleeSaveFrameSetup(Thread* self, Method** sp, Runtime::CalleeSaveType type) {
Ian Rogersce9eca62011-10-07 17:11:03 -070025 // Be aware the store below may well stomp on an incoming argument
Ian Rogers4f0d07c2011-10-06 23:38:47 -070026 *sp = Runtime::Current()->GetCalleeSaveMethod(type);
27 self->SetTopOfStack(sp, 0);
28}
29
Shih-wei Liao2d831012011-09-28 22:06:53 -070030// Temporary debugging hook for compiler.
31extern void DebugMe(Method* method, uint32_t info) {
32 LOG(INFO) << "DebugMe";
33 if (method != NULL) {
34 LOG(INFO) << PrettyMethod(method);
35 }
36 LOG(INFO) << "Info: " << info;
37}
38
39// Return value helper for jobject return types
40extern Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
41 return thread->DecodeJObject(obj);
42}
43
44extern void* FindNativeMethod(Thread* thread) {
45 DCHECK(Thread::Current() == thread);
46
47 Method* method = const_cast<Method*>(thread->GetCurrentMethod());
48 DCHECK(method != NULL);
49
50 // Lookup symbol address for method, on failure we'll return NULL with an
51 // exception set, otherwise we return the address of the method we found.
52 void* native_code = thread->GetJniEnv()->vm->FindCodeForNativeMethod(method);
53 if (native_code == NULL) {
54 DCHECK(thread->IsExceptionPending());
55 return NULL;
56 } else {
57 // Register so that future calls don't come here
58 method->RegisterNative(native_code);
59 return native_code;
60 }
61}
62
63// Called by generated call to throw an exception
64extern "C" void artDeliverExceptionFromCode(Throwable* exception, Thread* thread, Method** sp) {
65 /*
66 * exception may be NULL, in which case this routine should
67 * throw NPE. NOTE: this is a convenience for generated code,
68 * which previously did the null check inline and constructed
69 * and threw a NPE if NULL. This routine responsible for setting
70 * exception_ in thread and delivering the exception.
71 */
Ian Rogers4f0d07c2011-10-06 23:38:47 -070072 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -070073 if (exception == NULL) {
74 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
75 } else {
76 thread->SetException(exception);
77 }
78 thread->DeliverException();
79}
80
81// Deliver an exception that's pending on thread helping set up a callee save frame on the way
82extern "C" void artDeliverPendingExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070083 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -070084 thread->DeliverException();
85}
86
87// Called by generated call to throw a NPE exception
88extern "C" void artThrowNullPointerExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070089 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070090 thread->ThrowNewException("Ljava/lang/NullPointerException;", NULL);
Shih-wei Liao2d831012011-09-28 22:06:53 -070091 thread->DeliverException();
92}
93
94// Called by generated call to throw an arithmetic divide by zero exception
95extern "C" void artThrowDivZeroFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070096 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -070097 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
98 thread->DeliverException();
99}
100
101// Called by generated call to throw an arithmetic divide by zero exception
102extern "C" void artThrowArrayBoundsFromCode(int index, int limit, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700103 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
104 thread->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
105 "length=%d; index=%d", limit, index);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700106 thread->DeliverException();
107}
108
109// Called by the AbstractMethodError stub (not runtime support)
110extern void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700111 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
112 thread->ThrowNewExceptionF("Ljava/lang/AbstractMethodError;",
113 "abstract method \"%s\"", PrettyMethod(method).c_str());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700114 thread->DeliverException();
115}
116
117extern "C" void artThrowStackOverflowFromCode(Method* method, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700118 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700119 thread->SetStackEndForStackOverflow(); // Allow space on the stack for constructor to execute
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700120 thread->ThrowNewExceptionF("Ljava/lang/StackOverflowError;",
121 "stack size %zdkb; default stack size: %zdkb",
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700122 thread->GetStackSize() / KB, Runtime::Current()->GetDefaultStackSize() / KB);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700123 thread->ResetDefaultStackEnd(); // Return to default stack size
124 thread->DeliverException();
125}
126
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700127static std::string ClassNameFromIndex(Method* method, uint32_t ref,
128 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700129 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
130 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
131
132 uint16_t type_idx = 0;
133 if (ref_type == DexVerifier::VERIFY_ERROR_REF_FIELD) {
134 const DexFile::FieldId& id = dex_file.GetFieldId(ref);
135 type_idx = id.class_idx_;
136 } else if (ref_type == DexVerifier::VERIFY_ERROR_REF_METHOD) {
137 const DexFile::MethodId& id = dex_file.GetMethodId(ref);
138 type_idx = id.class_idx_;
139 } else if (ref_type == DexVerifier::VERIFY_ERROR_REF_CLASS) {
140 type_idx = ref;
141 } else {
142 CHECK(false) << static_cast<int>(ref_type);
143 }
144
145 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(type_idx)));
146 if (!access) {
147 return class_name;
148 }
149
150 std::string result;
151 result += "tried to access class ";
152 result += class_name;
153 result += " from class ";
154 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
155 return result;
156}
157
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700158static std::string FieldNameFromIndex(const Method* method, uint32_t ref,
159 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700160 CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(DexVerifier::VERIFY_ERROR_REF_FIELD));
161
162 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
163 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
164
165 const DexFile::FieldId& id = dex_file.GetFieldId(ref);
166 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(id.class_idx_)));
167 const char* field_name = dex_file.dexStringById(id.name_idx_);
168 if (!access) {
169 return class_name + "." + field_name;
170 }
171
172 std::string result;
173 result += "tried to access field ";
174 result += class_name + "." + field_name;
175 result += " from class ";
176 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
177 return result;
178}
179
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700180static std::string MethodNameFromIndex(const Method* method, uint32_t ref,
181 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700182 CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(DexVerifier::VERIFY_ERROR_REF_METHOD));
183
184 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
185 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
186
187 const DexFile::MethodId& id = dex_file.GetMethodId(ref);
188 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(id.class_idx_)));
189 const char* method_name = dex_file.dexStringById(id.name_idx_);
190 if (!access) {
191 return class_name + "." + method_name;
192 }
193
194 std::string result;
195 result += "tried to access method ";
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700196 result += class_name + "." + method_name + ":" +
197 dex_file.CreateMethodDescriptor(id.proto_idx_, NULL);
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700198 result += " from class ";
199 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
200 return result;
201}
202
203extern "C" void artThrowVerificationErrorFromCode(int32_t kind, int32_t ref, Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700204 FinishCalleeSaveFrameSetup(self, sp, Runtime::kSaveAll);
205 Frame frame = self->GetTopOfStack(); // We need the calling method as context to interpret 'ref'
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700206 frame.Next();
207 Method* method = frame.GetMethod();
208
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700209 DexVerifier::VerifyErrorRefType ref_type =
210 static_cast<DexVerifier::VerifyErrorRefType>(kind >> kVerifyErrorRefTypeShift);
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700211
212 const char* exception_class = "Ljava/lang/VerifyError;";
213 std::string msg;
214
215 switch (static_cast<DexVerifier::VerifyError>(kind & ~(0xff << kVerifyErrorRefTypeShift))) {
216 case DexVerifier::VERIFY_ERROR_NO_CLASS:
217 exception_class = "Ljava/lang/NoClassDefFoundError;";
218 msg = ClassNameFromIndex(method, ref, ref_type, false);
219 break;
220 case DexVerifier::VERIFY_ERROR_NO_FIELD:
221 exception_class = "Ljava/lang/NoSuchFieldError;";
222 msg = FieldNameFromIndex(method, ref, ref_type, false);
223 break;
224 case DexVerifier::VERIFY_ERROR_NO_METHOD:
225 exception_class = "Ljava/lang/NoSuchMethodError;";
226 msg = MethodNameFromIndex(method, ref, ref_type, false);
227 break;
228 case DexVerifier::VERIFY_ERROR_ACCESS_CLASS:
229 exception_class = "Ljava/lang/IllegalAccessError;";
230 msg = ClassNameFromIndex(method, ref, ref_type, true);
231 break;
232 case DexVerifier::VERIFY_ERROR_ACCESS_FIELD:
233 exception_class = "Ljava/lang/IllegalAccessError;";
234 msg = FieldNameFromIndex(method, ref, ref_type, true);
235 break;
236 case DexVerifier::VERIFY_ERROR_ACCESS_METHOD:
237 exception_class = "Ljava/lang/IllegalAccessError;";
238 msg = MethodNameFromIndex(method, ref, ref_type, true);
239 break;
240 case DexVerifier::VERIFY_ERROR_CLASS_CHANGE:
241 exception_class = "Ljava/lang/IncompatibleClassChangeError;";
242 msg = ClassNameFromIndex(method, ref, ref_type, false);
243 break;
244 case DexVerifier::VERIFY_ERROR_INSTANTIATION:
245 exception_class = "Ljava/lang/InstantiationError;";
246 msg = ClassNameFromIndex(method, ref, ref_type, false);
247 break;
248 case DexVerifier::VERIFY_ERROR_GENERIC:
249 // Generic VerifyError; use default exception, no message.
250 break;
251 case DexVerifier::VERIFY_ERROR_NONE:
252 CHECK(false);
253 break;
254 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700255 self->ThrowNewException(exception_class, msg.c_str());
256 self->DeliverException();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700257}
258
259extern "C" void artThrowInternalErrorFromCode(int32_t errnum, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700260 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700261 LOG(WARNING) << "TODO: internal error detail message. errnum=" << errnum;
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700262 thread->ThrowNewExceptionF("Ljava/lang/InternalError;", "errnum=%d", errnum);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700263 thread->DeliverException();
264}
265
266extern "C" void artThrowRuntimeExceptionFromCode(int32_t errnum, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700267 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700268 LOG(WARNING) << "TODO: runtime exception detail message. errnum=" << errnum;
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700269 thread->ThrowNewExceptionF("Ljava/lang/RuntimeException;", "errnum=%d", errnum);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700270 thread->DeliverException();
271}
272
Elliott Hughese1410a22011-10-04 12:10:24 -0700273extern "C" void artThrowNoSuchMethodFromCode(int32_t method_idx, Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700274 FinishCalleeSaveFrameSetup(self, sp, Runtime::kSaveAll);
275 Frame frame = self->GetTopOfStack(); // We need the calling method as context for the method_idx
Elliott Hughese1410a22011-10-04 12:10:24 -0700276 frame.Next();
277 Method* method = frame.GetMethod();
Elliott Hughese1410a22011-10-04 12:10:24 -0700278 self->ThrowNewException("Ljava/lang/NoSuchMethodError;",
279 MethodNameFromIndex(method, method_idx, DexVerifier::VERIFY_ERROR_REF_METHOD, false).c_str());
280 self->DeliverException();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700281}
282
283extern "C" void artThrowNegArraySizeFromCode(int32_t size, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700284 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700285 LOG(WARNING) << "UNTESTED artThrowNegArraySizeFromCode";
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700286 thread->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d", size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700287 thread->DeliverException();
288}
289
Ian Rogersad25ac52011-10-04 19:13:33 -0700290void* UnresolvedDirectMethodTrampolineFromCode(int32_t method_idx, void* sp, Thread* thread,
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700291 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700292 // TODO: this code is specific to ARM
293 // On entry the stack pointed by sp is:
294 // | argN | |
295 // | ... | |
296 // | arg4 | |
297 // | arg3 spill | | Caller's frame
298 // | arg2 spill | |
299 // | arg1 spill | |
300 // | Method* | ---
301 // | LR |
302 // | R3 | arg3
303 // | R2 | arg2
304 // | R1 | arg1
305 // | R0 | <- sp
306 uintptr_t* regs = reinterpret_cast<uintptr_t*>(sp);
307 Method** caller_sp = reinterpret_cast<Method**>(&regs[5]);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700308 uintptr_t caller_pc = regs[4];
Ian Rogersad25ac52011-10-04 19:13:33 -0700309 // Record the last top of the managed stack
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700310 thread->SetTopOfStack(caller_sp, caller_pc);
Ian Rogersad25ac52011-10-04 19:13:33 -0700311 // Start new JNI local reference state
312 JNIEnvExt* env = thread->GetJniEnv();
313 uint32_t saved_local_ref_cookie = env->local_ref_cookie;
314 env->local_ref_cookie = env->locals.GetSegmentState();
315 // Discover shorty (avoid GCs)
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700316 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Ian Rogersad25ac52011-10-04 19:13:33 -0700317 const char* shorty = linker->MethodShorty(method_idx, *caller_sp);
318 size_t shorty_len = strlen(shorty);
319 size_t args_in_regs = shorty_len < 3 ? shorty_len : 3;
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700320 if (type == Runtime::kUnknownMethod) {
321 uint32_t dex_pc = (*caller_sp)->ToDexPC(caller_pc - 2);
322 UNIMPLEMENTED(WARNING) << "Missed argument handlerization in direct method trampoline. "
323 "Need to discover method invoke type at " << PrettyMethod(*caller_sp)
324 << " PC: " << (void*)dex_pc;
325 } else {
326 bool is_static = type == Runtime::kStaticMethod;
327 // Handlerize references in registers
328 int cur_arg = 1; // skip method_idx in R0, first arg is in R1
329 if (!is_static) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700330 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700331 cur_arg++;
Ian Rogersad25ac52011-10-04 19:13:33 -0700332 AddLocalReference<jobject>(env, obj);
333 }
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700334 for(size_t i = 0; i < args_in_regs; i++) {
335 char c = shorty[i + 1]; // offset to skip return value
336 if (c == 'L') {
337 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
338 AddLocalReference<jobject>(env, obj);
339 }
340 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
Ian Rogersad25ac52011-10-04 19:13:33 -0700341 }
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700342 // Handlerize references in out going arguments
343 for(size_t i = 3; i < shorty_len; i++) {
344 char c = shorty[i + 1]; // offset to skip return value
345 if (c == 'L') {
346 Object* obj = reinterpret_cast<Object*>(regs[i + 3]); // skip R0, LR and Method* of caller
347 AddLocalReference<jobject>(env, obj);
348 }
349 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
350 }
Ian Rogersad25ac52011-10-04 19:13:33 -0700351 }
352 // Resolve method filling in dex cache
353 Method* called = linker->ResolveMethod(method_idx, *caller_sp, true);
354 if (!thread->IsExceptionPending()) {
355 // We got this far, ensure that the declaring class is initialized
356 linker->EnsureInitialized(called->GetDeclaringClass(), true);
357 }
358 // Restore JNI env state
359 env->locals.SetSegmentState(env->local_ref_cookie);
360 env->local_ref_cookie = saved_local_ref_cookie;
361
362 void* code;
363 if (thread->IsExceptionPending()) {
364 // Something went wrong, go into deliver exception with the pending exception in r0
365 code = reinterpret_cast<void*>(art_deliver_exception_from_code);
366 regs[0] = reinterpret_cast<uintptr_t>(thread->GetException());
367 thread->ClearException();
368 } else {
369 // Expect class to at least be initializing
370 CHECK(called->GetDeclaringClass()->IsInitializing());
371 // Set up entry into main method
372 regs[0] = reinterpret_cast<uintptr_t>(called);
373 code = const_cast<void*>(called->GetCode());
374 }
375 return code;
376}
377
Shih-wei Liao2d831012011-09-28 22:06:53 -0700378// TODO: placeholder. Helper function to type
379Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
380 /*
381 * Should initialize & fix up method->dex_cache_resolved_types_[].
382 * Returns initialized type. Does not return normally if an exception
383 * is thrown, but instead initiates the catch. Should be similar to
384 * ClassLinker::InitializeStaticStorageFromCode.
385 */
386 UNIMPLEMENTED(FATAL);
387 return NULL;
388}
389
390// TODO: placeholder. Helper function to resolve virtual method
391void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
392 /*
393 * Slow-path handler on invoke virtual method path in which
394 * base method is unresolved at compile-time. Doesn't need to
395 * return anything - just either ensure that
396 * method->dex_cache_resolved_methods_(method_idx) != NULL or
397 * throw and unwind. The caller will restart call sequence
398 * from the beginning.
399 */
400}
401
Ian Rogersce9eca62011-10-07 17:11:03 -0700402Field* FindFieldFromCode(uint32_t field_idx, const Method* referrer, bool is_static) {
403 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
404 Field* f = class_linker->ResolveField(field_idx, referrer, is_static);
405 if (f != NULL) {
406 Class* c = f->GetDeclaringClass();
407 // If the class is already initializing, we must be inside <clinit>, or
408 // we'd still be waiting for the lock.
409 if (c->GetStatus() == Class::kStatusInitializing || class_linker->EnsureInitialized(c, true)) {
410 return f;
411 }
412 }
413 DCHECK(Thread::Current()->IsExceptionPending()); // Throw exception and unwind
414 return NULL;
415}
416
417extern "C" Field* artFindInstanceFieldFromCode(uint32_t field_idx, const Method* referrer,
418 Thread* self, Method** sp) {
419 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
420 return FindFieldFromCode(field_idx, referrer, false);
421}
422
423extern "C" uint32_t artGet32StaticFromCode(uint32_t field_idx, const Method* referrer,
424 Thread* self, Method** sp) {
425 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
426 Field* field = FindFieldFromCode(field_idx, referrer, true);
427 if (field != NULL) {
428 Class* type = field->GetType();
429 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int64_t)) {
430 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
431 "Attempted read of 32-bit primitive on field '%s'",
432 PrettyField(field, true).c_str());
433 } else {
434 return field->Get32(NULL);
435 }
436 }
437 return 0; // Will throw exception by checking with Thread::Current
438}
439
440extern "C" uint64_t artGet64StaticFromCode(uint32_t field_idx, const Method* referrer,
441 Thread* self, Method** sp) {
442 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
443 Field* field = FindFieldFromCode(field_idx, referrer, true);
444 if (field != NULL) {
445 Class* type = field->GetType();
446 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int64_t)) {
447 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
448 "Attempted read of 64-bit primitive on field '%s'",
449 PrettyField(field, true).c_str());
450 } else {
451 return field->Get64(NULL);
452 }
453 }
454 return 0; // Will throw exception by checking with Thread::Current
455}
456
457extern "C" Object* artGetObjStaticFromCode(uint32_t field_idx, const Method* referrer,
458 Thread* self, Method** sp) {
459 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
460 Field* field = FindFieldFromCode(field_idx, referrer, true);
461 if (field != NULL) {
462 Class* type = field->GetType();
463 if (type->IsPrimitive()) {
464 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
465 "Attempted read of reference on primitive field '%s'",
466 PrettyField(field, true).c_str());
467 } else {
468 return field->GetObj(NULL);
469 }
470 }
471 return NULL; // Will throw exception by checking with Thread::Current
472}
473
474extern "C" int artSet32StaticFromCode(uint32_t field_idx, const Method* referrer,
475 uint32_t new_value, Thread* self, Method** sp) {
476 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
477 Field* field = FindFieldFromCode(field_idx, referrer, true);
478 if (field != NULL) {
479 Class* type = field->GetType();
480 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int32_t)) {
481 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
482 "Attempted write of 32-bit primitive to field '%s'",
483 PrettyField(field, true).c_str());
484 } else {
485 field->Set32(NULL, new_value);
486 return 0; // success
487 }
488 }
489 return -1; // failure
490}
491
492extern "C" int artSet64StaticFromCode(uint32_t field_idx, const Method* referrer,
493 uint64_t new_value, Thread* self, Method** sp) {
494 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
495 Field* field = FindFieldFromCode(field_idx, referrer, true);
496 if (field != NULL) {
497 Class* type = field->GetType();
498 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int64_t)) {
499 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
500 "Attempted write of 64-bit primitive to field '%s'",
501 PrettyField(field, true).c_str());
502 } else {
503 field->Set64(NULL, new_value);
504 return 0; // success
505 }
506 }
507 return -1; // failure
508}
509
510extern "C" int artSetObjStaticFromCode(uint32_t field_idx, const Method* referrer,
511 Object* new_value, Thread* self, Method** sp) {
512 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
513 Field* field = FindFieldFromCode(field_idx, referrer, true);
514 if (field != NULL) {
515 Class* type = field->GetType();
516 if (type->IsPrimitive()) {
517 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
518 "Attempted write of reference to primitive field '%s'",
519 PrettyField(field, true).c_str());
520 } else {
521 field->SetObj(NULL, new_value);
522 return 0; // success
523 }
524 }
525 return -1; // failure
526}
527
Shih-wei Liao2d831012011-09-28 22:06:53 -0700528// Given the context of a calling Method, use its DexCache to resolve a type to a Class. If it
529// cannot be resolved, throw an error. If it can, use it to create an instance.
buzbee33a129c2011-10-06 16:53:20 -0700530extern "C" Object* artAllocObjectFromCode(uint32_t type_idx, Method* method, Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700531 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700532 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700533 Runtime* runtime = Runtime::Current();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700534 if (klass == NULL) {
buzbee33a129c2011-10-06 16:53:20 -0700535 klass = runtime->GetClassLinker()->ResolveType(type_idx, method);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700536 if (klass == NULL) {
buzbee33a129c2011-10-06 16:53:20 -0700537 DCHECK(self->IsExceptionPending());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700538 return NULL; // Failure
539 }
540 }
buzbee33a129c2011-10-06 16:53:20 -0700541 if (!runtime->GetClassLinker()->EnsureInitialized(klass, true)) {
542 DCHECK(self->IsExceptionPending());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700543 return NULL; // Failure
544 }
545 return klass->AllocObject();
546}
547
Ian Rogersce9eca62011-10-07 17:11:03 -0700548Array* CheckAndAllocArrayFromCode(uint32_t type_idx, Method* method, int32_t component_count,
549 Thread* self) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700550 if (component_count < 0) {
Ian Rogersce9eca62011-10-07 17:11:03 -0700551 self->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d", component_count);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700552 return NULL; // Failure
553 }
554 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
555 if (klass == NULL) { // Not in dex cache so try to resolve
556 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
557 if (klass == NULL) { // Error
558 DCHECK(Thread::Current()->IsExceptionPending());
559 return NULL; // Failure
560 }
561 }
562 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
563 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700564 Thread::Current()->ThrowNewExceptionF("Ljava/lang/RuntimeException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700565 "Bad filled array request for type %s",
566 PrettyDescriptor(klass->GetDescriptor()).c_str());
567 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700568 Thread::Current()->ThrowNewExceptionF("Ljava/lang/InternalError;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700569 "Found type %s; filled-new-array not implemented for anything but \'int\'",
570 PrettyDescriptor(klass->GetDescriptor()).c_str());
571 }
572 return NULL; // Failure
573 } else {
574 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
575 return Array::Alloc(klass, component_count);
576 }
577}
578
Ian Rogersce9eca62011-10-07 17:11:03 -0700579// Helper function to alloc array for OP_FILLED_NEW_ARRAY
580extern "C" Array* artCheckAndAllocArrayFromCode(uint32_t type_idx, Method* method,
581 int32_t component_count, Thread* self, Method** sp) {
582 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
583 return CheckAndAllocArrayFromCode(type_idx, method, component_count, self);
584}
585
Shih-wei Liao2d831012011-09-28 22:06:53 -0700586// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
587// it cannot be resolved, throw an error. If it can, use it to create an array.
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700588extern "C" Array* artAllocArrayFromCode(uint32_t type_idx, Method* method, int32_t component_count,
589 Thread* self, Method** sp) {
590 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700591 if (component_count < 0) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700592 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700593 component_count);
594 return NULL; // Failure
595 }
596 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
597 if (klass == NULL) { // Not in dex cache so try to resolve
598 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
599 if (klass == NULL) { // Error
600 DCHECK(Thread::Current()->IsExceptionPending());
601 return NULL; // Failure
602 }
603 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
604 }
605 return Array::Alloc(klass, component_count);
606}
607
608// Check whether it is safe to cast one class to the other, throw exception and return -1 on failure
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700609extern "C" int artCheckCastFromCode(const Class* a, const Class* b, Thread* self, Method** sp) {
610 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700611 DCHECK(a->IsClass()) << PrettyClass(a);
612 DCHECK(b->IsClass()) << PrettyClass(b);
613 if (b->IsAssignableFrom(a)) {
614 return 0; // Success
615 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700616 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassCastException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700617 "%s cannot be cast to %s",
618 PrettyDescriptor(a->GetDescriptor()).c_str(),
619 PrettyDescriptor(b->GetDescriptor()).c_str());
620 return -1; // Failure
621 }
622}
623
624// Tests whether 'element' can be assigned into an array of type 'array_class'.
625// Returns 0 on success and -1 if an exception is pending.
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700626extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class,
627 Thread* self, Method** sp) {
628 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700629 DCHECK(array_class != NULL);
630 // element can't be NULL as we catch this is screened in runtime_support
631 Class* element_class = element->GetClass();
632 Class* component_type = array_class->GetComponentType();
633 if (component_type->IsAssignableFrom(element_class)) {
634 return 0; // Success
635 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700636 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700637 "Cannot store an object of type %s in to an array of type %s",
638 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
639 PrettyDescriptor(array_class->GetDescriptor()).c_str());
640 return -1; // Failure
641 }
642}
643
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700644Class* InitializeStaticStorage(uint32_t type_idx, const Method* referrer, Thread* self) {
645 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
646 Class* klass = class_linker->ResolveType(type_idx, referrer);
647 if (klass == NULL) {
648 CHECK(self->IsExceptionPending());
649 return NULL; // Failure - Indicate to caller to deliver exception
650 }
651 // If we are the <clinit> of this class, just return our storage.
652 //
653 // Do not set the DexCache InitializedStaticStorage, since that implies <clinit> has finished
654 // running.
655 if (klass == referrer->GetDeclaringClass() && referrer->IsClassInitializer()) {
656 return klass;
657 }
658 if (!class_linker->EnsureInitialized(klass, true)) {
659 CHECK(self->IsExceptionPending());
660 return NULL; // Failure - Indicate to caller to deliver exception
661 }
662 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
663 return klass;
Shih-wei Liao2d831012011-09-28 22:06:53 -0700664}
665
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700666extern "C" Class* artInitializeStaticStorageFromCode(uint32_t type_idx, const Method* referrer,
667 Thread* self, Method** sp) {
668 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
669 return InitializeStaticStorage(type_idx, referrer, self);
670}
671
672extern "C" int artUnlockObjectFromCode(Object* obj, Thread* self, Method** sp) {
673 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700674 DCHECK(obj != NULL); // Assumed to have been checked before entry
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700675 // MonitorExit may throw exception
676 return obj->MonitorExit(self) ? 0 /* Success */ : -1 /* Failure */;
677}
678
679extern "C" void artLockObjectFromCode(Object* obj, Thread* thread, Method** sp) {
680 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsOnly);
681 DCHECK(obj != NULL); // Assumed to have been checked before entry
682 obj->MonitorEnter(thread); // May block
Shih-wei Liao2d831012011-09-28 22:06:53 -0700683 DCHECK(thread->HoldsLock(obj));
684 // Only possible exception is NPE and is handled before entry
685 DCHECK(!thread->IsExceptionPending());
686}
687
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700688extern "C" void artCheckSuspendFromJni(Thread* thread) {
689 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
690}
691
692extern "C" void artCheckSuspendFromCode(Thread* thread, Method** sp) {
693 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700694 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
695}
696
697/*
698 * Fill the array with predefined constant values, throwing exceptions if the array is null or
699 * not of sufficient length.
700 *
701 * NOTE: When dealing with a raw dex file, the data to be copied uses
702 * little-endian ordering. Require that oat2dex do any required swapping
703 * so this routine can get by with a memcpy().
704 *
705 * Format of the data:
706 * ushort ident = 0x0300 magic value
707 * ushort width width of each element in the table
708 * uint size number of elements in the table
709 * ubyte data[size*width] table of data values (may contain a single-byte
710 * padding at the end)
711 */
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700712extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table,
713 Thread* self, Method** sp) {
714 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700715 DCHECK_EQ(table[0], 0x0300);
716 if (array == NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700717 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
718 "null array in fill array");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700719 return -1; // Error
720 }
721 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
722 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
723 if (static_cast<int32_t>(size) > array->GetLength()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700724 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
725 "failed array fill. length=%d; index=%d", array->GetLength(), size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700726 return -1; // Error
727 }
728 uint16_t width = table[1];
729 uint32_t size_in_bytes = size * width;
730 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
731 return 0; // Success
732}
733
734// See comments in runtime_support_asm.S
735extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
736 Object* this_object ,
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700737 Thread* thread, Method** sp) {
738 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsAndArgs);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700739 if (this_object == NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700740 thread->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
741 "null receiver during interface dispatch");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700742 return 0;
743 }
744 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700745 Frame frame = thread->GetTopOfStack(); // Compute calling method
746 frame.Next();
747 Method* caller_method = frame.GetMethod();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700748 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
749 if (interface_method == NULL) {
750 // Could not resolve interface method. Throw error and unwind
751 CHECK(thread->IsExceptionPending());
752 return 0;
753 }
754 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
755 if (method == NULL) {
756 CHECK(thread->IsExceptionPending());
757 return 0;
758 }
759 const void* code = method->GetCode();
760
761 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
762 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
763 uint64_t result = ((code_uint << 32) | method_uint);
764 return result;
765}
766
767/*
768 * Float/double conversion requires clamping to min and max of integer form. If
769 * target doesn't support this normally, use these.
770 */
771int64_t D2L(double d) {
772 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
773 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
774 if (d >= kMaxLong)
775 return (int64_t)0x7fffffffffffffffULL;
776 else if (d <= kMinLong)
777 return (int64_t)0x8000000000000000ULL;
778 else if (d != d) // NaN case
779 return 0;
780 else
781 return (int64_t)d;
782}
783
784int64_t F2L(float f) {
785 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
786 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
787 if (f >= kMaxLong)
788 return (int64_t)0x7fffffffffffffffULL;
789 else if (f <= kMinLong)
790 return (int64_t)0x8000000000000000ULL;
791 else if (f != f) // NaN case
792 return 0;
793 else
794 return (int64_t)f;
795}
796
797} // namespace art