blob: 2bcd7d9eadca16065476fe27421b2c8bf69f9394 [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
23// Temporary debugging hook for compiler.
24extern void DebugMe(Method* method, uint32_t info) {
25 LOG(INFO) << "DebugMe";
26 if (method != NULL) {
27 LOG(INFO) << PrettyMethod(method);
28 }
29 LOG(INFO) << "Info: " << info;
30}
31
32// Return value helper for jobject return types
33extern Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
34 return thread->DecodeJObject(obj);
35}
36
37extern void* FindNativeMethod(Thread* thread) {
38 DCHECK(Thread::Current() == thread);
39
40 Method* method = const_cast<Method*>(thread->GetCurrentMethod());
41 DCHECK(method != NULL);
42
43 // Lookup symbol address for method, on failure we'll return NULL with an
44 // exception set, otherwise we return the address of the method we found.
45 void* native_code = thread->GetJniEnv()->vm->FindCodeForNativeMethod(method);
46 if (native_code == NULL) {
47 DCHECK(thread->IsExceptionPending());
48 return NULL;
49 } else {
50 // Register so that future calls don't come here
51 method->RegisterNative(native_code);
52 return native_code;
53 }
54}
55
56// Called by generated call to throw an exception
57extern "C" void artDeliverExceptionFromCode(Throwable* exception, Thread* thread, Method** sp) {
58 /*
59 * exception may be NULL, in which case this routine should
60 * throw NPE. NOTE: this is a convenience for generated code,
61 * which previously did the null check inline and constructed
62 * and threw a NPE if NULL. This routine responsible for setting
63 * exception_ in thread and delivering the exception.
64 */
65 // Place a special frame at the TOS that will save all callee saves
66 *sp = Runtime::Current()->GetCalleeSaveMethod();
67 thread->SetTopOfStack(sp, 0);
68 if (exception == NULL) {
69 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
70 } else {
71 thread->SetException(exception);
72 }
73 thread->DeliverException();
74}
75
76// Deliver an exception that's pending on thread helping set up a callee save frame on the way
77extern "C" void artDeliverPendingExceptionFromCode(Thread* thread, Method** sp) {
78 *sp = Runtime::Current()->GetCalleeSaveMethod();
79 thread->SetTopOfStack(sp, 0);
80 thread->DeliverException();
81}
82
83// Called by generated call to throw a NPE exception
84extern "C" void artThrowNullPointerExceptionFromCode(Thread* thread, Method** sp) {
85 // Place a special frame at the TOS that will save all callee saves
86 *sp = Runtime::Current()->GetCalleeSaveMethod();
87 thread->SetTopOfStack(sp, 0);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070088 thread->ThrowNewException("Ljava/lang/NullPointerException;", NULL);
Shih-wei Liao2d831012011-09-28 22:06:53 -070089 thread->DeliverException();
90}
91
92// Called by generated call to throw an arithmetic divide by zero exception
93extern "C" void artThrowDivZeroFromCode(Thread* thread, Method** sp) {
94 // Place a special frame at the TOS that will save all callee saves
95 *sp = Runtime::Current()->GetCalleeSaveMethod();
96 thread->SetTopOfStack(sp, 0);
97 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) {
103 // Place a special frame at the TOS that will save all callee saves
104 *sp = Runtime::Current()->GetCalleeSaveMethod();
105 thread->SetTopOfStack(sp, 0);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700106 thread->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;", "length=%d; index=%d",
107 limit, index);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700108 thread->DeliverException();
109}
110
111// Called by the AbstractMethodError stub (not runtime support)
112extern void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread, Method** sp) {
113 *sp = Runtime::Current()->GetCalleeSaveMethod();
114 thread->SetTopOfStack(sp, 0);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700115 thread->ThrowNewExceptionF("Ljava/lang/AbstractMethodError;", "abstract method \"%s\"",
116 PrettyMethod(method).c_str());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700117 thread->DeliverException();
118}
119
120extern "C" void artThrowStackOverflowFromCode(Method* method, Thread* thread, Method** sp) {
121 // Place a special frame at the TOS that will save all callee saves
122 Runtime* runtime = Runtime::Current();
123 *sp = runtime->GetCalleeSaveMethod();
124 thread->SetTopOfStack(sp, 0);
125 thread->SetStackEndForStackOverflow(); // Allow space on the stack for constructor to execute
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700126 thread->ThrowNewExceptionF("Ljava/lang/StackOverflowError;",
127 "stack size %zdkb; default stack size: %zdkb",
128 thread->GetStackSize() / KB, runtime->GetDefaultStackSize() / KB);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700129 thread->ResetDefaultStackEnd(); // Return to default stack size
130 thread->DeliverException();
131}
132
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700133std::string ClassNameFromIndex(Method* method, uint32_t ref, DexVerifier::VerifyErrorRefType ref_type, bool access) {
134 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
135 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
136
137 uint16_t type_idx = 0;
138 if (ref_type == DexVerifier::VERIFY_ERROR_REF_FIELD) {
139 const DexFile::FieldId& id = dex_file.GetFieldId(ref);
140 type_idx = id.class_idx_;
141 } else if (ref_type == DexVerifier::VERIFY_ERROR_REF_METHOD) {
142 const DexFile::MethodId& id = dex_file.GetMethodId(ref);
143 type_idx = id.class_idx_;
144 } else if (ref_type == DexVerifier::VERIFY_ERROR_REF_CLASS) {
145 type_idx = ref;
146 } else {
147 CHECK(false) << static_cast<int>(ref_type);
148 }
149
150 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(type_idx)));
151 if (!access) {
152 return class_name;
153 }
154
155 std::string result;
156 result += "tried to access class ";
157 result += class_name;
158 result += " from class ";
159 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
160 return result;
161}
162
163std::string FieldNameFromIndex(const Method* method, uint32_t ref, DexVerifier::VerifyErrorRefType ref_type, bool access) {
164 CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(DexVerifier::VERIFY_ERROR_REF_FIELD));
165
166 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
167 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
168
169 const DexFile::FieldId& id = dex_file.GetFieldId(ref);
170 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(id.class_idx_)));
171 const char* field_name = dex_file.dexStringById(id.name_idx_);
172 if (!access) {
173 return class_name + "." + field_name;
174 }
175
176 std::string result;
177 result += "tried to access field ";
178 result += class_name + "." + field_name;
179 result += " from class ";
180 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
181 return result;
182}
183
184std::string MethodNameFromIndex(const Method* method, uint32_t ref, DexVerifier::VerifyErrorRefType ref_type, bool access) {
185 CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(DexVerifier::VERIFY_ERROR_REF_METHOD));
186
187 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
188 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
189
190 const DexFile::MethodId& id = dex_file.GetMethodId(ref);
191 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(id.class_idx_)));
192 const char* method_name = dex_file.dexStringById(id.name_idx_);
193 if (!access) {
194 return class_name + "." + method_name;
195 }
196
197 std::string result;
198 result += "tried to access method ";
199 result += class_name + "." + method_name + ":" + dex_file.CreateMethodDescriptor(id.proto_idx_, NULL);
200 result += " from class ";
201 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
202 return result;
203}
204
205extern "C" void artThrowVerificationErrorFromCode(int32_t kind, int32_t ref, Thread* self, Method** sp) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700206 // Place a special frame at the TOS that will save all callee saves
207 Runtime* runtime = Runtime::Current();
208 *sp = runtime->GetCalleeSaveMethod();
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700209 self->SetTopOfStack(sp, 0);
210
Elliott Hughese1410a22011-10-04 12:10:24 -0700211 // We need the calling method as context to interpret 'ref'.
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700212 Frame frame = self->GetTopOfStack();
213 frame.Next();
214 Method* method = frame.GetMethod();
215
216 DexVerifier::VerifyErrorRefType ref_type = static_cast<DexVerifier::VerifyErrorRefType>(kind >> kVerifyErrorRefTypeShift);
217
218 const char* exception_class = "Ljava/lang/VerifyError;";
219 std::string msg;
220
221 switch (static_cast<DexVerifier::VerifyError>(kind & ~(0xff << kVerifyErrorRefTypeShift))) {
222 case DexVerifier::VERIFY_ERROR_NO_CLASS:
223 exception_class = "Ljava/lang/NoClassDefFoundError;";
224 msg = ClassNameFromIndex(method, ref, ref_type, false);
225 break;
226 case DexVerifier::VERIFY_ERROR_NO_FIELD:
227 exception_class = "Ljava/lang/NoSuchFieldError;";
228 msg = FieldNameFromIndex(method, ref, ref_type, false);
229 break;
230 case DexVerifier::VERIFY_ERROR_NO_METHOD:
231 exception_class = "Ljava/lang/NoSuchMethodError;";
232 msg = MethodNameFromIndex(method, ref, ref_type, false);
233 break;
234 case DexVerifier::VERIFY_ERROR_ACCESS_CLASS:
235 exception_class = "Ljava/lang/IllegalAccessError;";
236 msg = ClassNameFromIndex(method, ref, ref_type, true);
237 break;
238 case DexVerifier::VERIFY_ERROR_ACCESS_FIELD:
239 exception_class = "Ljava/lang/IllegalAccessError;";
240 msg = FieldNameFromIndex(method, ref, ref_type, true);
241 break;
242 case DexVerifier::VERIFY_ERROR_ACCESS_METHOD:
243 exception_class = "Ljava/lang/IllegalAccessError;";
244 msg = MethodNameFromIndex(method, ref, ref_type, true);
245 break;
246 case DexVerifier::VERIFY_ERROR_CLASS_CHANGE:
247 exception_class = "Ljava/lang/IncompatibleClassChangeError;";
248 msg = ClassNameFromIndex(method, ref, ref_type, false);
249 break;
250 case DexVerifier::VERIFY_ERROR_INSTANTIATION:
251 exception_class = "Ljava/lang/InstantiationError;";
252 msg = ClassNameFromIndex(method, ref, ref_type, false);
253 break;
254 case DexVerifier::VERIFY_ERROR_GENERIC:
255 // Generic VerifyError; use default exception, no message.
256 break;
257 case DexVerifier::VERIFY_ERROR_NONE:
258 CHECK(false);
259 break;
260 }
261
262 self->ThrowNewException(exception_class, msg.c_str());
263 self->DeliverException();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700264}
265
266extern "C" void artThrowInternalErrorFromCode(int32_t errnum, Thread* thread, Method** sp) {
267 // Place a special frame at the TOS that will save all callee saves
268 Runtime* runtime = Runtime::Current();
269 *sp = runtime->GetCalleeSaveMethod();
270 thread->SetTopOfStack(sp, 0);
271 LOG(WARNING) << "TODO: internal error detail message. errnum=" << errnum;
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700272 thread->ThrowNewExceptionF("Ljava/lang/InternalError;", "errnum=%d", errnum);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700273 thread->DeliverException();
274}
275
276extern "C" void artThrowRuntimeExceptionFromCode(int32_t errnum, Thread* thread, Method** sp) {
277 // Place a special frame at the TOS that will save all callee saves
278 Runtime* runtime = Runtime::Current();
279 *sp = runtime->GetCalleeSaveMethod();
280 thread->SetTopOfStack(sp, 0);
281 LOG(WARNING) << "TODO: runtime exception detail message. errnum=" << errnum;
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700282 thread->ThrowNewExceptionF("Ljava/lang/RuntimeException;", "errnum=%d", errnum);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700283 thread->DeliverException();
284}
285
Elliott Hughese1410a22011-10-04 12:10:24 -0700286extern "C" void artThrowNoSuchMethodFromCode(int32_t method_idx, Thread* self, Method** sp) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700287 // Place a special frame at the TOS that will save all callee saves
288 Runtime* runtime = Runtime::Current();
289 *sp = runtime->GetCalleeSaveMethod();
Elliott Hughese1410a22011-10-04 12:10:24 -0700290 self->SetTopOfStack(sp, 0);
291
292 // We need the calling method as context for the method_idx.
293 Frame frame = self->GetTopOfStack();
294 frame.Next();
295 Method* method = frame.GetMethod();
296
297 self->ThrowNewException("Ljava/lang/NoSuchMethodError;",
298 MethodNameFromIndex(method, method_idx, DexVerifier::VERIFY_ERROR_REF_METHOD, false).c_str());
299 self->DeliverException();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700300}
301
302extern "C" void artThrowNegArraySizeFromCode(int32_t size, Thread* thread, Method** sp) {
303 LOG(WARNING) << "UNTESTED artThrowNegArraySizeFromCode";
304 // Place a special frame at the TOS that will save all callee saves
305 Runtime* runtime = Runtime::Current();
306 *sp = runtime->GetCalleeSaveMethod();
307 thread->SetTopOfStack(sp, 0);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700308 thread->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d", size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700309 thread->DeliverException();
310}
311
Ian Rogersad25ac52011-10-04 19:13:33 -0700312void* UnresolvedDirectMethodTrampolineFromCode(int32_t method_idx, void* sp, Thread* thread,
313 bool is_static) {
314 // TODO: this code is specific to ARM
315 // On entry the stack pointed by sp is:
316 // | argN | |
317 // | ... | |
318 // | arg4 | |
319 // | arg3 spill | | Caller's frame
320 // | arg2 spill | |
321 // | arg1 spill | |
322 // | Method* | ---
323 // | LR |
324 // | R3 | arg3
325 // | R2 | arg2
326 // | R1 | arg1
327 // | R0 | <- sp
328 uintptr_t* regs = reinterpret_cast<uintptr_t*>(sp);
329 Method** caller_sp = reinterpret_cast<Method**>(&regs[5]);
330 // Record the last top of the managed stack
331 thread->SetTopOfStack(caller_sp, regs[4]);
332 ClassLinker* linker = Runtime::Current()->GetClassLinker();
333 // Start new JNI local reference state
334 JNIEnvExt* env = thread->GetJniEnv();
335 uint32_t saved_local_ref_cookie = env->local_ref_cookie;
336 env->local_ref_cookie = env->locals.GetSegmentState();
337 // Discover shorty (avoid GCs)
338 const char* shorty = linker->MethodShorty(method_idx, *caller_sp);
339 size_t shorty_len = strlen(shorty);
340 size_t args_in_regs = shorty_len < 3 ? shorty_len : 3;
341 // Handlerize references in registers
342 int cur_arg = 1; // skip method_idx in R0, first arg is in R1
343 if (!is_static) {
344 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
345 cur_arg++;
346 AddLocalReference<jobject>(env, obj);
347 }
348 for(size_t i = 0; i < args_in_regs; i++) {
349 char c = shorty[i + 1]; // offset to skip return value
350 if (c == 'L') {
351 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
352 AddLocalReference<jobject>(env, obj);
353 }
354 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
355 }
356 // Handlerize references in out going arguments
357 for(size_t i = 3; i < shorty_len; i++) {
358 char c = shorty[i + 1]; // offset to skip return value
359 if (c == 'L') {
360 Object* obj = reinterpret_cast<Object*>(regs[i + 3]); // skip R0, LR and Method* of caller
361 AddLocalReference<jobject>(env, obj);
362 }
363 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
364 }
365 // Resolve method filling in dex cache
366 Method* called = linker->ResolveMethod(method_idx, *caller_sp, true);
367 if (!thread->IsExceptionPending()) {
368 // We got this far, ensure that the declaring class is initialized
369 linker->EnsureInitialized(called->GetDeclaringClass(), true);
370 }
371 // Restore JNI env state
372 env->locals.SetSegmentState(env->local_ref_cookie);
373 env->local_ref_cookie = saved_local_ref_cookie;
374
375 void* code;
376 if (thread->IsExceptionPending()) {
377 // Something went wrong, go into deliver exception with the pending exception in r0
378 code = reinterpret_cast<void*>(art_deliver_exception_from_code);
379 regs[0] = reinterpret_cast<uintptr_t>(thread->GetException());
380 thread->ClearException();
381 } else {
382 // Expect class to at least be initializing
383 CHECK(called->GetDeclaringClass()->IsInitializing());
384 // Set up entry into main method
385 regs[0] = reinterpret_cast<uintptr_t>(called);
386 code = const_cast<void*>(called->GetCode());
387 }
388 return code;
389}
390
Shih-wei Liao2d831012011-09-28 22:06:53 -0700391// TODO: placeholder. Helper function to type
392Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
393 /*
394 * Should initialize & fix up method->dex_cache_resolved_types_[].
395 * Returns initialized type. Does not return normally if an exception
396 * is thrown, but instead initiates the catch. Should be similar to
397 * ClassLinker::InitializeStaticStorageFromCode.
398 */
399 UNIMPLEMENTED(FATAL);
400 return NULL;
401}
402
403// TODO: placeholder. Helper function to resolve virtual method
404void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
405 /*
406 * Slow-path handler on invoke virtual method path in which
407 * base method is unresolved at compile-time. Doesn't need to
408 * return anything - just either ensure that
409 * method->dex_cache_resolved_methods_(method_idx) != NULL or
410 * throw and unwind. The caller will restart call sequence
411 * from the beginning.
412 */
413}
414
415// Given the context of a calling Method, use its DexCache to resolve a type to a Class. If it
416// cannot be resolved, throw an error. If it can, use it to create an instance.
417extern "C" Object* artAllocObjectFromCode(uint32_t type_idx, Method* method) {
418 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
419 if (klass == NULL) {
420 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
421 if (klass == NULL) {
422 DCHECK(Thread::Current()->IsExceptionPending());
423 return NULL; // Failure
424 }
425 }
426 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(klass, true)) {
427 DCHECK(Thread::Current()->IsExceptionPending());
428 return NULL; // Failure
429 }
430 return klass->AllocObject();
431}
432
433// Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesb408de72011-10-04 14:35:05 -0700434extern "C" Array* artCheckAndAllocArrayFromCode(uint32_t type_idx, Method* method,
Shih-wei Liao2d831012011-09-28 22:06:53 -0700435 int32_t component_count) {
436 if (component_count < 0) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700437 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700438 component_count);
439 return NULL; // Failure
440 }
441 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
442 if (klass == NULL) { // Not in dex cache so try to resolve
443 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
444 if (klass == NULL) { // Error
445 DCHECK(Thread::Current()->IsExceptionPending());
446 return NULL; // Failure
447 }
448 }
449 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
450 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700451 Thread::Current()->ThrowNewExceptionF("Ljava/lang/RuntimeException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700452 "Bad filled array request for type %s",
453 PrettyDescriptor(klass->GetDescriptor()).c_str());
454 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700455 Thread::Current()->ThrowNewExceptionF("Ljava/lang/InternalError;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700456 "Found type %s; filled-new-array not implemented for anything but \'int\'",
457 PrettyDescriptor(klass->GetDescriptor()).c_str());
458 }
459 return NULL; // Failure
460 } else {
461 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
462 return Array::Alloc(klass, component_count);
463 }
464}
465
466// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
467// it cannot be resolved, throw an error. If it can, use it to create an array.
Elliott Hughesb408de72011-10-04 14:35:05 -0700468extern "C" Array* artAllocArrayFromCode(uint32_t type_idx, Method* method, int32_t component_count) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700469 if (component_count < 0) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700470 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700471 component_count);
472 return NULL; // Failure
473 }
474 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
475 if (klass == NULL) { // Not in dex cache so try to resolve
476 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
477 if (klass == NULL) { // Error
478 DCHECK(Thread::Current()->IsExceptionPending());
479 return NULL; // Failure
480 }
481 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
482 }
483 return Array::Alloc(klass, component_count);
484}
485
486// Check whether it is safe to cast one class to the other, throw exception and return -1 on failure
487extern "C" int artCheckCastFromCode(const Class* a, const Class* b) {
488 DCHECK(a->IsClass()) << PrettyClass(a);
489 DCHECK(b->IsClass()) << PrettyClass(b);
490 if (b->IsAssignableFrom(a)) {
491 return 0; // Success
492 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700493 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassCastException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700494 "%s cannot be cast to %s",
495 PrettyDescriptor(a->GetDescriptor()).c_str(),
496 PrettyDescriptor(b->GetDescriptor()).c_str());
497 return -1; // Failure
498 }
499}
500
501// Tests whether 'element' can be assigned into an array of type 'array_class'.
502// Returns 0 on success and -1 if an exception is pending.
503extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class) {
504 DCHECK(array_class != NULL);
505 // element can't be NULL as we catch this is screened in runtime_support
506 Class* element_class = element->GetClass();
507 Class* component_type = array_class->GetComponentType();
508 if (component_type->IsAssignableFrom(element_class)) {
509 return 0; // Success
510 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700511 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700512 "Cannot store an object of type %s in to an array of type %s",
513 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
514 PrettyDescriptor(array_class->GetDescriptor()).c_str());
515 return -1; // Failure
516 }
517}
518
519extern "C" int artUnlockObjectFromCode(Thread* thread, Object* obj) {
520 DCHECK(obj != NULL); // Assumed to have been checked before entry
521 return obj->MonitorExit(thread) ? 0 /* Success */ : -1 /* Failure */;
522}
523
524void LockObjectFromCode(Thread* thread, Object* obj) {
525 DCHECK(obj != NULL); // Assumed to have been checked before entry
526 obj->MonitorEnter(thread);
527 DCHECK(thread->HoldsLock(obj));
528 // Only possible exception is NPE and is handled before entry
529 DCHECK(!thread->IsExceptionPending());
530}
531
532extern "C" void artCheckSuspendFromCode(Thread* thread) {
533 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
534}
535
536/*
537 * Fill the array with predefined constant values, throwing exceptions if the array is null or
538 * not of sufficient length.
539 *
540 * NOTE: When dealing with a raw dex file, the data to be copied uses
541 * little-endian ordering. Require that oat2dex do any required swapping
542 * so this routine can get by with a memcpy().
543 *
544 * Format of the data:
545 * ushort ident = 0x0300 magic value
546 * ushort width width of each element in the table
547 * uint size number of elements in the table
548 * ubyte data[size*width] table of data values (may contain a single-byte
549 * padding at the end)
550 */
551extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
552 DCHECK_EQ(table[0], 0x0300);
553 if (array == NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700554 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
555 "null array in fill array");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700556 return -1; // Error
557 }
558 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
559 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
560 if (static_cast<int32_t>(size) > array->GetLength()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700561 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
562 "failed array fill. length=%d; index=%d", array->GetLength(), size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700563 return -1; // Error
564 }
565 uint16_t width = table[1];
566 uint32_t size_in_bytes = size * width;
567 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
568 return 0; // Success
569}
570
571// See comments in runtime_support_asm.S
572extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
573 Object* this_object ,
574 Method* caller_method) {
575 Thread* thread = Thread::Current();
576 if (this_object == NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700577 thread->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
578 "null receiver during interface dispatch");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700579 return 0;
580 }
581 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
582 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
583 if (interface_method == NULL) {
584 // Could not resolve interface method. Throw error and unwind
585 CHECK(thread->IsExceptionPending());
586 return 0;
587 }
588 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
589 if (method == NULL) {
590 CHECK(thread->IsExceptionPending());
591 return 0;
592 }
593 const void* code = method->GetCode();
594
595 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
596 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
597 uint64_t result = ((code_uint << 32) | method_uint);
598 return result;
599}
600
601/*
602 * Float/double conversion requires clamping to min and max of integer form. If
603 * target doesn't support this normally, use these.
604 */
605int64_t D2L(double d) {
606 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
607 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
608 if (d >= kMaxLong)
609 return (int64_t)0x7fffffffffffffffULL;
610 else if (d <= kMinLong)
611 return (int64_t)0x8000000000000000ULL;
612 else if (d != d) // NaN case
613 return 0;
614 else
615 return (int64_t)d;
616}
617
618int64_t F2L(float f) {
619 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
620 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
621 if (f >= kMaxLong)
622 return (int64_t)0x7fffffffffffffffULL;
623 else if (f <= kMinLong)
624 return (int64_t)0x8000000000000000ULL;
625 else if (f != f) // NaN case
626 return 0;
627 else
628 return (int64_t)f;
629}
630
631} // namespace art