blob: 6a11e11b477b0eced8724dc5fa79bda7b159db58 [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) {
25 *sp = Runtime::Current()->GetCalleeSaveMethod(type);
26 self->SetTopOfStack(sp, 0);
27}
28
Shih-wei Liao2d831012011-09-28 22:06:53 -070029// Temporary debugging hook for compiler.
30extern void DebugMe(Method* method, uint32_t info) {
31 LOG(INFO) << "DebugMe";
32 if (method != NULL) {
33 LOG(INFO) << PrettyMethod(method);
34 }
35 LOG(INFO) << "Info: " << info;
36}
37
38// Return value helper for jobject return types
39extern Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
40 return thread->DecodeJObject(obj);
41}
42
43extern void* FindNativeMethod(Thread* thread) {
44 DCHECK(Thread::Current() == thread);
45
46 Method* method = const_cast<Method*>(thread->GetCurrentMethod());
47 DCHECK(method != NULL);
48
49 // Lookup symbol address for method, on failure we'll return NULL with an
50 // exception set, otherwise we return the address of the method we found.
51 void* native_code = thread->GetJniEnv()->vm->FindCodeForNativeMethod(method);
52 if (native_code == NULL) {
53 DCHECK(thread->IsExceptionPending());
54 return NULL;
55 } else {
56 // Register so that future calls don't come here
57 method->RegisterNative(native_code);
58 return native_code;
59 }
60}
61
62// Called by generated call to throw an exception
63extern "C" void artDeliverExceptionFromCode(Throwable* exception, Thread* thread, Method** sp) {
64 /*
65 * exception may be NULL, in which case this routine should
66 * throw NPE. NOTE: this is a convenience for generated code,
67 * which previously did the null check inline and constructed
68 * and threw a NPE if NULL. This routine responsible for setting
69 * exception_ in thread and delivering the exception.
70 */
Ian Rogers4f0d07c2011-10-06 23:38:47 -070071 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -070072 if (exception == NULL) {
73 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
74 } else {
75 thread->SetException(exception);
76 }
77 thread->DeliverException();
78}
79
80// Deliver an exception that's pending on thread helping set up a callee save frame on the way
81extern "C" void artDeliverPendingExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070082 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -070083 thread->DeliverException();
84}
85
86// Called by generated call to throw a NPE exception
87extern "C" void artThrowNullPointerExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070088 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070089 thread->ThrowNewException("Ljava/lang/NullPointerException;", NULL);
Shih-wei Liao2d831012011-09-28 22:06:53 -070090 thread->DeliverException();
91}
92
93// Called by generated call to throw an arithmetic divide by zero exception
94extern "C" void artThrowDivZeroFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070095 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -070096 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
97 thread->DeliverException();
98}
99
100// Called by generated call to throw an arithmetic divide by zero exception
101extern "C" void artThrowArrayBoundsFromCode(int index, int limit, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700102 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
103 thread->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
104 "length=%d; index=%d", limit, index);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700105 thread->DeliverException();
106}
107
108// Called by the AbstractMethodError stub (not runtime support)
109extern void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700110 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
111 thread->ThrowNewExceptionF("Ljava/lang/AbstractMethodError;",
112 "abstract method \"%s\"", PrettyMethod(method).c_str());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700113 thread->DeliverException();
114}
115
116extern "C" void artThrowStackOverflowFromCode(Method* method, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700117 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700118 thread->SetStackEndForStackOverflow(); // Allow space on the stack for constructor to execute
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700119 thread->ThrowNewExceptionF("Ljava/lang/StackOverflowError;",
120 "stack size %zdkb; default stack size: %zdkb",
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700121 thread->GetStackSize() / KB, Runtime::Current()->GetDefaultStackSize() / KB);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700122 thread->ResetDefaultStackEnd(); // Return to default stack size
123 thread->DeliverException();
124}
125
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700126static std::string ClassNameFromIndex(Method* method, uint32_t ref,
127 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700128 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
129 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
130
131 uint16_t type_idx = 0;
132 if (ref_type == DexVerifier::VERIFY_ERROR_REF_FIELD) {
133 const DexFile::FieldId& id = dex_file.GetFieldId(ref);
134 type_idx = id.class_idx_;
135 } else if (ref_type == DexVerifier::VERIFY_ERROR_REF_METHOD) {
136 const DexFile::MethodId& id = dex_file.GetMethodId(ref);
137 type_idx = id.class_idx_;
138 } else if (ref_type == DexVerifier::VERIFY_ERROR_REF_CLASS) {
139 type_idx = ref;
140 } else {
141 CHECK(false) << static_cast<int>(ref_type);
142 }
143
144 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(type_idx)));
145 if (!access) {
146 return class_name;
147 }
148
149 std::string result;
150 result += "tried to access class ";
151 result += class_name;
152 result += " from class ";
153 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
154 return result;
155}
156
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700157static std::string FieldNameFromIndex(const Method* method, uint32_t ref,
158 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700159 CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(DexVerifier::VERIFY_ERROR_REF_FIELD));
160
161 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
162 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
163
164 const DexFile::FieldId& id = dex_file.GetFieldId(ref);
165 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(id.class_idx_)));
166 const char* field_name = dex_file.dexStringById(id.name_idx_);
167 if (!access) {
168 return class_name + "." + field_name;
169 }
170
171 std::string result;
172 result += "tried to access field ";
173 result += class_name + "." + field_name;
174 result += " from class ";
175 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
176 return result;
177}
178
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700179static std::string MethodNameFromIndex(const Method* method, uint32_t ref,
180 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700181 CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(DexVerifier::VERIFY_ERROR_REF_METHOD));
182
183 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
184 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
185
186 const DexFile::MethodId& id = dex_file.GetMethodId(ref);
187 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(id.class_idx_)));
188 const char* method_name = dex_file.dexStringById(id.name_idx_);
189 if (!access) {
190 return class_name + "." + method_name;
191 }
192
193 std::string result;
194 result += "tried to access method ";
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700195 result += class_name + "." + method_name + ":" +
196 dex_file.CreateMethodDescriptor(id.proto_idx_, NULL);
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700197 result += " from class ";
198 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
199 return result;
200}
201
202extern "C" void artThrowVerificationErrorFromCode(int32_t kind, int32_t ref, Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700203 FinishCalleeSaveFrameSetup(self, sp, Runtime::kSaveAll);
204 Frame frame = self->GetTopOfStack(); // We need the calling method as context to interpret 'ref'
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700205 frame.Next();
206 Method* method = frame.GetMethod();
207
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700208 DexVerifier::VerifyErrorRefType ref_type =
209 static_cast<DexVerifier::VerifyErrorRefType>(kind >> kVerifyErrorRefTypeShift);
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700210
211 const char* exception_class = "Ljava/lang/VerifyError;";
212 std::string msg;
213
214 switch (static_cast<DexVerifier::VerifyError>(kind & ~(0xff << kVerifyErrorRefTypeShift))) {
215 case DexVerifier::VERIFY_ERROR_NO_CLASS:
216 exception_class = "Ljava/lang/NoClassDefFoundError;";
217 msg = ClassNameFromIndex(method, ref, ref_type, false);
218 break;
219 case DexVerifier::VERIFY_ERROR_NO_FIELD:
220 exception_class = "Ljava/lang/NoSuchFieldError;";
221 msg = FieldNameFromIndex(method, ref, ref_type, false);
222 break;
223 case DexVerifier::VERIFY_ERROR_NO_METHOD:
224 exception_class = "Ljava/lang/NoSuchMethodError;";
225 msg = MethodNameFromIndex(method, ref, ref_type, false);
226 break;
227 case DexVerifier::VERIFY_ERROR_ACCESS_CLASS:
228 exception_class = "Ljava/lang/IllegalAccessError;";
229 msg = ClassNameFromIndex(method, ref, ref_type, true);
230 break;
231 case DexVerifier::VERIFY_ERROR_ACCESS_FIELD:
232 exception_class = "Ljava/lang/IllegalAccessError;";
233 msg = FieldNameFromIndex(method, ref, ref_type, true);
234 break;
235 case DexVerifier::VERIFY_ERROR_ACCESS_METHOD:
236 exception_class = "Ljava/lang/IllegalAccessError;";
237 msg = MethodNameFromIndex(method, ref, ref_type, true);
238 break;
239 case DexVerifier::VERIFY_ERROR_CLASS_CHANGE:
240 exception_class = "Ljava/lang/IncompatibleClassChangeError;";
241 msg = ClassNameFromIndex(method, ref, ref_type, false);
242 break;
243 case DexVerifier::VERIFY_ERROR_INSTANTIATION:
244 exception_class = "Ljava/lang/InstantiationError;";
245 msg = ClassNameFromIndex(method, ref, ref_type, false);
246 break;
247 case DexVerifier::VERIFY_ERROR_GENERIC:
248 // Generic VerifyError; use default exception, no message.
249 break;
250 case DexVerifier::VERIFY_ERROR_NONE:
251 CHECK(false);
252 break;
253 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700254 self->ThrowNewException(exception_class, msg.c_str());
255 self->DeliverException();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700256}
257
258extern "C" void artThrowInternalErrorFromCode(int32_t errnum, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700259 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700260 LOG(WARNING) << "TODO: internal error detail message. errnum=" << errnum;
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700261 thread->ThrowNewExceptionF("Ljava/lang/InternalError;", "errnum=%d", errnum);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700262 thread->DeliverException();
263}
264
265extern "C" void artThrowRuntimeExceptionFromCode(int32_t errnum, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700266 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700267 LOG(WARNING) << "TODO: runtime exception detail message. errnum=" << errnum;
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700268 thread->ThrowNewExceptionF("Ljava/lang/RuntimeException;", "errnum=%d", errnum);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700269 thread->DeliverException();
270}
271
Elliott Hughese1410a22011-10-04 12:10:24 -0700272extern "C" void artThrowNoSuchMethodFromCode(int32_t method_idx, Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700273 FinishCalleeSaveFrameSetup(self, sp, Runtime::kSaveAll);
274 Frame frame = self->GetTopOfStack(); // We need the calling method as context for the method_idx
Elliott Hughese1410a22011-10-04 12:10:24 -0700275 frame.Next();
276 Method* method = frame.GetMethod();
Elliott Hughese1410a22011-10-04 12:10:24 -0700277 self->ThrowNewException("Ljava/lang/NoSuchMethodError;",
278 MethodNameFromIndex(method, method_idx, DexVerifier::VERIFY_ERROR_REF_METHOD, false).c_str());
279 self->DeliverException();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700280}
281
282extern "C" void artThrowNegArraySizeFromCode(int32_t size, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700283 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700284 LOG(WARNING) << "UNTESTED artThrowNegArraySizeFromCode";
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700285 thread->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d", size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700286 thread->DeliverException();
287}
288
Ian Rogersad25ac52011-10-04 19:13:33 -0700289void* UnresolvedDirectMethodTrampolineFromCode(int32_t method_idx, void* sp, Thread* thread,
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700290 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700291 // TODO: this code is specific to ARM
292 // On entry the stack pointed by sp is:
293 // | argN | |
294 // | ... | |
295 // | arg4 | |
296 // | arg3 spill | | Caller's frame
297 // | arg2 spill | |
298 // | arg1 spill | |
299 // | Method* | ---
300 // | LR |
301 // | R3 | arg3
302 // | R2 | arg2
303 // | R1 | arg1
304 // | R0 | <- sp
305 uintptr_t* regs = reinterpret_cast<uintptr_t*>(sp);
306 Method** caller_sp = reinterpret_cast<Method**>(&regs[5]);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700307 uintptr_t caller_pc = regs[4];
Ian Rogersad25ac52011-10-04 19:13:33 -0700308 // Record the last top of the managed stack
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700309 thread->SetTopOfStack(caller_sp, caller_pc);
Ian Rogersad25ac52011-10-04 19:13:33 -0700310 // Start new JNI local reference state
311 JNIEnvExt* env = thread->GetJniEnv();
312 uint32_t saved_local_ref_cookie = env->local_ref_cookie;
313 env->local_ref_cookie = env->locals.GetSegmentState();
314 // Discover shorty (avoid GCs)
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700315 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Ian Rogersad25ac52011-10-04 19:13:33 -0700316 const char* shorty = linker->MethodShorty(method_idx, *caller_sp);
317 size_t shorty_len = strlen(shorty);
318 size_t args_in_regs = shorty_len < 3 ? shorty_len : 3;
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700319 if (type == Runtime::kUnknownMethod) {
320 uint32_t dex_pc = (*caller_sp)->ToDexPC(caller_pc - 2);
321 UNIMPLEMENTED(WARNING) << "Missed argument handlerization in direct method trampoline. "
322 "Need to discover method invoke type at " << PrettyMethod(*caller_sp)
323 << " PC: " << (void*)dex_pc;
324 } else {
325 bool is_static = type == Runtime::kStaticMethod;
326 // Handlerize references in registers
327 int cur_arg = 1; // skip method_idx in R0, first arg is in R1
328 if (!is_static) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700329 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700330 cur_arg++;
Ian Rogersad25ac52011-10-04 19:13:33 -0700331 AddLocalReference<jobject>(env, obj);
332 }
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700333 for(size_t i = 0; i < args_in_regs; i++) {
334 char c = shorty[i + 1]; // offset to skip return value
335 if (c == 'L') {
336 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
337 AddLocalReference<jobject>(env, obj);
338 }
339 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
Ian Rogersad25ac52011-10-04 19:13:33 -0700340 }
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700341 // Handlerize references in out going arguments
342 for(size_t i = 3; i < shorty_len; i++) {
343 char c = shorty[i + 1]; // offset to skip return value
344 if (c == 'L') {
345 Object* obj = reinterpret_cast<Object*>(regs[i + 3]); // skip R0, LR and Method* of caller
346 AddLocalReference<jobject>(env, obj);
347 }
348 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
349 }
Ian Rogersad25ac52011-10-04 19:13:33 -0700350 }
351 // Resolve method filling in dex cache
352 Method* called = linker->ResolveMethod(method_idx, *caller_sp, true);
353 if (!thread->IsExceptionPending()) {
354 // We got this far, ensure that the declaring class is initialized
355 linker->EnsureInitialized(called->GetDeclaringClass(), true);
356 }
357 // Restore JNI env state
358 env->locals.SetSegmentState(env->local_ref_cookie);
359 env->local_ref_cookie = saved_local_ref_cookie;
360
361 void* code;
362 if (thread->IsExceptionPending()) {
363 // Something went wrong, go into deliver exception with the pending exception in r0
364 code = reinterpret_cast<void*>(art_deliver_exception_from_code);
365 regs[0] = reinterpret_cast<uintptr_t>(thread->GetException());
366 thread->ClearException();
367 } else {
368 // Expect class to at least be initializing
369 CHECK(called->GetDeclaringClass()->IsInitializing());
370 // Set up entry into main method
371 regs[0] = reinterpret_cast<uintptr_t>(called);
372 code = const_cast<void*>(called->GetCode());
373 }
374 return code;
375}
376
Shih-wei Liao2d831012011-09-28 22:06:53 -0700377// TODO: placeholder. Helper function to type
378Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
379 /*
380 * Should initialize & fix up method->dex_cache_resolved_types_[].
381 * Returns initialized type. Does not return normally if an exception
382 * is thrown, but instead initiates the catch. Should be similar to
383 * ClassLinker::InitializeStaticStorageFromCode.
384 */
385 UNIMPLEMENTED(FATAL);
386 return NULL;
387}
388
389// TODO: placeholder. Helper function to resolve virtual method
390void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
391 /*
392 * Slow-path handler on invoke virtual method path in which
393 * base method is unresolved at compile-time. Doesn't need to
394 * return anything - just either ensure that
395 * method->dex_cache_resolved_methods_(method_idx) != NULL or
396 * throw and unwind. The caller will restart call sequence
397 * from the beginning.
398 */
399}
400
401// Given the context of a calling Method, use its DexCache to resolve a type to a Class. If it
402// cannot be resolved, throw an error. If it can, use it to create an instance.
buzbee33a129c2011-10-06 16:53:20 -0700403extern "C" Object* artAllocObjectFromCode(uint32_t type_idx, Method* method, Thread* self, Method** sp) {
404 // Place a special frame at the TOS that will save all callee saves
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700405 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700406 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700407 Runtime* runtime = Runtime::Current();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700408 if (klass == NULL) {
buzbee33a129c2011-10-06 16:53:20 -0700409 klass = runtime->GetClassLinker()->ResolveType(type_idx, method);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700410 if (klass == NULL) {
buzbee33a129c2011-10-06 16:53:20 -0700411 DCHECK(self->IsExceptionPending());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700412 return NULL; // Failure
413 }
414 }
buzbee33a129c2011-10-06 16:53:20 -0700415 if (!runtime->GetClassLinker()->EnsureInitialized(klass, true)) {
416 DCHECK(self->IsExceptionPending());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700417 return NULL; // Failure
418 }
419 return klass->AllocObject();
420}
421
422// Helper function to alloc array for OP_FILLED_NEW_ARRAY
Elliott Hughesb408de72011-10-04 14:35:05 -0700423extern "C" Array* artCheckAndAllocArrayFromCode(uint32_t type_idx, Method* method,
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700424 int32_t component_count, Thread* self, Method** sp) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700425 if (component_count < 0) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700426 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700427 component_count);
428 return NULL; // Failure
429 }
430 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
431 if (klass == NULL) { // Not in dex cache so try to resolve
432 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
433 if (klass == NULL) { // Error
434 DCHECK(Thread::Current()->IsExceptionPending());
435 return NULL; // Failure
436 }
437 }
438 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
439 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700440 Thread::Current()->ThrowNewExceptionF("Ljava/lang/RuntimeException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700441 "Bad filled array request for type %s",
442 PrettyDescriptor(klass->GetDescriptor()).c_str());
443 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700444 Thread::Current()->ThrowNewExceptionF("Ljava/lang/InternalError;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700445 "Found type %s; filled-new-array not implemented for anything but \'int\'",
446 PrettyDescriptor(klass->GetDescriptor()).c_str());
447 }
448 return NULL; // Failure
449 } else {
450 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
451 return Array::Alloc(klass, component_count);
452 }
453}
454
455// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
456// it cannot be resolved, throw an error. If it can, use it to create an array.
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700457extern "C" Array* artAllocArrayFromCode(uint32_t type_idx, Method* method, int32_t component_count,
458 Thread* self, Method** sp) {
459 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700460 if (component_count < 0) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700461 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700462 component_count);
463 return NULL; // Failure
464 }
465 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
466 if (klass == NULL) { // Not in dex cache so try to resolve
467 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
468 if (klass == NULL) { // Error
469 DCHECK(Thread::Current()->IsExceptionPending());
470 return NULL; // Failure
471 }
472 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
473 }
474 return Array::Alloc(klass, component_count);
475}
476
477// 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 -0700478extern "C" int artCheckCastFromCode(const Class* a, const Class* b, Thread* self, Method** sp) {
479 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700480 DCHECK(a->IsClass()) << PrettyClass(a);
481 DCHECK(b->IsClass()) << PrettyClass(b);
482 if (b->IsAssignableFrom(a)) {
483 return 0; // Success
484 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700485 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassCastException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700486 "%s cannot be cast to %s",
487 PrettyDescriptor(a->GetDescriptor()).c_str(),
488 PrettyDescriptor(b->GetDescriptor()).c_str());
489 return -1; // Failure
490 }
491}
492
493// Tests whether 'element' can be assigned into an array of type 'array_class'.
494// Returns 0 on success and -1 if an exception is pending.
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700495extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class,
496 Thread* self, Method** sp) {
497 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700498 DCHECK(array_class != NULL);
499 // element can't be NULL as we catch this is screened in runtime_support
500 Class* element_class = element->GetClass();
501 Class* component_type = array_class->GetComponentType();
502 if (component_type->IsAssignableFrom(element_class)) {
503 return 0; // Success
504 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700505 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700506 "Cannot store an object of type %s in to an array of type %s",
507 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
508 PrettyDescriptor(array_class->GetDescriptor()).c_str());
509 return -1; // Failure
510 }
511}
512
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700513Class* InitializeStaticStorage(uint32_t type_idx, const Method* referrer, Thread* self) {
514 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
515 Class* klass = class_linker->ResolveType(type_idx, referrer);
516 if (klass == NULL) {
517 CHECK(self->IsExceptionPending());
518 return NULL; // Failure - Indicate to caller to deliver exception
519 }
520 // If we are the <clinit> of this class, just return our storage.
521 //
522 // Do not set the DexCache InitializedStaticStorage, since that implies <clinit> has finished
523 // running.
524 if (klass == referrer->GetDeclaringClass() && referrer->IsClassInitializer()) {
525 return klass;
526 }
527 if (!class_linker->EnsureInitialized(klass, true)) {
528 CHECK(self->IsExceptionPending());
529 return NULL; // Failure - Indicate to caller to deliver exception
530 }
531 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
532 return klass;
Shih-wei Liao2d831012011-09-28 22:06:53 -0700533}
534
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700535extern "C" Class* artInitializeStaticStorageFromCode(uint32_t type_idx, const Method* referrer,
536 Thread* self, Method** sp) {
537 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
538 return InitializeStaticStorage(type_idx, referrer, self);
539}
540
541extern "C" int artUnlockObjectFromCode(Object* obj, Thread* self, Method** sp) {
542 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700543 DCHECK(obj != NULL); // Assumed to have been checked before entry
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700544 // MonitorExit may throw exception
545 return obj->MonitorExit(self) ? 0 /* Success */ : -1 /* Failure */;
546}
547
548extern "C" void artLockObjectFromCode(Object* obj, Thread* thread, Method** sp) {
549 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsOnly);
550 DCHECK(obj != NULL); // Assumed to have been checked before entry
551 obj->MonitorEnter(thread); // May block
Shih-wei Liao2d831012011-09-28 22:06:53 -0700552 DCHECK(thread->HoldsLock(obj));
553 // Only possible exception is NPE and is handled before entry
554 DCHECK(!thread->IsExceptionPending());
555}
556
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700557extern "C" void artCheckSuspendFromJni(Thread* thread) {
558 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
559}
560
561extern "C" void artCheckSuspendFromCode(Thread* thread, Method** sp) {
562 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700563 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
564}
565
566/*
567 * Fill the array with predefined constant values, throwing exceptions if the array is null or
568 * not of sufficient length.
569 *
570 * NOTE: When dealing with a raw dex file, the data to be copied uses
571 * little-endian ordering. Require that oat2dex do any required swapping
572 * so this routine can get by with a memcpy().
573 *
574 * Format of the data:
575 * ushort ident = 0x0300 magic value
576 * ushort width width of each element in the table
577 * uint size number of elements in the table
578 * ubyte data[size*width] table of data values (may contain a single-byte
579 * padding at the end)
580 */
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700581extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table,
582 Thread* self, Method** sp) {
583 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700584 DCHECK_EQ(table[0], 0x0300);
585 if (array == NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700586 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
587 "null array in fill array");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700588 return -1; // Error
589 }
590 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
591 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
592 if (static_cast<int32_t>(size) > array->GetLength()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700593 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
594 "failed array fill. length=%d; index=%d", array->GetLength(), size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700595 return -1; // Error
596 }
597 uint16_t width = table[1];
598 uint32_t size_in_bytes = size * width;
599 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
600 return 0; // Success
601}
602
603// See comments in runtime_support_asm.S
604extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
605 Object* this_object ,
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700606 Thread* thread, Method** sp) {
607 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsAndArgs);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700608 if (this_object == NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700609 thread->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
610 "null receiver during interface dispatch");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700611 return 0;
612 }
613 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700614 Frame frame = thread->GetTopOfStack(); // Compute calling method
615 frame.Next();
616 Method* caller_method = frame.GetMethod();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700617 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
618 if (interface_method == NULL) {
619 // Could not resolve interface method. Throw error and unwind
620 CHECK(thread->IsExceptionPending());
621 return 0;
622 }
623 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
624 if (method == NULL) {
625 CHECK(thread->IsExceptionPending());
626 return 0;
627 }
628 const void* code = method->GetCode();
629
630 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
631 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
632 uint64_t result = ((code_uint << 32) | method_uint);
633 return result;
634}
635
636/*
637 * Float/double conversion requires clamping to min and max of integer form. If
638 * target doesn't support this normally, use these.
639 */
640int64_t D2L(double d) {
641 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
642 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
643 if (d >= kMaxLong)
644 return (int64_t)0x7fffffffffffffffULL;
645 else if (d <= kMinLong)
646 return (int64_t)0x8000000000000000ULL;
647 else if (d != d) // NaN case
648 return 0;
649 else
650 return (int64_t)d;
651}
652
653int64_t F2L(float f) {
654 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
655 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
656 if (f >= kMaxLong)
657 return (int64_t)0x7fffffffffffffffULL;
658 else if (f <= kMinLong)
659 return (int64_t)0x8000000000000000ULL;
660 else if (f != f) // NaN case
661 return 0;
662 else
663 return (int64_t)f;
664}
665
666} // namespace art