blob: 6ebe36e1c29445899471e6ae1e08df6ebb7240b4 [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) {
Brian Carlstrom6f495f22011-10-10 15:05:03 -070041 if (thread->IsExceptionPending()) {
42 return NULL;
43 }
Shih-wei Liao2d831012011-09-28 22:06:53 -070044 return thread->DecodeJObject(obj);
45}
46
47extern void* FindNativeMethod(Thread* thread) {
48 DCHECK(Thread::Current() == thread);
49
50 Method* method = const_cast<Method*>(thread->GetCurrentMethod());
51 DCHECK(method != NULL);
52
53 // Lookup symbol address for method, on failure we'll return NULL with an
54 // exception set, otherwise we return the address of the method we found.
55 void* native_code = thread->GetJniEnv()->vm->FindCodeForNativeMethod(method);
56 if (native_code == NULL) {
57 DCHECK(thread->IsExceptionPending());
58 return NULL;
59 } else {
60 // Register so that future calls don't come here
61 method->RegisterNative(native_code);
62 return native_code;
63 }
64}
65
66// Called by generated call to throw an exception
67extern "C" void artDeliverExceptionFromCode(Throwable* exception, Thread* thread, Method** sp) {
68 /*
69 * exception may be NULL, in which case this routine should
70 * throw NPE. NOTE: this is a convenience for generated code,
71 * which previously did the null check inline and constructed
72 * and threw a NPE if NULL. This routine responsible for setting
73 * exception_ in thread and delivering the exception.
74 */
Ian Rogers4f0d07c2011-10-06 23:38:47 -070075 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -070076 if (exception == NULL) {
77 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
78 } else {
79 thread->SetException(exception);
80 }
81 thread->DeliverException();
82}
83
84// Deliver an exception that's pending on thread helping set up a callee save frame on the way
85extern "C" void artDeliverPendingExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070086 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -070087 thread->DeliverException();
88}
89
90// Called by generated call to throw a NPE exception
91extern "C" void artThrowNullPointerExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070092 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070093 thread->ThrowNewException("Ljava/lang/NullPointerException;", NULL);
Shih-wei Liao2d831012011-09-28 22:06:53 -070094 thread->DeliverException();
95}
96
97// Called by generated call to throw an arithmetic divide by zero exception
98extern "C" void artThrowDivZeroFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070099 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700100 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
101 thread->DeliverException();
102}
103
104// Called by generated call to throw an arithmetic divide by zero exception
105extern "C" void artThrowArrayBoundsFromCode(int index, int limit, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700106 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
107 thread->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
108 "length=%d; index=%d", limit, index);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700109 thread->DeliverException();
110}
111
112// Called by the AbstractMethodError stub (not runtime support)
113extern void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700114 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
115 thread->ThrowNewExceptionF("Ljava/lang/AbstractMethodError;",
116 "abstract method \"%s\"", 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) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700121 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700122 thread->SetStackEndForStackOverflow(); // Allow space on the stack for constructor to execute
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700123 thread->ThrowNewExceptionF("Ljava/lang/StackOverflowError;",
124 "stack size %zdkb; default stack size: %zdkb",
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700125 thread->GetStackSize() / KB, Runtime::Current()->GetDefaultStackSize() / KB);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700126 thread->ResetDefaultStackEnd(); // Return to default stack size
127 thread->DeliverException();
128}
129
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700130static std::string ClassNameFromIndex(Method* method, uint32_t ref,
131 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700132 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
133 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
134
135 uint16_t type_idx = 0;
136 if (ref_type == DexVerifier::VERIFY_ERROR_REF_FIELD) {
137 const DexFile::FieldId& id = dex_file.GetFieldId(ref);
138 type_idx = id.class_idx_;
139 } else if (ref_type == DexVerifier::VERIFY_ERROR_REF_METHOD) {
140 const DexFile::MethodId& id = dex_file.GetMethodId(ref);
141 type_idx = id.class_idx_;
142 } else if (ref_type == DexVerifier::VERIFY_ERROR_REF_CLASS) {
143 type_idx = ref;
144 } else {
145 CHECK(false) << static_cast<int>(ref_type);
146 }
147
148 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(type_idx)));
149 if (!access) {
150 return class_name;
151 }
152
153 std::string result;
154 result += "tried to access class ";
155 result += class_name;
156 result += " from class ";
157 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
158 return result;
159}
160
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700161static std::string FieldNameFromIndex(const Method* method, uint32_t ref,
162 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700163 CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(DexVerifier::VERIFY_ERROR_REF_FIELD));
164
165 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
166 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
167
168 const DexFile::FieldId& id = dex_file.GetFieldId(ref);
169 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(id.class_idx_)));
170 const char* field_name = dex_file.dexStringById(id.name_idx_);
171 if (!access) {
172 return class_name + "." + field_name;
173 }
174
175 std::string result;
176 result += "tried to access field ";
177 result += class_name + "." + field_name;
178 result += " from class ";
179 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
180 return result;
181}
182
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700183static std::string MethodNameFromIndex(const Method* method, uint32_t ref,
184 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700185 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 ";
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700199 result += class_name + "." + method_name + ":" +
200 dex_file.CreateMethodDescriptor(id.proto_idx_, NULL);
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700201 result += " from class ";
202 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
203 return result;
204}
205
206extern "C" void artThrowVerificationErrorFromCode(int32_t kind, int32_t ref, Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700207 FinishCalleeSaveFrameSetup(self, sp, Runtime::kSaveAll);
208 Frame frame = self->GetTopOfStack(); // We need the calling method as context to interpret 'ref'
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700209 frame.Next();
210 Method* method = frame.GetMethod();
211
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700212 DexVerifier::VerifyErrorRefType ref_type =
213 static_cast<DexVerifier::VerifyErrorRefType>(kind >> kVerifyErrorRefTypeShift);
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700214
215 const char* exception_class = "Ljava/lang/VerifyError;";
216 std::string msg;
217
218 switch (static_cast<DexVerifier::VerifyError>(kind & ~(0xff << kVerifyErrorRefTypeShift))) {
219 case DexVerifier::VERIFY_ERROR_NO_CLASS:
220 exception_class = "Ljava/lang/NoClassDefFoundError;";
221 msg = ClassNameFromIndex(method, ref, ref_type, false);
222 break;
223 case DexVerifier::VERIFY_ERROR_NO_FIELD:
224 exception_class = "Ljava/lang/NoSuchFieldError;";
225 msg = FieldNameFromIndex(method, ref, ref_type, false);
226 break;
227 case DexVerifier::VERIFY_ERROR_NO_METHOD:
228 exception_class = "Ljava/lang/NoSuchMethodError;";
229 msg = MethodNameFromIndex(method, ref, ref_type, false);
230 break;
231 case DexVerifier::VERIFY_ERROR_ACCESS_CLASS:
232 exception_class = "Ljava/lang/IllegalAccessError;";
233 msg = ClassNameFromIndex(method, ref, ref_type, true);
234 break;
235 case DexVerifier::VERIFY_ERROR_ACCESS_FIELD:
236 exception_class = "Ljava/lang/IllegalAccessError;";
237 msg = FieldNameFromIndex(method, ref, ref_type, true);
238 break;
239 case DexVerifier::VERIFY_ERROR_ACCESS_METHOD:
240 exception_class = "Ljava/lang/IllegalAccessError;";
241 msg = MethodNameFromIndex(method, ref, ref_type, true);
242 break;
243 case DexVerifier::VERIFY_ERROR_CLASS_CHANGE:
244 exception_class = "Ljava/lang/IncompatibleClassChangeError;";
245 msg = ClassNameFromIndex(method, ref, ref_type, false);
246 break;
247 case DexVerifier::VERIFY_ERROR_INSTANTIATION:
248 exception_class = "Ljava/lang/InstantiationError;";
249 msg = ClassNameFromIndex(method, ref, ref_type, false);
250 break;
251 case DexVerifier::VERIFY_ERROR_GENERIC:
252 // Generic VerifyError; use default exception, no message.
253 break;
254 case DexVerifier::VERIFY_ERROR_NONE:
255 CHECK(false);
256 break;
257 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700258 self->ThrowNewException(exception_class, msg.c_str());
259 self->DeliverException();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700260}
261
262extern "C" void artThrowInternalErrorFromCode(int32_t errnum, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700263 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700264 LOG(WARNING) << "TODO: internal error detail message. errnum=" << errnum;
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700265 thread->ThrowNewExceptionF("Ljava/lang/InternalError;", "errnum=%d", errnum);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700266 thread->DeliverException();
267}
268
269extern "C" void artThrowRuntimeExceptionFromCode(int32_t errnum, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700270 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700271 LOG(WARNING) << "TODO: runtime exception detail message. errnum=" << errnum;
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700272 thread->ThrowNewExceptionF("Ljava/lang/RuntimeException;", "errnum=%d", errnum);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700273 thread->DeliverException();
274}
275
Elliott Hughese1410a22011-10-04 12:10:24 -0700276extern "C" void artThrowNoSuchMethodFromCode(int32_t method_idx, Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700277 FinishCalleeSaveFrameSetup(self, sp, Runtime::kSaveAll);
278 Frame frame = self->GetTopOfStack(); // We need the calling method as context for the method_idx
Elliott Hughese1410a22011-10-04 12:10:24 -0700279 frame.Next();
280 Method* method = frame.GetMethod();
Elliott Hughese1410a22011-10-04 12:10:24 -0700281 self->ThrowNewException("Ljava/lang/NoSuchMethodError;",
282 MethodNameFromIndex(method, method_idx, DexVerifier::VERIFY_ERROR_REF_METHOD, false).c_str());
283 self->DeliverException();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700284}
285
286extern "C" void artThrowNegArraySizeFromCode(int32_t size, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700287 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700288 LOG(WARNING) << "UNTESTED artThrowNegArraySizeFromCode";
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700289 thread->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d", size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700290 thread->DeliverException();
291}
292
Ian Rogersad25ac52011-10-04 19:13:33 -0700293void* UnresolvedDirectMethodTrampolineFromCode(int32_t method_idx, void* sp, Thread* thread,
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700294 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700295 // TODO: this code is specific to ARM
296 // On entry the stack pointed by sp is:
297 // | argN | |
298 // | ... | |
299 // | arg4 | |
300 // | arg3 spill | | Caller's frame
301 // | arg2 spill | |
302 // | arg1 spill | |
303 // | Method* | ---
304 // | LR |
305 // | R3 | arg3
306 // | R2 | arg2
307 // | R1 | arg1
308 // | R0 | <- sp
309 uintptr_t* regs = reinterpret_cast<uintptr_t*>(sp);
310 Method** caller_sp = reinterpret_cast<Method**>(&regs[5]);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700311 uintptr_t caller_pc = regs[4];
Ian Rogersad25ac52011-10-04 19:13:33 -0700312 // Record the last top of the managed stack
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700313 thread->SetTopOfStack(caller_sp, caller_pc);
Ian Rogersad25ac52011-10-04 19:13:33 -0700314 // Start new JNI local reference state
315 JNIEnvExt* env = thread->GetJniEnv();
316 uint32_t saved_local_ref_cookie = env->local_ref_cookie;
317 env->local_ref_cookie = env->locals.GetSegmentState();
318 // Discover shorty (avoid GCs)
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700319 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Ian Rogersad25ac52011-10-04 19:13:33 -0700320 const char* shorty = linker->MethodShorty(method_idx, *caller_sp);
321 size_t shorty_len = strlen(shorty);
322 size_t args_in_regs = shorty_len < 3 ? shorty_len : 3;
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700323 if (type == Runtime::kUnknownMethod) {
324 uint32_t dex_pc = (*caller_sp)->ToDexPC(caller_pc - 2);
325 UNIMPLEMENTED(WARNING) << "Missed argument handlerization in direct method trampoline. "
326 "Need to discover method invoke type at " << PrettyMethod(*caller_sp)
327 << " PC: " << (void*)dex_pc;
328 } else {
329 bool is_static = type == Runtime::kStaticMethod;
330 // Handlerize references in registers
331 int cur_arg = 1; // skip method_idx in R0, first arg is in R1
332 if (!is_static) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700333 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700334 cur_arg++;
Ian Rogersad25ac52011-10-04 19:13:33 -0700335 AddLocalReference<jobject>(env, obj);
336 }
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700337 for(size_t i = 0; i < args_in_regs; i++) {
338 char c = shorty[i + 1]; // offset to skip return value
339 if (c == 'L') {
340 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
341 AddLocalReference<jobject>(env, obj);
342 }
343 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
Ian Rogersad25ac52011-10-04 19:13:33 -0700344 }
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700345 // Handlerize references in out going arguments
346 for(size_t i = 3; i < shorty_len; i++) {
347 char c = shorty[i + 1]; // offset to skip return value
348 if (c == 'L') {
349 Object* obj = reinterpret_cast<Object*>(regs[i + 3]); // skip R0, LR and Method* of caller
350 AddLocalReference<jobject>(env, obj);
351 }
352 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
353 }
Ian Rogersad25ac52011-10-04 19:13:33 -0700354 }
355 // Resolve method filling in dex cache
356 Method* called = linker->ResolveMethod(method_idx, *caller_sp, true);
357 if (!thread->IsExceptionPending()) {
358 // We got this far, ensure that the declaring class is initialized
359 linker->EnsureInitialized(called->GetDeclaringClass(), true);
360 }
361 // Restore JNI env state
362 env->locals.SetSegmentState(env->local_ref_cookie);
363 env->local_ref_cookie = saved_local_ref_cookie;
364
365 void* code;
366 if (thread->IsExceptionPending()) {
367 // Something went wrong, go into deliver exception with the pending exception in r0
368 code = reinterpret_cast<void*>(art_deliver_exception_from_code);
369 regs[0] = reinterpret_cast<uintptr_t>(thread->GetException());
370 thread->ClearException();
371 } else {
372 // Expect class to at least be initializing
373 CHECK(called->GetDeclaringClass()->IsInitializing());
374 // Set up entry into main method
375 regs[0] = reinterpret_cast<uintptr_t>(called);
376 code = const_cast<void*>(called->GetCode());
377 }
378 return code;
379}
380
Shih-wei Liao2d831012011-09-28 22:06:53 -0700381// TODO: placeholder. Helper function to type
382Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
383 /*
384 * Should initialize & fix up method->dex_cache_resolved_types_[].
385 * Returns initialized type. Does not return normally if an exception
386 * is thrown, but instead initiates the catch. Should be similar to
387 * ClassLinker::InitializeStaticStorageFromCode.
388 */
389 UNIMPLEMENTED(FATAL);
390 return NULL;
391}
392
393// TODO: placeholder. Helper function to resolve virtual method
394void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
395 /*
396 * Slow-path handler on invoke virtual method path in which
397 * base method is unresolved at compile-time. Doesn't need to
398 * return anything - just either ensure that
399 * method->dex_cache_resolved_methods_(method_idx) != NULL or
400 * throw and unwind. The caller will restart call sequence
401 * from the beginning.
402 */
403}
404
Ian Rogersce9eca62011-10-07 17:11:03 -0700405Field* FindFieldFromCode(uint32_t field_idx, const Method* referrer, bool is_static) {
406 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
407 Field* f = class_linker->ResolveField(field_idx, referrer, is_static);
408 if (f != NULL) {
409 Class* c = f->GetDeclaringClass();
410 // If the class is already initializing, we must be inside <clinit>, or
411 // we'd still be waiting for the lock.
412 if (c->GetStatus() == Class::kStatusInitializing || class_linker->EnsureInitialized(c, true)) {
413 return f;
414 }
415 }
416 DCHECK(Thread::Current()->IsExceptionPending()); // Throw exception and unwind
417 return NULL;
418}
419
420extern "C" Field* artFindInstanceFieldFromCode(uint32_t field_idx, const Method* referrer,
421 Thread* self, Method** sp) {
422 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
423 return FindFieldFromCode(field_idx, referrer, false);
424}
425
426extern "C" uint32_t artGet32StaticFromCode(uint32_t field_idx, const Method* referrer,
427 Thread* self, Method** sp) {
428 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
429 Field* field = FindFieldFromCode(field_idx, referrer, true);
430 if (field != NULL) {
431 Class* type = field->GetType();
432 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int64_t)) {
433 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
434 "Attempted read of 32-bit primitive on field '%s'",
435 PrettyField(field, true).c_str());
436 } else {
437 return field->Get32(NULL);
438 }
439 }
440 return 0; // Will throw exception by checking with Thread::Current
441}
442
443extern "C" uint64_t artGet64StaticFromCode(uint32_t field_idx, const Method* referrer,
444 Thread* self, Method** sp) {
445 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
446 Field* field = FindFieldFromCode(field_idx, referrer, true);
447 if (field != NULL) {
448 Class* type = field->GetType();
449 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int64_t)) {
450 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
451 "Attempted read of 64-bit primitive on field '%s'",
452 PrettyField(field, true).c_str());
453 } else {
454 return field->Get64(NULL);
455 }
456 }
457 return 0; // Will throw exception by checking with Thread::Current
458}
459
460extern "C" Object* artGetObjStaticFromCode(uint32_t field_idx, const Method* referrer,
461 Thread* self, Method** sp) {
462 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
463 Field* field = FindFieldFromCode(field_idx, referrer, true);
464 if (field != NULL) {
465 Class* type = field->GetType();
466 if (type->IsPrimitive()) {
467 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
468 "Attempted read of reference on primitive field '%s'",
469 PrettyField(field, true).c_str());
470 } else {
471 return field->GetObj(NULL);
472 }
473 }
474 return NULL; // Will throw exception by checking with Thread::Current
475}
476
477extern "C" int artSet32StaticFromCode(uint32_t field_idx, const Method* referrer,
478 uint32_t new_value, Thread* self, Method** sp) {
479 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
480 Field* field = FindFieldFromCode(field_idx, referrer, true);
481 if (field != NULL) {
482 Class* type = field->GetType();
483 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int32_t)) {
484 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
485 "Attempted write of 32-bit primitive to field '%s'",
486 PrettyField(field, true).c_str());
487 } else {
488 field->Set32(NULL, new_value);
489 return 0; // success
490 }
491 }
492 return -1; // failure
493}
494
495extern "C" int artSet64StaticFromCode(uint32_t field_idx, const Method* referrer,
496 uint64_t new_value, Thread* self, Method** sp) {
497 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
498 Field* field = FindFieldFromCode(field_idx, referrer, true);
499 if (field != NULL) {
500 Class* type = field->GetType();
501 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int64_t)) {
502 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
503 "Attempted write of 64-bit primitive to field '%s'",
504 PrettyField(field, true).c_str());
505 } else {
506 field->Set64(NULL, new_value);
507 return 0; // success
508 }
509 }
510 return -1; // failure
511}
512
513extern "C" int artSetObjStaticFromCode(uint32_t field_idx, const Method* referrer,
514 Object* new_value, Thread* self, Method** sp) {
515 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
516 Field* field = FindFieldFromCode(field_idx, referrer, true);
517 if (field != NULL) {
518 Class* type = field->GetType();
519 if (type->IsPrimitive()) {
520 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
521 "Attempted write of reference to primitive field '%s'",
522 PrettyField(field, true).c_str());
523 } else {
524 field->SetObj(NULL, new_value);
525 return 0; // success
526 }
527 }
528 return -1; // failure
529}
530
Shih-wei Liao2d831012011-09-28 22:06:53 -0700531// Given the context of a calling Method, use its DexCache to resolve a type to a Class. If it
532// cannot be resolved, throw an error. If it can, use it to create an instance.
buzbee33a129c2011-10-06 16:53:20 -0700533extern "C" Object* artAllocObjectFromCode(uint32_t type_idx, Method* method, Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700534 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700535 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700536 Runtime* runtime = Runtime::Current();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700537 if (klass == NULL) {
buzbee33a129c2011-10-06 16:53:20 -0700538 klass = runtime->GetClassLinker()->ResolveType(type_idx, method);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700539 if (klass == NULL) {
buzbee33a129c2011-10-06 16:53:20 -0700540 DCHECK(self->IsExceptionPending());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700541 return NULL; // Failure
542 }
543 }
buzbee33a129c2011-10-06 16:53:20 -0700544 if (!runtime->GetClassLinker()->EnsureInitialized(klass, true)) {
545 DCHECK(self->IsExceptionPending());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700546 return NULL; // Failure
547 }
548 return klass->AllocObject();
549}
550
Ian Rogersce9eca62011-10-07 17:11:03 -0700551Array* CheckAndAllocArrayFromCode(uint32_t type_idx, Method* method, int32_t component_count,
552 Thread* self) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700553 if (component_count < 0) {
Ian Rogersce9eca62011-10-07 17:11:03 -0700554 self->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d", component_count);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700555 return NULL; // Failure
556 }
557 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
558 if (klass == NULL) { // Not in dex cache so try to resolve
559 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
560 if (klass == NULL) { // Error
561 DCHECK(Thread::Current()->IsExceptionPending());
562 return NULL; // Failure
563 }
564 }
565 if (klass->IsPrimitive() && !klass->IsPrimitiveInt()) {
566 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700567 Thread::Current()->ThrowNewExceptionF("Ljava/lang/RuntimeException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700568 "Bad filled array request for type %s",
569 PrettyDescriptor(klass->GetDescriptor()).c_str());
570 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700571 Thread::Current()->ThrowNewExceptionF("Ljava/lang/InternalError;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700572 "Found type %s; filled-new-array not implemented for anything but \'int\'",
573 PrettyDescriptor(klass->GetDescriptor()).c_str());
574 }
575 return NULL; // Failure
576 } else {
577 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
578 return Array::Alloc(klass, component_count);
579 }
580}
581
Ian Rogersce9eca62011-10-07 17:11:03 -0700582// Helper function to alloc array for OP_FILLED_NEW_ARRAY
583extern "C" Array* artCheckAndAllocArrayFromCode(uint32_t type_idx, Method* method,
584 int32_t component_count, Thread* self, Method** sp) {
585 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
586 return CheckAndAllocArrayFromCode(type_idx, method, component_count, self);
587}
588
Shih-wei Liao2d831012011-09-28 22:06:53 -0700589// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
590// it cannot be resolved, throw an error. If it can, use it to create an array.
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700591extern "C" Array* artAllocArrayFromCode(uint32_t type_idx, Method* method, int32_t component_count,
592 Thread* self, Method** sp) {
593 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700594 if (component_count < 0) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700595 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700596 component_count);
597 return NULL; // Failure
598 }
599 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
600 if (klass == NULL) { // Not in dex cache so try to resolve
601 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
602 if (klass == NULL) { // Error
603 DCHECK(Thread::Current()->IsExceptionPending());
604 return NULL; // Failure
605 }
606 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
607 }
608 return Array::Alloc(klass, component_count);
609}
610
611// 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 -0700612extern "C" int artCheckCastFromCode(const Class* a, const Class* b, Thread* self, Method** sp) {
613 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700614 DCHECK(a->IsClass()) << PrettyClass(a);
615 DCHECK(b->IsClass()) << PrettyClass(b);
616 if (b->IsAssignableFrom(a)) {
617 return 0; // Success
618 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700619 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassCastException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700620 "%s cannot be cast to %s",
621 PrettyDescriptor(a->GetDescriptor()).c_str(),
622 PrettyDescriptor(b->GetDescriptor()).c_str());
623 return -1; // Failure
624 }
625}
626
627// Tests whether 'element' can be assigned into an array of type 'array_class'.
628// Returns 0 on success and -1 if an exception is pending.
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700629extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class,
630 Thread* self, Method** sp) {
631 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700632 DCHECK(array_class != NULL);
633 // element can't be NULL as we catch this is screened in runtime_support
634 Class* element_class = element->GetClass();
635 Class* component_type = array_class->GetComponentType();
636 if (component_type->IsAssignableFrom(element_class)) {
637 return 0; // Success
638 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700639 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700640 "Cannot store an object of type %s in to an array of type %s",
641 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
642 PrettyDescriptor(array_class->GetDescriptor()).c_str());
643 return -1; // Failure
644 }
645}
646
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700647Class* InitializeStaticStorage(uint32_t type_idx, const Method* referrer, Thread* self) {
648 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
649 Class* klass = class_linker->ResolveType(type_idx, referrer);
650 if (klass == NULL) {
651 CHECK(self->IsExceptionPending());
652 return NULL; // Failure - Indicate to caller to deliver exception
653 }
654 // If we are the <clinit> of this class, just return our storage.
655 //
656 // Do not set the DexCache InitializedStaticStorage, since that implies <clinit> has finished
657 // running.
658 if (klass == referrer->GetDeclaringClass() && referrer->IsClassInitializer()) {
659 return klass;
660 }
661 if (!class_linker->EnsureInitialized(klass, true)) {
662 CHECK(self->IsExceptionPending());
663 return NULL; // Failure - Indicate to caller to deliver exception
664 }
665 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
666 return klass;
Shih-wei Liao2d831012011-09-28 22:06:53 -0700667}
668
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700669extern "C" Class* artInitializeStaticStorageFromCode(uint32_t type_idx, const Method* referrer,
670 Thread* self, Method** sp) {
671 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
672 return InitializeStaticStorage(type_idx, referrer, self);
673}
674
Brian Carlstromaded5f72011-10-07 17:15:04 -0700675String* ResolveStringFromCode(const Method* referrer, uint32_t string_idx) {
676 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
677 return class_linker->ResolveString(string_idx, referrer);
678}
679
680extern "C" String* artResolveStringFromCode(Method* referrer, int32_t string_idx,
681 Thread* self, Method** sp) {
682 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
683 return ResolveStringFromCode(referrer, string_idx);
684}
685
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700686extern "C" int artUnlockObjectFromCode(Object* obj, Thread* self, Method** sp) {
687 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700688 DCHECK(obj != NULL); // Assumed to have been checked before entry
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700689 // MonitorExit may throw exception
690 return obj->MonitorExit(self) ? 0 /* Success */ : -1 /* Failure */;
691}
692
693extern "C" void artLockObjectFromCode(Object* obj, Thread* thread, Method** sp) {
694 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsOnly);
695 DCHECK(obj != NULL); // Assumed to have been checked before entry
696 obj->MonitorEnter(thread); // May block
Shih-wei Liao2d831012011-09-28 22:06:53 -0700697 DCHECK(thread->HoldsLock(obj));
698 // Only possible exception is NPE and is handled before entry
699 DCHECK(!thread->IsExceptionPending());
700}
701
Ian Rogers4a510d82011-10-09 14:30:24 -0700702void CheckSuspendFromCode(Thread* thread) {
703 // Called when thread->suspend_count_ != 0
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700704 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
705}
706
Ian Rogers4a510d82011-10-09 14:30:24 -0700707extern "C" void artTestSuspendFromCode(Thread* thread, Method** sp) {
708 // Called when suspend count check value is 0 and thread->suspend_count_ != 0
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700709 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700710 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
711}
712
713/*
714 * Fill the array with predefined constant values, throwing exceptions if the array is null or
715 * not of sufficient length.
716 *
717 * NOTE: When dealing with a raw dex file, the data to be copied uses
718 * little-endian ordering. Require that oat2dex do any required swapping
719 * so this routine can get by with a memcpy().
720 *
721 * Format of the data:
722 * ushort ident = 0x0300 magic value
723 * ushort width width of each element in the table
724 * uint size number of elements in the table
725 * ubyte data[size*width] table of data values (may contain a single-byte
726 * padding at the end)
727 */
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700728extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table,
729 Thread* self, Method** sp) {
730 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700731 DCHECK_EQ(table[0], 0x0300);
732 if (array == NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700733 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
734 "null array in fill array");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700735 return -1; // Error
736 }
737 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
738 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
739 if (static_cast<int32_t>(size) > array->GetLength()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700740 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
741 "failed array fill. length=%d; index=%d", array->GetLength(), size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700742 return -1; // Error
743 }
744 uint16_t width = table[1];
745 uint32_t size_in_bytes = size * width;
746 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
747 return 0; // Success
748}
749
750// See comments in runtime_support_asm.S
751extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
752 Object* this_object ,
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700753 Thread* thread, Method** sp) {
754 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsAndArgs);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700755 if (this_object == NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700756 thread->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
757 "null receiver during interface dispatch");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700758 return 0;
759 }
760 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700761 Frame frame = thread->GetTopOfStack(); // Compute calling method
762 frame.Next();
763 Method* caller_method = frame.GetMethod();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700764 Method* interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
765 if (interface_method == NULL) {
766 // Could not resolve interface method. Throw error and unwind
767 CHECK(thread->IsExceptionPending());
768 return 0;
769 }
770 Method* method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method);
771 if (method == NULL) {
772 CHECK(thread->IsExceptionPending());
773 return 0;
774 }
775 const void* code = method->GetCode();
776
777 uint32_t method_uint = reinterpret_cast<uint32_t>(method);
778 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
779 uint64_t result = ((code_uint << 32) | method_uint);
780 return result;
781}
782
783/*
784 * Float/double conversion requires clamping to min and max of integer form. If
785 * target doesn't support this normally, use these.
786 */
787int64_t D2L(double d) {
788 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
789 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
790 if (d >= kMaxLong)
791 return (int64_t)0x7fffffffffffffffULL;
792 else if (d <= kMinLong)
793 return (int64_t)0x8000000000000000ULL;
794 else if (d != d) // NaN case
795 return 0;
796 else
797 return (int64_t)d;
798}
799
800int64_t F2L(float f) {
801 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
802 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
803 if (f >= kMaxLong)
804 return (int64_t)0x7fffffffffffffffULL;
805 else if (f <= kMinLong)
806 return (int64_t)0x8000000000000000ULL;
807 else if (f != f) // NaN case
808 return 0;
809 else
810 return (int64_t)f;
811}
812
813} // namespace art