blob: 9cc88049bad8eb9726a8d3b8b9e4d94b2ffa9cd1 [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,
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700313 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700314 // 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]);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700330 uintptr_t caller_pc = regs[4];
Ian Rogersad25ac52011-10-04 19:13:33 -0700331 // Record the last top of the managed stack
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700332 thread->SetTopOfStack(caller_sp, caller_pc);
Ian Rogersad25ac52011-10-04 19:13:33 -0700333 // 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)
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700338 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Ian Rogersad25ac52011-10-04 19:13:33 -0700339 const char* shorty = linker->MethodShorty(method_idx, *caller_sp);
340 size_t shorty_len = strlen(shorty);
341 size_t args_in_regs = shorty_len < 3 ? shorty_len : 3;
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700342 if (type == Runtime::kUnknownMethod) {
343 uint32_t dex_pc = (*caller_sp)->ToDexPC(caller_pc - 2);
344 UNIMPLEMENTED(WARNING) << "Missed argument handlerization in direct method trampoline. "
345 "Need to discover method invoke type at " << PrettyMethod(*caller_sp)
346 << " PC: " << (void*)dex_pc;
347 } else {
348 bool is_static = type == Runtime::kStaticMethod;
349 // Handlerize references in registers
350 int cur_arg = 1; // skip method_idx in R0, first arg is in R1
351 if (!is_static) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700352 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700353 cur_arg++;
Ian Rogersad25ac52011-10-04 19:13:33 -0700354 AddLocalReference<jobject>(env, obj);
355 }
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700356 for(size_t i = 0; i < args_in_regs; i++) {
357 char c = shorty[i + 1]; // offset to skip return value
358 if (c == 'L') {
359 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
360 AddLocalReference<jobject>(env, obj);
361 }
362 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
Ian Rogersad25ac52011-10-04 19:13:33 -0700363 }
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700364 // Handlerize references in out going arguments
365 for(size_t i = 3; i < shorty_len; i++) {
366 char c = shorty[i + 1]; // offset to skip return value
367 if (c == 'L') {
368 Object* obj = reinterpret_cast<Object*>(regs[i + 3]); // skip R0, LR and Method* of caller
369 AddLocalReference<jobject>(env, obj);
370 }
371 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
372 }
Ian Rogersad25ac52011-10-04 19:13:33 -0700373 }
374 // Resolve method filling in dex cache
375 Method* called = linker->ResolveMethod(method_idx, *caller_sp, true);
376 if (!thread->IsExceptionPending()) {
377 // We got this far, ensure that the declaring class is initialized
378 linker->EnsureInitialized(called->GetDeclaringClass(), true);
379 }
380 // Restore JNI env state
381 env->locals.SetSegmentState(env->local_ref_cookie);
382 env->local_ref_cookie = saved_local_ref_cookie;
383
384 void* code;
385 if (thread->IsExceptionPending()) {
386 // Something went wrong, go into deliver exception with the pending exception in r0
387 code = reinterpret_cast<void*>(art_deliver_exception_from_code);
388 regs[0] = reinterpret_cast<uintptr_t>(thread->GetException());
389 thread->ClearException();
390 } else {
391 // Expect class to at least be initializing
392 CHECK(called->GetDeclaringClass()->IsInitializing());
393 // Set up entry into main method
394 regs[0] = reinterpret_cast<uintptr_t>(called);
395 code = const_cast<void*>(called->GetCode());
396 }
397 return code;
398}
399
Shih-wei Liao2d831012011-09-28 22:06:53 -0700400// TODO: placeholder. Helper function to type
401Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
402 /*
403 * Should initialize & fix up method->dex_cache_resolved_types_[].
404 * Returns initialized type. Does not return normally if an exception
405 * is thrown, but instead initiates the catch. Should be similar to
406 * ClassLinker::InitializeStaticStorageFromCode.
407 */
408 UNIMPLEMENTED(FATAL);
409 return NULL;
410}
411
412// TODO: placeholder. Helper function to resolve virtual method
413void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
414 /*
415 * Slow-path handler on invoke virtual method path in which
416 * base method is unresolved at compile-time. Doesn't need to
417 * return anything - just either ensure that
418 * method->dex_cache_resolved_methods_(method_idx) != NULL or
419 * throw and unwind. The caller will restart call sequence
420 * from the beginning.
421 */
422}
423
424// Given the context of a calling Method, use its DexCache to resolve a type to a Class. If it
425// cannot be resolved, throw an error. If it can, use it to create an instance.
buzbee33a129c2011-10-06 16:53:20 -0700426extern "C" Object* artAllocObjectFromCode(uint32_t type_idx, Method* method, Thread* self, Method** sp) {
427 // Place a special frame at the TOS that will save all callee saves
428 Runtime* runtime = Runtime::Current();
429 *sp = runtime->GetCalleeSaveMethod();
430 self->SetTopOfStack(sp, 0);
431
Shih-wei Liao2d831012011-09-28 22:06:53 -0700432 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
433 if (klass == NULL) {
buzbee33a129c2011-10-06 16:53:20 -0700434 klass = runtime->GetClassLinker()->ResolveType(type_idx, method);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700435 if (klass == NULL) {
buzbee33a129c2011-10-06 16:53:20 -0700436 DCHECK(self->IsExceptionPending());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700437 return NULL; // Failure
438 }
439 }
buzbee33a129c2011-10-06 16:53:20 -0700440 if (!runtime->GetClassLinker()->EnsureInitialized(klass, true)) {
441 DCHECK(self->IsExceptionPending());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700442 return NULL; // Failure
443 }
444 return klass->AllocObject();
445}
446
447// Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesb408de72011-10-04 14:35:05 -0700448extern "C" Array* artCheckAndAllocArrayFromCode(uint32_t type_idx, Method* method,
Shih-wei Liao2d831012011-09-28 22:06:53 -0700449 int32_t component_count) {
450 if (component_count < 0) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700451 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700452 component_count);
453 return NULL; // Failure
454 }
455 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
456 if (klass == NULL) { // Not in dex cache so try to resolve
457 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
458 if (klass == NULL) { // Error
459 DCHECK(Thread::Current()->IsExceptionPending());
460 return NULL; // Failure
461 }
462 }
463 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
464 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700465 Thread::Current()->ThrowNewExceptionF("Ljava/lang/RuntimeException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700466 "Bad filled array request for type %s",
467 PrettyDescriptor(klass->GetDescriptor()).c_str());
468 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700469 Thread::Current()->ThrowNewExceptionF("Ljava/lang/InternalError;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700470 "Found type %s; filled-new-array not implemented for anything but \'int\'",
471 PrettyDescriptor(klass->GetDescriptor()).c_str());
472 }
473 return NULL; // Failure
474 } else {
475 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
476 return Array::Alloc(klass, component_count);
477 }
478}
479
480// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
481// it cannot be resolved, throw an error. If it can, use it to create an array.
buzbee33a129c2011-10-06 16:53:20 -0700482extern "C" Array* artAllocArrayFromCode(uint32_t type_idx, Method* method, int32_t component_count, Thread* self, Method** sp) {
483 // Place a special frame at the TOS that will save all callee saves
484 Runtime* runtime = Runtime::Current();
485 *sp = runtime->GetCalleeSaveMethod();
486 self->SetTopOfStack(sp, 0);
487
Shih-wei Liao2d831012011-09-28 22:06:53 -0700488 if (component_count < 0) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700489 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700490 component_count);
491 return NULL; // Failure
492 }
493 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
494 if (klass == NULL) { // Not in dex cache so try to resolve
495 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
496 if (klass == NULL) { // Error
497 DCHECK(Thread::Current()->IsExceptionPending());
498 return NULL; // Failure
499 }
500 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
501 }
502 return Array::Alloc(klass, component_count);
503}
504
505// Check whether it is safe to cast one class to the other, throw exception and return -1 on failure
506extern "C" int artCheckCastFromCode(const Class* a, const Class* b) {
507 DCHECK(a->IsClass()) << PrettyClass(a);
508 DCHECK(b->IsClass()) << PrettyClass(b);
509 if (b->IsAssignableFrom(a)) {
510 return 0; // Success
511 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700512 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassCastException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700513 "%s cannot be cast to %s",
514 PrettyDescriptor(a->GetDescriptor()).c_str(),
515 PrettyDescriptor(b->GetDescriptor()).c_str());
516 return -1; // Failure
517 }
518}
519
520// Tests whether 'element' can be assigned into an array of type 'array_class'.
521// Returns 0 on success and -1 if an exception is pending.
522extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class) {
523 DCHECK(array_class != NULL);
524 // element can't be NULL as we catch this is screened in runtime_support
525 Class* element_class = element->GetClass();
526 Class* component_type = array_class->GetComponentType();
527 if (component_type->IsAssignableFrom(element_class)) {
528 return 0; // Success
529 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700530 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700531 "Cannot store an object of type %s in to an array of type %s",
532 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
533 PrettyDescriptor(array_class->GetDescriptor()).c_str());
534 return -1; // Failure
535 }
536}
537
538extern "C" int artUnlockObjectFromCode(Thread* thread, Object* obj) {
539 DCHECK(obj != NULL); // Assumed to have been checked before entry
540 return obj->MonitorExit(thread) ? 0 /* Success */ : -1 /* Failure */;
541}
542
543void LockObjectFromCode(Thread* thread, Object* obj) {
544 DCHECK(obj != NULL); // Assumed to have been checked before entry
545 obj->MonitorEnter(thread);
546 DCHECK(thread->HoldsLock(obj));
547 // Only possible exception is NPE and is handled before entry
548 DCHECK(!thread->IsExceptionPending());
549}
550
551extern "C" void artCheckSuspendFromCode(Thread* thread) {
552 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
553}
554
555/*
556 * Fill the array with predefined constant values, throwing exceptions if the array is null or
557 * not of sufficient length.
558 *
559 * NOTE: When dealing with a raw dex file, the data to be copied uses
560 * little-endian ordering. Require that oat2dex do any required swapping
561 * so this routine can get by with a memcpy().
562 *
563 * Format of the data:
564 * ushort ident = 0x0300 magic value
565 * ushort width width of each element in the table
566 * uint size number of elements in the table
567 * ubyte data[size*width] table of data values (may contain a single-byte
568 * padding at the end)
569 */
570extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table) {
571 DCHECK_EQ(table[0], 0x0300);
572 if (array == NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700573 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
574 "null array in fill array");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700575 return -1; // Error
576 }
577 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
578 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
579 if (static_cast<int32_t>(size) > array->GetLength()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700580 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
581 "failed array fill. length=%d; index=%d", array->GetLength(), size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700582 return -1; // Error
583 }
584 uint16_t width = table[1];
585 uint32_t size_in_bytes = size * width;
586 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
587 return 0; // Success
588}
589
590// See comments in runtime_support_asm.S
591extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
592 Object* this_object ,
593 Method* caller_method) {
594 Thread* thread = Thread::Current();
595 if (this_object == NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700596 thread->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
597 "null receiver during interface dispatch");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700598 return 0;
599 }
600 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
601 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
602 if (interface_method == NULL) {
603 // Could not resolve interface method. Throw error and unwind
604 CHECK(thread->IsExceptionPending());
605 return 0;
606 }
607 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
608 if (method == NULL) {
609 CHECK(thread->IsExceptionPending());
610 return 0;
611 }
612 const void* code = method->GetCode();
613
614 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
615 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
616 uint64_t result = ((code_uint << 32) | method_uint);
617 return result;
618}
619
620/*
621 * Float/double conversion requires clamping to min and max of integer form. If
622 * target doesn't support this normally, use these.
623 */
624int64_t D2L(double d) {
625 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
626 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
627 if (d >= kMaxLong)
628 return (int64_t)0x7fffffffffffffffULL;
629 else if (d <= kMinLong)
630 return (int64_t)0x8000000000000000ULL;
631 else if (d != d) // NaN case
632 return 0;
633 else
634 return (int64_t)d;
635}
636
637int64_t F2L(float f) {
638 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
639 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
640 if (f >= kMaxLong)
641 return (int64_t)0x7fffffffffffffffULL;
642 else if (f <= kMinLong)
643 return (int64_t)0x8000000000000000ULL;
644 else if (f != f) // NaN case
645 return 0;
646 else
647 return (int64_t)f;
648}
649
650} // namespace art