blob: 5550c2f35fc871d59e9801c38ab2830e0d15e79f [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
Ian Rogerscaab8c42011-10-12 12:11:18 -070019#include "dex_cache.h"
Elliott Hughes6c8867d2011-10-03 16:34:05 -070020#include "dex_verifier.h"
Ian Rogerscaab8c42011-10-12 12:11:18 -070021#include "macros.h"
Ian Rogersdfcdf1a2011-10-10 17:50:35 -070022#include "reflection.h"
23#include "ScopedLocalRef.h"
Elliott Hughes6c8867d2011-10-03 16:34:05 -070024
Shih-wei Liao2d831012011-09-28 22:06:53 -070025namespace art {
26
Ian Rogers4f0d07c2011-10-06 23:38:47 -070027// Place a special frame at the TOS that will save the callee saves for the given type
28static void FinishCalleeSaveFrameSetup(Thread* self, Method** sp, Runtime::CalleeSaveType type) {
Ian Rogersce9eca62011-10-07 17:11:03 -070029 // Be aware the store below may well stomp on an incoming argument
Ian Rogers4f0d07c2011-10-06 23:38:47 -070030 *sp = Runtime::Current()->GetCalleeSaveMethod(type);
31 self->SetTopOfStack(sp, 0);
32}
33
Shih-wei Liao2d831012011-09-28 22:06:53 -070034// Temporary debugging hook for compiler.
35extern void DebugMe(Method* method, uint32_t info) {
36 LOG(INFO) << "DebugMe";
37 if (method != NULL) {
38 LOG(INFO) << PrettyMethod(method);
39 }
40 LOG(INFO) << "Info: " << info;
41}
42
Ian Rogerscaab8c42011-10-12 12:11:18 -070043void ObjectInitFromCode(Object* o) {
44 Class* c = o->GetClass();
45 if (UNLIKELY(c->IsFinalizable())) {
46 Heap::AddFinalizerReference(o);
47 }
48 /*
49 * NOTE: once debugger/profiler support is added, we'll need to check
50 * here and branch to actual compiled object.<init> to handle any
51 * breakpoint/logging activites if either is active.
52 */
53}
54
Shih-wei Liao2d831012011-09-28 22:06:53 -070055// Return value helper for jobject return types
56extern Object* DecodeJObjectInThread(Thread* thread, jobject obj) {
Brian Carlstrom6f495f22011-10-10 15:05:03 -070057 if (thread->IsExceptionPending()) {
58 return NULL;
59 }
Shih-wei Liao2d831012011-09-28 22:06:53 -070060 return thread->DecodeJObject(obj);
61}
62
63extern void* FindNativeMethod(Thread* thread) {
64 DCHECK(Thread::Current() == thread);
65
66 Method* method = const_cast<Method*>(thread->GetCurrentMethod());
67 DCHECK(method != NULL);
68
69 // Lookup symbol address for method, on failure we'll return NULL with an
70 // exception set, otherwise we return the address of the method we found.
71 void* native_code = thread->GetJniEnv()->vm->FindCodeForNativeMethod(method);
72 if (native_code == NULL) {
73 DCHECK(thread->IsExceptionPending());
74 return NULL;
75 } else {
76 // Register so that future calls don't come here
77 method->RegisterNative(native_code);
78 return native_code;
79 }
80}
81
82// Called by generated call to throw an exception
83extern "C" void artDeliverExceptionFromCode(Throwable* exception, Thread* thread, Method** sp) {
84 /*
85 * exception may be NULL, in which case this routine should
86 * throw NPE. NOTE: this is a convenience for generated code,
87 * which previously did the null check inline and constructed
88 * and threw a NPE if NULL. This routine responsible for setting
89 * exception_ in thread and delivering the exception.
90 */
Ian Rogers4f0d07c2011-10-06 23:38:47 -070091 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -070092 if (exception == NULL) {
93 thread->ThrowNewException("Ljava/lang/NullPointerException;", "throw with null exception");
94 } else {
95 thread->SetException(exception);
96 }
97 thread->DeliverException();
98}
99
100// Deliver an exception that's pending on thread helping set up a callee save frame on the way
101extern "C" void artDeliverPendingExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700102 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700103 thread->DeliverException();
104}
105
106// Called by generated call to throw a NPE exception
107extern "C" void artThrowNullPointerExceptionFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700108 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700109 thread->ThrowNewException("Ljava/lang/NullPointerException;", NULL);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700110 thread->DeliverException();
111}
112
113// Called by generated call to throw an arithmetic divide by zero exception
114extern "C" void artThrowDivZeroFromCode(Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700115 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700116 thread->ThrowNewException("Ljava/lang/ArithmeticException;", "divide by zero");
117 thread->DeliverException();
118}
119
120// Called by generated call to throw an arithmetic divide by zero exception
121extern "C" void artThrowArrayBoundsFromCode(int index, int limit, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700122 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
123 thread->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
124 "length=%d; index=%d", limit, index);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700125 thread->DeliverException();
126}
127
128// Called by the AbstractMethodError stub (not runtime support)
129extern void ThrowAbstractMethodErrorFromCode(Method* method, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700130 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
131 thread->ThrowNewExceptionF("Ljava/lang/AbstractMethodError;",
132 "abstract method \"%s\"", PrettyMethod(method).c_str());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700133 thread->DeliverException();
134}
135
136extern "C" void artThrowStackOverflowFromCode(Method* method, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700137 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700138 thread->SetStackEndForStackOverflow(); // Allow space on the stack for constructor to execute
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700139 thread->ThrowNewExceptionF("Ljava/lang/StackOverflowError;",
140 "stack size %zdkb; default stack size: %zdkb",
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700141 thread->GetStackSize() / KB, Runtime::Current()->GetDefaultStackSize() / KB);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700142 thread->ResetDefaultStackEnd(); // Return to default stack size
143 thread->DeliverException();
144}
145
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700146static std::string ClassNameFromIndex(Method* method, uint32_t ref,
147 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700148 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
149 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
150
151 uint16_t type_idx = 0;
152 if (ref_type == DexVerifier::VERIFY_ERROR_REF_FIELD) {
153 const DexFile::FieldId& id = dex_file.GetFieldId(ref);
154 type_idx = id.class_idx_;
155 } else if (ref_type == DexVerifier::VERIFY_ERROR_REF_METHOD) {
156 const DexFile::MethodId& id = dex_file.GetMethodId(ref);
157 type_idx = id.class_idx_;
158 } else if (ref_type == DexVerifier::VERIFY_ERROR_REF_CLASS) {
159 type_idx = ref;
160 } else {
161 CHECK(false) << static_cast<int>(ref_type);
162 }
163
164 std::string class_name(PrettyDescriptor(dex_file.dexStringByTypeIdx(type_idx)));
165 if (!access) {
166 return class_name;
167 }
168
169 std::string result;
170 result += "tried to access class ";
171 result += class_name;
172 result += " from class ";
173 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
174 return result;
175}
176
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700177static std::string FieldNameFromIndex(const Method* method, uint32_t ref,
178 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700179 CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(DexVerifier::VERIFY_ERROR_REF_FIELD));
180
181 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
182 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
183
184 const DexFile::FieldId& id = dex_file.GetFieldId(ref);
Brian Carlstrom03a20ba2011-10-13 10:24:13 -0700185 std::string class_name(PrettyDescriptor(dex_file.GetFieldClassDescriptor(id)));
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700186 const char* field_name = dex_file.dexStringById(id.name_idx_);
187 if (!access) {
188 return class_name + "." + field_name;
189 }
190
191 std::string result;
192 result += "tried to access field ";
193 result += class_name + "." + field_name;
194 result += " from class ";
195 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
196 return result;
197}
198
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700199static std::string MethodNameFromIndex(const Method* method, uint32_t ref,
200 DexVerifier::VerifyErrorRefType ref_type, bool access) {
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700201 CHECK_EQ(static_cast<int>(ref_type), static_cast<int>(DexVerifier::VERIFY_ERROR_REF_METHOD));
202
203 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
204 const DexFile& dex_file = class_linker->FindDexFile(method->GetDeclaringClass()->GetDexCache());
205
206 const DexFile::MethodId& id = dex_file.GetMethodId(ref);
Brian Carlstrom03a20ba2011-10-13 10:24:13 -0700207 std::string class_name(PrettyDescriptor(dex_file.GetMethodClassDescriptor(id)));
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700208 const char* method_name = dex_file.dexStringById(id.name_idx_);
209 if (!access) {
210 return class_name + "." + method_name;
211 }
212
213 std::string result;
214 result += "tried to access method ";
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700215 result += class_name + "." + method_name + ":" +
216 dex_file.CreateMethodDescriptor(id.proto_idx_, NULL);
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700217 result += " from class ";
218 result += PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor());
219 return result;
220}
221
222extern "C" void artThrowVerificationErrorFromCode(int32_t kind, int32_t ref, Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700223 FinishCalleeSaveFrameSetup(self, sp, Runtime::kSaveAll);
224 Frame frame = self->GetTopOfStack(); // We need the calling method as context to interpret 'ref'
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700225 frame.Next();
226 Method* method = frame.GetMethod();
227
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700228 DexVerifier::VerifyErrorRefType ref_type =
229 static_cast<DexVerifier::VerifyErrorRefType>(kind >> kVerifyErrorRefTypeShift);
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700230
231 const char* exception_class = "Ljava/lang/VerifyError;";
232 std::string msg;
233
234 switch (static_cast<DexVerifier::VerifyError>(kind & ~(0xff << kVerifyErrorRefTypeShift))) {
235 case DexVerifier::VERIFY_ERROR_NO_CLASS:
236 exception_class = "Ljava/lang/NoClassDefFoundError;";
237 msg = ClassNameFromIndex(method, ref, ref_type, false);
238 break;
239 case DexVerifier::VERIFY_ERROR_NO_FIELD:
240 exception_class = "Ljava/lang/NoSuchFieldError;";
241 msg = FieldNameFromIndex(method, ref, ref_type, false);
242 break;
243 case DexVerifier::VERIFY_ERROR_NO_METHOD:
244 exception_class = "Ljava/lang/NoSuchMethodError;";
245 msg = MethodNameFromIndex(method, ref, ref_type, false);
246 break;
247 case DexVerifier::VERIFY_ERROR_ACCESS_CLASS:
248 exception_class = "Ljava/lang/IllegalAccessError;";
249 msg = ClassNameFromIndex(method, ref, ref_type, true);
250 break;
251 case DexVerifier::VERIFY_ERROR_ACCESS_FIELD:
252 exception_class = "Ljava/lang/IllegalAccessError;";
253 msg = FieldNameFromIndex(method, ref, ref_type, true);
254 break;
255 case DexVerifier::VERIFY_ERROR_ACCESS_METHOD:
256 exception_class = "Ljava/lang/IllegalAccessError;";
257 msg = MethodNameFromIndex(method, ref, ref_type, true);
258 break;
259 case DexVerifier::VERIFY_ERROR_CLASS_CHANGE:
260 exception_class = "Ljava/lang/IncompatibleClassChangeError;";
261 msg = ClassNameFromIndex(method, ref, ref_type, false);
262 break;
263 case DexVerifier::VERIFY_ERROR_INSTANTIATION:
264 exception_class = "Ljava/lang/InstantiationError;";
265 msg = ClassNameFromIndex(method, ref, ref_type, false);
266 break;
267 case DexVerifier::VERIFY_ERROR_GENERIC:
268 // Generic VerifyError; use default exception, no message.
269 break;
270 case DexVerifier::VERIFY_ERROR_NONE:
271 CHECK(false);
272 break;
273 }
Elliott Hughes6c8867d2011-10-03 16:34:05 -0700274 self->ThrowNewException(exception_class, msg.c_str());
275 self->DeliverException();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700276}
277
278extern "C" void artThrowInternalErrorFromCode(int32_t errnum, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700279 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700280 LOG(WARNING) << "TODO: internal error detail message. errnum=" << errnum;
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700281 thread->ThrowNewExceptionF("Ljava/lang/InternalError;", "errnum=%d", errnum);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700282 thread->DeliverException();
283}
284
285extern "C" void artThrowRuntimeExceptionFromCode(int32_t errnum, Thread* thread, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700286 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700287 LOG(WARNING) << "TODO: runtime exception detail message. errnum=" << errnum;
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700288 thread->ThrowNewExceptionF("Ljava/lang/RuntimeException;", "errnum=%d", errnum);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700289 thread->DeliverException();
290}
291
Elliott Hughese1410a22011-10-04 12:10:24 -0700292extern "C" void artThrowNoSuchMethodFromCode(int32_t method_idx, Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700293 FinishCalleeSaveFrameSetup(self, sp, Runtime::kSaveAll);
294 Frame frame = self->GetTopOfStack(); // We need the calling method as context for the method_idx
Elliott Hughese1410a22011-10-04 12:10:24 -0700295 frame.Next();
296 Method* method = frame.GetMethod();
Elliott Hughese1410a22011-10-04 12:10:24 -0700297 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) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700303 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kSaveAll);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700304 LOG(WARNING) << "UNTESTED artThrowNegArraySizeFromCode";
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700305 thread->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d", size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700306 thread->DeliverException();
307}
308
Ian Rogersad25ac52011-10-04 19:13:33 -0700309void* UnresolvedDirectMethodTrampolineFromCode(int32_t method_idx, void* sp, Thread* thread,
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700310 Runtime::TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700311 // TODO: this code is specific to ARM
312 // On entry the stack pointed by sp is:
313 // | argN | |
314 // | ... | |
315 // | arg4 | |
316 // | arg3 spill | | Caller's frame
317 // | arg2 spill | |
318 // | arg1 spill | |
319 // | Method* | ---
320 // | LR |
321 // | R3 | arg3
322 // | R2 | arg2
323 // | R1 | arg1
324 // | R0 | <- sp
325 uintptr_t* regs = reinterpret_cast<uintptr_t*>(sp);
326 Method** caller_sp = reinterpret_cast<Method**>(&regs[5]);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700327 uintptr_t caller_pc = regs[4];
Ian Rogersad25ac52011-10-04 19:13:33 -0700328 // Record the last top of the managed stack
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700329 thread->SetTopOfStack(caller_sp, caller_pc);
Ian Rogersad25ac52011-10-04 19:13:33 -0700330 // Start new JNI local reference state
331 JNIEnvExt* env = thread->GetJniEnv();
Ian Rogersdfcdf1a2011-10-10 17:50:35 -0700332 ScopedJniEnvLocalRefState env_state(env);
Ian Rogersad25ac52011-10-04 19:13:33 -0700333 // Discover shorty (avoid GCs)
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700334 ClassLinker* linker = Runtime::Current()->GetClassLinker();
Ian Rogersad25ac52011-10-04 19:13:33 -0700335 const char* shorty = linker->MethodShorty(method_idx, *caller_sp);
336 size_t shorty_len = strlen(shorty);
Ian Rogers14b1b242011-10-11 18:54:34 -0700337 size_t args_in_regs = 0;
338 for (size_t i = 1; i < shorty_len; i++) {
339 char c = shorty[i];
340 args_in_regs = args_in_regs + (c == 'J' || c == 'D' ? 2 : 1);
341 if (args_in_regs > 3) {
342 args_in_regs = 3;
343 break;
344 }
345 }
Ian Rogersea2a11d2011-10-11 16:48:51 -0700346 bool is_static;
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700347 if (type == Runtime::kUnknownMethod) {
Ian Rogersea2a11d2011-10-11 16:48:51 -0700348 Method* caller = *caller_sp;
Ian Rogersdf9a7822011-10-11 16:53:22 -0700349 // less two as return address may span into next dex instruction
350 uint32_t dex_pc = caller->ToDexPC(caller_pc - 2);
Ian Rogersea2a11d2011-10-11 16:48:51 -0700351 const DexFile& dex_file = Runtime::Current()->GetClassLinker()
352 ->FindDexFile(caller->GetDeclaringClass()->GetDexCache());
353 const DexFile::CodeItem* code = dex_file.GetCodeItem(caller->GetCodeItemOffset());
354 CHECK_LT(dex_pc, code->insns_size_);
355 const Instruction* instr = Instruction::At(reinterpret_cast<const byte*>(&code->insns_[dex_pc]));
356 Instruction::Code instr_code = instr->Opcode();
357 is_static = (instr_code == Instruction::INVOKE_STATIC) ||
358 (instr_code == Instruction::INVOKE_STATIC_RANGE);
359 DCHECK(is_static || (instr_code == Instruction::INVOKE_DIRECT) ||
360 (instr_code == Instruction::INVOKE_DIRECT_RANGE));
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700361 } else {
Ian Rogersea2a11d2011-10-11 16:48:51 -0700362 is_static = type == Runtime::kStaticMethod;
363 }
Ian Rogerscaab8c42011-10-12 12:11:18 -0700364 // Place into local references incoming arguments from the caller's register arguments
Ian Rogers14b1b242011-10-11 18:54:34 -0700365 size_t cur_arg = 1; // skip method_idx in R0, first arg is in R1
Ian Rogersea2a11d2011-10-11 16:48:51 -0700366 if (!is_static) {
367 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
368 cur_arg++;
Ian Rogers14b1b242011-10-11 18:54:34 -0700369 if (args_in_regs < 3) {
370 // If we thought we had fewer than 3 arguments in registers, account for the receiver
371 args_in_regs++;
372 }
Ian Rogersea2a11d2011-10-11 16:48:51 -0700373 AddLocalReference<jobject>(env, obj);
374 }
Ian Rogers14b1b242011-10-11 18:54:34 -0700375 size_t shorty_index = 1; // skip return value
376 // Iterate while arguments and arguments in registers (less 1 from cur_arg which is offset to skip
377 // R0)
378 while ((cur_arg - 1) < args_in_regs && shorty_index < shorty_len) {
379 char c = shorty[shorty_index];
380 shorty_index++;
Ian Rogersea2a11d2011-10-11 16:48:51 -0700381 if (c == 'L') {
Ian Rogersad25ac52011-10-04 19:13:33 -0700382 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
383 AddLocalReference<jobject>(env, obj);
384 }
Ian Rogersea2a11d2011-10-11 16:48:51 -0700385 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
386 }
Ian Rogerscaab8c42011-10-12 12:11:18 -0700387 // Place into local references incoming arguments from the caller's stack arguments
Ian Rogers14b1b242011-10-11 18:54:34 -0700388 cur_arg += 5; // skip LR, Method* and spills for R1 to R3
389 while (shorty_index < shorty_len) {
390 char c = shorty[shorty_index];
391 shorty_index++;
Ian Rogersea2a11d2011-10-11 16:48:51 -0700392 if (c == 'L') {
Ian Rogers14b1b242011-10-11 18:54:34 -0700393 Object* obj = reinterpret_cast<Object*>(regs[cur_arg]);
Ian Rogersea2a11d2011-10-11 16:48:51 -0700394 AddLocalReference<jobject>(env, obj);
Ian Rogersad25ac52011-10-04 19:13:33 -0700395 }
Ian Rogersea2a11d2011-10-11 16:48:51 -0700396 cur_arg = cur_arg + (c == 'J' || c == 'D' ? 2 : 1);
Ian Rogersad25ac52011-10-04 19:13:33 -0700397 }
398 // Resolve method filling in dex cache
399 Method* called = linker->ResolveMethod(method_idx, *caller_sp, true);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700400 if (LIKELY(!thread->IsExceptionPending())) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700401 // We got this far, ensure that the declaring class is initialized
402 linker->EnsureInitialized(called->GetDeclaringClass(), true);
403 }
Ian Rogersad25ac52011-10-04 19:13:33 -0700404 void* code;
Ian Rogerscaab8c42011-10-12 12:11:18 -0700405 if (UNLIKELY(thread->IsExceptionPending())) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700406 // Something went wrong, go into deliver exception with the pending exception in r0
407 code = reinterpret_cast<void*>(art_deliver_exception_from_code);
408 regs[0] = reinterpret_cast<uintptr_t>(thread->GetException());
409 thread->ClearException();
410 } else {
411 // Expect class to at least be initializing
412 CHECK(called->GetDeclaringClass()->IsInitializing());
413 // Set up entry into main method
414 regs[0] = reinterpret_cast<uintptr_t>(called);
415 code = const_cast<void*>(called->GetCode());
416 }
417 return code;
418}
419
Shih-wei Liao2d831012011-09-28 22:06:53 -0700420// TODO: placeholder. Helper function to type
421Class* InitializeTypeFromCode(uint32_t type_idx, Method* method) {
422 /*
423 * Should initialize & fix up method->dex_cache_resolved_types_[].
424 * Returns initialized type. Does not return normally if an exception
425 * is thrown, but instead initiates the catch. Should be similar to
426 * ClassLinker::InitializeStaticStorageFromCode.
427 */
428 UNIMPLEMENTED(FATAL);
429 return NULL;
430}
431
432// TODO: placeholder. Helper function to resolve virtual method
433void ResolveMethodFromCode(Method* method, uint32_t method_idx) {
434 /*
435 * Slow-path handler on invoke virtual method path in which
436 * base method is unresolved at compile-time. Doesn't need to
437 * return anything - just either ensure that
438 * method->dex_cache_resolved_methods_(method_idx) != NULL or
439 * throw and unwind. The caller will restart call sequence
440 * from the beginning.
441 */
442}
443
Ian Rogerscaab8c42011-10-12 12:11:18 -0700444// Fast path field resolution that can't throw exceptions
445static Field* FindFieldFast(uint32_t field_idx, const Method* referrer) {
446 Field* resolved_field = referrer->GetDexCacheResolvedFields()->Get(field_idx);
447 if (UNLIKELY(resolved_field == NULL)) {
448 return NULL;
449 }
450 Class* fields_class = resolved_field->GetDeclaringClass();
451 // Check class is initilaized or initializing
452 if (UNLIKELY(!fields_class->IsInitializing())) {
453 return NULL;
454 }
455 return resolved_field;
456}
457
458// Slow path field resolution and declaring class initialization
Ian Rogersce9eca62011-10-07 17:11:03 -0700459Field* FindFieldFromCode(uint32_t field_idx, const Method* referrer, bool is_static) {
460 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogerscaab8c42011-10-12 12:11:18 -0700461 Field* resolved_field = class_linker->ResolveField(field_idx, referrer, is_static);
462 if (LIKELY(resolved_field != NULL)) {
463 Class* fields_class = resolved_field->GetDeclaringClass();
Ian Rogersce9eca62011-10-07 17:11:03 -0700464 // If the class is already initializing, we must be inside <clinit>, or
465 // we'd still be waiting for the lock.
Ian Rogerscaab8c42011-10-12 12:11:18 -0700466 if (fields_class->IsInitializing()) {
467 return resolved_field;
468 }
469 if(Runtime::Current()->GetClassLinker()->EnsureInitialized(fields_class, true)) {
470 return resolved_field;
Ian Rogersce9eca62011-10-07 17:11:03 -0700471 }
472 }
473 DCHECK(Thread::Current()->IsExceptionPending()); // Throw exception and unwind
474 return NULL;
475}
476
477extern "C" Field* artFindInstanceFieldFromCode(uint32_t field_idx, const Method* referrer,
478 Thread* self, Method** sp) {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700479 Field* resolved_field = FindFieldFast(field_idx, referrer);
480 if (UNLIKELY(resolved_field == NULL)) {
481 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
482 resolved_field = FindFieldFromCode(field_idx, referrer, false);
483 }
484 return resolved_field;
Ian Rogersce9eca62011-10-07 17:11:03 -0700485}
486
487extern "C" uint32_t artGet32StaticFromCode(uint32_t field_idx, const Method* referrer,
488 Thread* self, Method** sp) {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700489 Field* field = FindFieldFast(field_idx, referrer);
490 if (LIKELY(field != NULL)) {
491 Class* type = field->GetType();
492 if (LIKELY(type->IsPrimitive() && type->PrimitiveSize() == sizeof(int32_t))) {
493 return field->Get32(NULL);
494 }
495 }
Ian Rogersce9eca62011-10-07 17:11:03 -0700496 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700497 field = FindFieldFromCode(field_idx, referrer, true);
Ian Rogersce9eca62011-10-07 17:11:03 -0700498 if (field != NULL) {
499 Class* type = field->GetType();
Ian Rogerscaab8c42011-10-12 12:11:18 -0700500 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int32_t)) {
Ian Rogersce9eca62011-10-07 17:11:03 -0700501 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
502 "Attempted read of 32-bit primitive on field '%s'",
503 PrettyField(field, true).c_str());
504 } else {
505 return field->Get32(NULL);
506 }
507 }
508 return 0; // Will throw exception by checking with Thread::Current
509}
510
511extern "C" uint64_t artGet64StaticFromCode(uint32_t field_idx, const Method* referrer,
512 Thread* self, Method** sp) {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700513 Field* field = FindFieldFast(field_idx, referrer);
514 if (LIKELY(field != NULL)) {
515 Class* type = field->GetType();
516 if (LIKELY(type->IsPrimitive() && type->PrimitiveSize() == sizeof(int64_t))) {
517 return field->Get64(NULL);
518 }
519 }
Ian Rogersce9eca62011-10-07 17:11:03 -0700520 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700521 field = FindFieldFromCode(field_idx, referrer, true);
Ian Rogersce9eca62011-10-07 17:11:03 -0700522 if (field != NULL) {
523 Class* type = field->GetType();
524 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int64_t)) {
525 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
526 "Attempted read of 64-bit primitive on field '%s'",
527 PrettyField(field, true).c_str());
528 } else {
529 return field->Get64(NULL);
530 }
531 }
532 return 0; // Will throw exception by checking with Thread::Current
533}
534
535extern "C" Object* artGetObjStaticFromCode(uint32_t field_idx, const Method* referrer,
536 Thread* self, Method** sp) {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700537 Field* field = FindFieldFast(field_idx, referrer);
538 if (LIKELY(field != NULL)) {
539 Class* type = field->GetType();
540 if (LIKELY(!type->IsPrimitive())) {
541 return field->GetObj(NULL);
542 }
543 }
Ian Rogersce9eca62011-10-07 17:11:03 -0700544 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700545 field = FindFieldFromCode(field_idx, referrer, true);
Ian Rogersce9eca62011-10-07 17:11:03 -0700546 if (field != NULL) {
547 Class* type = field->GetType();
548 if (type->IsPrimitive()) {
549 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
550 "Attempted read of reference on primitive field '%s'",
551 PrettyField(field, true).c_str());
552 } else {
553 return field->GetObj(NULL);
554 }
555 }
556 return NULL; // Will throw exception by checking with Thread::Current
557}
558
559extern "C" int artSet32StaticFromCode(uint32_t field_idx, const Method* referrer,
560 uint32_t new_value, Thread* self, Method** sp) {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700561 Field* field = FindFieldFast(field_idx, referrer);
562 if (LIKELY(field != NULL)) {
563 Class* type = field->GetType();
564 if (LIKELY(type->IsPrimitive() && type->PrimitiveSize() == sizeof(int32_t))) {
565 field->Set32(NULL, new_value);
566 return 0; // success
567 }
568 }
Ian Rogersce9eca62011-10-07 17:11:03 -0700569 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700570 field = FindFieldFromCode(field_idx, referrer, true);
Ian Rogersce9eca62011-10-07 17:11:03 -0700571 if (field != NULL) {
572 Class* type = field->GetType();
573 if (!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int32_t)) {
574 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
575 "Attempted write of 32-bit primitive to field '%s'",
576 PrettyField(field, true).c_str());
577 } else {
578 field->Set32(NULL, new_value);
579 return 0; // success
580 }
581 }
582 return -1; // failure
583}
584
585extern "C" int artSet64StaticFromCode(uint32_t field_idx, const Method* referrer,
586 uint64_t new_value, Thread* self, Method** sp) {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700587 Field* field = FindFieldFast(field_idx, referrer);
588 if (LIKELY(field != NULL)) {
Ian Rogersce9eca62011-10-07 17:11:03 -0700589 Class* type = field->GetType();
Ian Rogerscaab8c42011-10-12 12:11:18 -0700590 if (LIKELY(type->IsPrimitive() && type->PrimitiveSize() == sizeof(int64_t))) {
591 field->Set64(NULL, new_value);
592 return 0; // success
593 }
594 }
595 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
596 field = FindFieldFromCode(field_idx, referrer, true);
597 if (LIKELY(field != NULL)) {
598 Class* type = field->GetType();
599 if (UNLIKELY(!type->IsPrimitive() || type->PrimitiveSize() != sizeof(int64_t))) {
Ian Rogersce9eca62011-10-07 17:11:03 -0700600 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
601 "Attempted write of 64-bit primitive to field '%s'",
602 PrettyField(field, true).c_str());
603 } else {
604 field->Set64(NULL, new_value);
605 return 0; // success
606 }
607 }
608 return -1; // failure
609}
610
611extern "C" int artSetObjStaticFromCode(uint32_t field_idx, const Method* referrer,
612 Object* new_value, Thread* self, Method** sp) {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700613 Field* field = FindFieldFast(field_idx, referrer);
614 if (LIKELY(field != NULL)) {
615 Class* type = field->GetType();
616 if (LIKELY(!type->IsPrimitive())) {
617 field->SetObj(NULL, new_value);
618 return 0; // success
619 }
620 }
Ian Rogersce9eca62011-10-07 17:11:03 -0700621 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700622 field = FindFieldFromCode(field_idx, referrer, true);
Ian Rogersce9eca62011-10-07 17:11:03 -0700623 if (field != NULL) {
624 Class* type = field->GetType();
625 if (type->IsPrimitive()) {
626 self->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;",
627 "Attempted write of reference to primitive field '%s'",
628 PrettyField(field, true).c_str());
629 } else {
630 field->SetObj(NULL, new_value);
631 return 0; // success
632 }
633 }
634 return -1; // failure
635}
636
Shih-wei Liao2d831012011-09-28 22:06:53 -0700637// Given the context of a calling Method, use its DexCache to resolve a type to a Class. If it
638// cannot be resolved, throw an error. If it can, use it to create an instance.
Ian Rogerscaab8c42011-10-12 12:11:18 -0700639extern "C" Object* artAllocObjectFromCode(uint32_t type_idx, Method* method,
640 Thread* self, Method** sp) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700641 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700642 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700643 Runtime* runtime = Runtime::Current();
Ian Rogerscaab8c42011-10-12 12:11:18 -0700644 if (UNLIKELY(klass == NULL)) {
buzbee33a129c2011-10-06 16:53:20 -0700645 klass = runtime->GetClassLinker()->ResolveType(type_idx, method);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700646 if (klass == NULL) {
buzbee33a129c2011-10-06 16:53:20 -0700647 DCHECK(self->IsExceptionPending());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700648 return NULL; // Failure
649 }
650 }
buzbee33a129c2011-10-06 16:53:20 -0700651 if (!runtime->GetClassLinker()->EnsureInitialized(klass, true)) {
652 DCHECK(self->IsExceptionPending());
Shih-wei Liao2d831012011-09-28 22:06:53 -0700653 return NULL; // Failure
654 }
655 return klass->AllocObject();
656}
657
Ian Rogersce9eca62011-10-07 17:11:03 -0700658Array* CheckAndAllocArrayFromCode(uint32_t type_idx, Method* method, int32_t component_count,
659 Thread* self) {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700660 if (UNLIKELY(component_count < 0)) {
Ian Rogersce9eca62011-10-07 17:11:03 -0700661 self->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d", component_count);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700662 return NULL; // Failure
663 }
664 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700665 if (UNLIKELY(klass == NULL)) { // Not in dex cache so try to resolve
Shih-wei Liao2d831012011-09-28 22:06:53 -0700666 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
667 if (klass == NULL) { // Error
668 DCHECK(Thread::Current()->IsExceptionPending());
669 return NULL; // Failure
670 }
671 }
Ian Rogerscaab8c42011-10-12 12:11:18 -0700672 if (UNLIKELY(klass->IsPrimitive() && !klass->IsPrimitiveInt())) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700673 if (klass->IsPrimitiveLong() || klass->IsPrimitiveDouble()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700674 Thread::Current()->ThrowNewExceptionF("Ljava/lang/RuntimeException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700675 "Bad filled array request for type %s",
676 PrettyDescriptor(klass->GetDescriptor()).c_str());
677 } else {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700678 Thread::Current()->ThrowNewExceptionF("Ljava/lang/InternalError;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700679 "Found type %s; filled-new-array not implemented for anything but \'int\'",
680 PrettyDescriptor(klass->GetDescriptor()).c_str());
681 }
682 return NULL; // Failure
683 } else {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700684 DCHECK(klass->IsArrayClass()) << PrettyClass(klass);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700685 return Array::Alloc(klass, component_count);
686 }
687}
688
Ian Rogersce9eca62011-10-07 17:11:03 -0700689// Helper function to alloc array for OP_FILLED_NEW_ARRAY
690extern "C" Array* artCheckAndAllocArrayFromCode(uint32_t type_idx, Method* method,
691 int32_t component_count, Thread* self, Method** sp) {
692 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
693 return CheckAndAllocArrayFromCode(type_idx, method, component_count, self);
694}
695
Shih-wei Liao2d831012011-09-28 22:06:53 -0700696// Given the context of a calling Method, use its DexCache to resolve a type to an array Class. If
697// it cannot be resolved, throw an error. If it can, use it to create an array.
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700698extern "C" Array* artAllocArrayFromCode(uint32_t type_idx, Method* method, int32_t component_count,
699 Thread* self, Method** sp) {
700 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700701 if (UNLIKELY(component_count < 0)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700702 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NegativeArraySizeException;", "%d",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700703 component_count);
704 return NULL; // Failure
705 }
706 Class* klass = method->GetDexCacheResolvedTypes()->Get(type_idx);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700707 if (UNLIKELY(klass == NULL)) { // Not in dex cache so try to resolve
Shih-wei Liao2d831012011-09-28 22:06:53 -0700708 klass = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, method);
709 if (klass == NULL) { // Error
710 DCHECK(Thread::Current()->IsExceptionPending());
711 return NULL; // Failure
712 }
713 CHECK(klass->IsArrayClass()) << PrettyClass(klass);
714 }
715 return Array::Alloc(klass, component_count);
716}
717
Ian Rogerscaab8c42011-10-12 12:11:18 -0700718// Assignable test for code, won't throw. Null and equality tests already performed
719uint32_t IsAssignableFromCode(const Class* klass, const Class* ref_class) {
720 DCHECK(klass != NULL);
721 DCHECK(ref_class != NULL);
722 return klass->IsAssignableFrom(ref_class) ? 1 : 0;
723}
724
Shih-wei Liao2d831012011-09-28 22:06:53 -0700725// 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 -0700726extern "C" int artCheckCastFromCode(const Class* a, const Class* b, Thread* self, Method** sp) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700727 DCHECK(a->IsClass()) << PrettyClass(a);
728 DCHECK(b->IsClass()) << PrettyClass(b);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700729 if (LIKELY(b->IsAssignableFrom(a))) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700730 return 0; // Success
731 } else {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700732 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700733 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassCastException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700734 "%s cannot be cast to %s",
735 PrettyDescriptor(a->GetDescriptor()).c_str(),
736 PrettyDescriptor(b->GetDescriptor()).c_str());
737 return -1; // Failure
738 }
739}
740
741// Tests whether 'element' can be assigned into an array of type 'array_class'.
742// Returns 0 on success and -1 if an exception is pending.
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700743extern "C" int artCanPutArrayElementFromCode(const Object* element, const Class* array_class,
744 Thread* self, Method** sp) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700745 DCHECK(array_class != NULL);
746 // element can't be NULL as we catch this is screened in runtime_support
747 Class* element_class = element->GetClass();
748 Class* component_type = array_class->GetComponentType();
Ian Rogerscaab8c42011-10-12 12:11:18 -0700749 if (LIKELY(component_type->IsAssignableFrom(element_class))) {
Shih-wei Liao2d831012011-09-28 22:06:53 -0700750 return 0; // Success
751 } else {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700752 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700753 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayStoreException;",
Shih-wei Liao2d831012011-09-28 22:06:53 -0700754 "Cannot store an object of type %s in to an array of type %s",
755 PrettyDescriptor(element_class->GetDescriptor()).c_str(),
756 PrettyDescriptor(array_class->GetDescriptor()).c_str());
757 return -1; // Failure
758 }
759}
760
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700761Class* InitializeStaticStorage(uint32_t type_idx, const Method* referrer, Thread* self) {
762 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
763 Class* klass = class_linker->ResolveType(type_idx, referrer);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700764 if (UNLIKELY(klass == NULL)) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700765 CHECK(self->IsExceptionPending());
766 return NULL; // Failure - Indicate to caller to deliver exception
767 }
768 // If we are the <clinit> of this class, just return our storage.
769 //
770 // Do not set the DexCache InitializedStaticStorage, since that implies <clinit> has finished
771 // running.
772 if (klass == referrer->GetDeclaringClass() && referrer->IsClassInitializer()) {
773 return klass;
774 }
775 if (!class_linker->EnsureInitialized(klass, true)) {
776 CHECK(self->IsExceptionPending());
777 return NULL; // Failure - Indicate to caller to deliver exception
778 }
779 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
780 return klass;
Shih-wei Liao2d831012011-09-28 22:06:53 -0700781}
782
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700783extern "C" Class* artInitializeStaticStorageFromCode(uint32_t type_idx, const Method* referrer,
784 Thread* self, Method** sp) {
785 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
786 return InitializeStaticStorage(type_idx, referrer, self);
787}
788
Brian Carlstromaded5f72011-10-07 17:15:04 -0700789String* ResolveStringFromCode(const Method* referrer, uint32_t string_idx) {
790 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
791 return class_linker->ResolveString(string_idx, referrer);
792}
793
794extern "C" String* artResolveStringFromCode(Method* referrer, int32_t string_idx,
795 Thread* self, Method** sp) {
796 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
797 return ResolveStringFromCode(referrer, string_idx);
798}
799
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700800extern "C" int artUnlockObjectFromCode(Object* obj, Thread* self, Method** sp) {
801 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700802 DCHECK(obj != NULL); // Assumed to have been checked before entry
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700803 // MonitorExit may throw exception
804 return obj->MonitorExit(self) ? 0 /* Success */ : -1 /* Failure */;
805}
806
807extern "C" void artLockObjectFromCode(Object* obj, Thread* thread, Method** sp) {
808 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsOnly);
809 DCHECK(obj != NULL); // Assumed to have been checked before entry
810 obj->MonitorEnter(thread); // May block
Shih-wei Liao2d831012011-09-28 22:06:53 -0700811 DCHECK(thread->HoldsLock(obj));
812 // Only possible exception is NPE and is handled before entry
813 DCHECK(!thread->IsExceptionPending());
814}
815
Ian Rogers4a510d82011-10-09 14:30:24 -0700816void CheckSuspendFromCode(Thread* thread) {
817 // Called when thread->suspend_count_ != 0
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700818 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
819}
820
Ian Rogers4a510d82011-10-09 14:30:24 -0700821extern "C" void artTestSuspendFromCode(Thread* thread, Method** sp) {
822 // Called when suspend count check value is 0 and thread->suspend_count_ != 0
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700823 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700824 Runtime::Current()->GetThreadList()->FullSuspendCheck(thread);
825}
826
827/*
828 * Fill the array with predefined constant values, throwing exceptions if the array is null or
829 * not of sufficient length.
830 *
831 * NOTE: When dealing with a raw dex file, the data to be copied uses
832 * little-endian ordering. Require that oat2dex do any required swapping
833 * so this routine can get by with a memcpy().
834 *
835 * Format of the data:
836 * ushort ident = 0x0300 magic value
837 * ushort width width of each element in the table
838 * uint size number of elements in the table
839 * ubyte data[size*width] table of data values (may contain a single-byte
840 * padding at the end)
841 */
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700842extern "C" int artHandleFillArrayDataFromCode(Array* array, const uint16_t* table,
843 Thread* self, Method** sp) {
844 FinishCalleeSaveFrameSetup(self, sp, Runtime::kRefsOnly);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700845 DCHECK_EQ(table[0], 0x0300);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700846 if (UNLIKELY(array == NULL)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700847 Thread::Current()->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
848 "null array in fill array");
Shih-wei Liao2d831012011-09-28 22:06:53 -0700849 return -1; // Error
850 }
851 DCHECK(array->IsArrayInstance() && !array->IsObjectArray());
852 uint32_t size = (uint32_t)table[2] | (((uint32_t)table[3]) << 16);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700853 if (UNLIKELY(static_cast<int32_t>(size) > array->GetLength())) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700854 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
855 "failed array fill. length=%d; index=%d", array->GetLength(), size);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700856 return -1; // Error
857 }
858 uint16_t width = table[1];
859 uint32_t size_in_bytes = size * width;
860 memcpy((char*)array + Array::DataOffset().Int32Value(), (char*)&table[4], size_in_bytes);
861 return 0; // Success
862}
863
864// See comments in runtime_support_asm.S
865extern "C" uint64_t artFindInterfaceMethodInCacheFromCode(uint32_t method_idx,
Ian Rogerscaab8c42011-10-12 12:11:18 -0700866 Object* this_object,
867 Method* caller_method,
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700868 Thread* thread, Method** sp) {
Ian Rogerscaab8c42011-10-12 12:11:18 -0700869 Method* interface_method = caller_method->GetDexCacheResolvedMethods()->Get(method_idx);
870 Method* found_method = NULL; // The found method
871 if (LIKELY(interface_method != NULL && this_object != NULL)) {
Ian Rogersb04f69f2011-10-17 00:40:54 -0700872 found_method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method, false);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700873 }
Ian Rogerscaab8c42011-10-12 12:11:18 -0700874 if (UNLIKELY(found_method == NULL)) {
875 FinishCalleeSaveFrameSetup(thread, sp, Runtime::kRefsAndArgs);
876 if (this_object == NULL) {
877 thread->ThrowNewExceptionF("Ljava/lang/NullPointerException;",
878 "null receiver during interface dispatch");
879 return 0;
880 }
881 if (interface_method == NULL) {
882 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
883 interface_method = class_linker->ResolveMethod(method_idx, caller_method, false);
884 if (interface_method == NULL) {
885 // Could not resolve interface method. Throw error and unwind
886 CHECK(thread->IsExceptionPending());
887 return 0;
888 }
889 }
Ian Rogersb04f69f2011-10-17 00:40:54 -0700890 found_method = this_object->GetClass()->FindVirtualMethodForInterface(interface_method, true);
Ian Rogerscaab8c42011-10-12 12:11:18 -0700891 if (found_method == NULL) {
892 CHECK(thread->IsExceptionPending());
893 return 0;
894 }
Shih-wei Liao2d831012011-09-28 22:06:53 -0700895 }
Ian Rogerscaab8c42011-10-12 12:11:18 -0700896 const void* code = found_method->GetCode();
Shih-wei Liao2d831012011-09-28 22:06:53 -0700897
Ian Rogerscaab8c42011-10-12 12:11:18 -0700898 uint32_t method_uint = reinterpret_cast<uint32_t>(found_method);
Shih-wei Liao2d831012011-09-28 22:06:53 -0700899 uint64_t code_uint = reinterpret_cast<uint32_t>(code);
900 uint64_t result = ((code_uint << 32) | method_uint);
901 return result;
902}
903
Ian Rogers466bb252011-10-14 03:29:56 -0700904static void ThrowNewUndeclaredThrowableException(Thread* self, JNIEnv* env, Throwable* exception) {
905 ScopedLocalRef<jclass> jlr_UTE_class(env,
906 env->FindClass("java/lang/reflect/UndeclaredThrowableException"));
907 if (jlr_UTE_class.get() == NULL) {
908 LOG(ERROR) << "Couldn't throw new \"java/lang/reflect/UndeclaredThrowableException\"";
909 } else {
910 jmethodID jlre_UTE_constructor = env->GetMethodID(jlr_UTE_class.get(), "<init>",
911 "(Ljava/lang/Throwable;)V");
912 jthrowable jexception = AddLocalReference<jthrowable>(env, exception);
913 ScopedLocalRef<jthrowable> jlr_UTE(env,
914 reinterpret_cast<jthrowable>(env->NewObject(jlr_UTE_class.get(), jlre_UTE_constructor,
915 jexception)));
916 int rc = env->Throw(jlr_UTE.get());
917 if (rc != JNI_OK) {
918 LOG(ERROR) << "Couldn't throw new \"java/lang/reflect/UndeclaredThrowableException\"";
919 }
920 }
921 CHECK(self->IsExceptionPending());
922}
923
Ian Rogersdfcdf1a2011-10-10 17:50:35 -0700924// Handler for invocation on proxy methods. On entry a frame will exist for the proxy object method
925// which is responsible for recording callee save registers. We explicitly handlerize incoming
926// reference arguments (so they survive GC) and create a boxed argument array. Finally we invoke
927// the invocation handler which is a field within the proxy object receiver.
928extern "C" void artProxyInvokeHandler(Method* proxy_method, Object* receiver,
Ian Rogers466bb252011-10-14 03:29:56 -0700929 Thread* self, byte* stack_args) {
Ian Rogersdfcdf1a2011-10-10 17:50:35 -0700930 // Register the top of the managed stack
Ian Rogers466bb252011-10-14 03:29:56 -0700931 Method** proxy_sp = reinterpret_cast<Method**>(stack_args - 12);
932 DCHECK_EQ(*proxy_sp, proxy_method);
933 self->SetTopOfStack(proxy_sp, 0);
Ian Rogersdfcdf1a2011-10-10 17:50:35 -0700934 // TODO: ARM specific
935 DCHECK_EQ(proxy_method->GetFrameSizeInBytes(), 48u);
936 // Start new JNI local reference state
937 JNIEnvExt* env = self->GetJniEnv();
938 ScopedJniEnvLocalRefState env_state(env);
939 // Create local ref. copies of proxy method and the receiver
940 jobject rcvr_jobj = AddLocalReference<jobject>(env, receiver);
941 jobject proxy_method_jobj = AddLocalReference<jobject>(env, proxy_method);
942
Ian Rogers14b1b242011-10-11 18:54:34 -0700943 // Placing into local references incoming arguments from the caller's register arguments,
944 // replacing original Object* with jobject
945 const size_t num_params = proxy_method->NumArgs();
946 size_t args_in_regs = 0;
947 for (size_t i = 1; i < num_params; i++) { // skip receiver
948 args_in_regs = args_in_regs + (proxy_method->IsParamALongOrDouble(i) ? 2 : 1);
949 if (args_in_regs > 2) {
950 args_in_regs = 2;
951 break;
952 }
953 }
954 size_t cur_arg = 0; // current stack location to read
955 size_t param_index = 1; // skip receiver
956 while (cur_arg < args_in_regs && param_index < num_params) {
957 if (proxy_method->IsParamAReference(param_index)) {
958 Object* obj = *reinterpret_cast<Object**>(stack_args + (cur_arg * kPointerSize));
Ian Rogersdfcdf1a2011-10-10 17:50:35 -0700959 jobject jobj = AddLocalReference<jobject>(env, obj);
Ian Rogers14b1b242011-10-11 18:54:34 -0700960 *reinterpret_cast<jobject*>(stack_args + (cur_arg * kPointerSize)) = jobj;
Ian Rogersdfcdf1a2011-10-10 17:50:35 -0700961 }
Ian Rogers14b1b242011-10-11 18:54:34 -0700962 cur_arg = cur_arg + (proxy_method->IsParamALongOrDouble(param_index) ? 2 : 1);
963 param_index++;
964 }
965 // Placing into local references incoming arguments from the caller's stack arguments
Ian Rogers466bb252011-10-14 03:29:56 -0700966 cur_arg += 11; // skip callee saves, LR, Method* and out arg spills for R1 to R3
Ian Rogers14b1b242011-10-11 18:54:34 -0700967 while (param_index < num_params) {
968 if (proxy_method->IsParamAReference(param_index)) {
969 Object* obj = *reinterpret_cast<Object**>(stack_args + (cur_arg * kPointerSize));
970 jobject jobj = AddLocalReference<jobject>(env, obj);
971 *reinterpret_cast<jobject*>(stack_args + (cur_arg * kPointerSize)) = jobj;
Ian Rogersdfcdf1a2011-10-10 17:50:35 -0700972 }
Ian Rogers14b1b242011-10-11 18:54:34 -0700973 cur_arg = cur_arg + (proxy_method->IsParamALongOrDouble(param_index) ? 2 : 1);
974 param_index++;
Ian Rogersdfcdf1a2011-10-10 17:50:35 -0700975 }
Ian Rogersdfcdf1a2011-10-10 17:50:35 -0700976 // Set up arguments array and place in local IRT during boxing (which may allocate/GC)
977 jvalue args_jobj[3];
978 args_jobj[0].l = rcvr_jobj;
979 args_jobj[1].l = proxy_method_jobj;
Ian Rogers466bb252011-10-14 03:29:56 -0700980 // Args array, if no arguments then NULL (don't include receiver in argument count)
981 args_jobj[2].l = NULL;
982 ObjectArray<Object>* args = NULL;
983 if ((num_params - 1) > 0) {
984 args = Runtime::Current()->GetClassLinker()->AllocObjectArray<Object>(num_params - 1);
985 if(args == NULL) {
986 CHECK(self->IsExceptionPending());
987 return;
988 }
989 args_jobj[2].l = AddLocalReference<jobjectArray>(env, args);
990 }
991 // Convert proxy method into expected interface method
992 Method* interface_method = proxy_method->FindOverriddenMethod();
993 CHECK(interface_method != NULL);
994 args_jobj[1].l = AddLocalReference<jobject>(env, interface_method);
995 LOG(INFO) << "Interface method is " << PrettyMethod(interface_method, true);
Ian Rogersdfcdf1a2011-10-10 17:50:35 -0700996 // Box arguments
Ian Rogers14b1b242011-10-11 18:54:34 -0700997 cur_arg = 0; // reset stack location to read to start
998 // reset index, will index into param type array which doesn't include the receiver
999 param_index = 0;
Ian Rogers466bb252011-10-14 03:29:56 -07001000 ObjectArray<Class>* param_types = interface_method->GetJavaParameterTypes();
Ian Rogers14b1b242011-10-11 18:54:34 -07001001 CHECK(param_types != NULL);
1002 // Check number of parameter types agrees with number from the Method - less 1 for the receiver.
1003 CHECK_EQ(static_cast<size_t>(param_types->GetLength()), num_params - 1);
1004 while (cur_arg < args_in_regs && param_index < (num_params - 1)) {
1005 Class* param_type = param_types->Get(param_index);
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001006 Object* obj;
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001007 if (!param_type->IsPrimitive()) {
Ian Rogers14b1b242011-10-11 18:54:34 -07001008 obj = self->DecodeJObject(*reinterpret_cast<jobject*>(stack_args + (cur_arg * kPointerSize)));
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001009 } else {
Ian Rogers14b1b242011-10-11 18:54:34 -07001010 JValue val = *reinterpret_cast<JValue*>(stack_args + (cur_arg * kPointerSize));
1011 if (cur_arg == 1 && (param_type->IsPrimitiveLong() || param_type->IsPrimitiveDouble())) {
1012 // long/double split over regs and stack, mask in high half from stack arguments
Ian Rogers466bb252011-10-14 03:29:56 -07001013 uint64_t high_half = *reinterpret_cast<uint32_t*>(stack_args + (13 * kPointerSize));
Ian Rogerscaab8c42011-10-12 12:11:18 -07001014 val.j = (val.j & 0xffffffffULL) | (high_half << 32);
Ian Rogers14b1b242011-10-11 18:54:34 -07001015 }
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001016 BoxPrimitive(env, param_type, val);
1017 if (self->IsExceptionPending()) {
1018 return;
1019 }
1020 obj = val.l;
1021 }
Ian Rogers14b1b242011-10-11 18:54:34 -07001022 args->Set(param_index, obj);
1023 cur_arg = cur_arg + (param_type->IsPrimitiveLong() || param_type->IsPrimitiveDouble() ? 2 : 1);
1024 param_index++;
1025 }
1026 // Placing into local references incoming arguments from the caller's stack arguments
Ian Rogers466bb252011-10-14 03:29:56 -07001027 cur_arg += 11; // skip callee saves, LR, Method* and out arg spills for R1 to R3
1028 while (param_index < (num_params - 1)) {
Ian Rogers14b1b242011-10-11 18:54:34 -07001029 Class* param_type = param_types->Get(param_index);
1030 Object* obj;
1031 if (!param_type->IsPrimitive()) {
1032 obj = self->DecodeJObject(*reinterpret_cast<jobject*>(stack_args + (cur_arg * kPointerSize)));
1033 } else {
1034 JValue val = *reinterpret_cast<JValue*>(stack_args + (cur_arg * kPointerSize));
1035 BoxPrimitive(env, param_type, val);
1036 if (self->IsExceptionPending()) {
1037 return;
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001038 }
Ian Rogers14b1b242011-10-11 18:54:34 -07001039 obj = val.l;
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001040 }
Ian Rogers14b1b242011-10-11 18:54:34 -07001041 args->Set(param_index, obj);
1042 cur_arg = cur_arg + (param_type->IsPrimitiveLong() || param_type->IsPrimitiveDouble() ? 2 : 1);
1043 param_index++;
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001044 }
1045 // Get the InvocationHandler method and the field that holds it within the Proxy object
1046 static jmethodID inv_hand_invoke_mid = NULL;
1047 static jfieldID proxy_inv_hand_fid = NULL;
1048 if (proxy_inv_hand_fid == NULL) {
Ian Rogers466bb252011-10-14 03:29:56 -07001049 ScopedLocalRef<jclass> proxy(env, env->FindClass("java/lang/reflect/Proxy"));
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001050 proxy_inv_hand_fid = env->GetFieldID(proxy.get(), "h", "Ljava/lang/reflect/InvocationHandler;");
Ian Rogers466bb252011-10-14 03:29:56 -07001051 ScopedLocalRef<jclass> inv_hand_class(env, env->FindClass("java/lang/reflect/InvocationHandler"));
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001052 inv_hand_invoke_mid = env->GetMethodID(inv_hand_class.get(), "invoke",
1053 "(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;");
1054 }
Ian Rogers466bb252011-10-14 03:29:56 -07001055 DCHECK(env->IsInstanceOf(rcvr_jobj, env->FindClass("java/lang/reflect/Proxy")));
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001056 jobject inv_hand = env->GetObjectField(rcvr_jobj, proxy_inv_hand_fid);
1057 // Call InvocationHandler.invoke
1058 jobject result = env->CallObjectMethodA(inv_hand, inv_hand_invoke_mid, args_jobj);
1059 // Place result in stack args
1060 if (!self->IsExceptionPending()) {
1061 Object* result_ref = self->DecodeJObject(result);
1062 if (result_ref != NULL) {
1063 JValue result_unboxed;
Ian Rogers466bb252011-10-14 03:29:56 -07001064 UnboxPrimitive(env, result_ref, interface_method->GetReturnType(), result_unboxed);
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001065 *reinterpret_cast<JValue*>(stack_args) = result_unboxed;
1066 } else {
1067 *reinterpret_cast<jobject*>(stack_args) = NULL;
1068 }
Ian Rogers466bb252011-10-14 03:29:56 -07001069 } else {
1070 // In the case of checked exceptions that aren't declared, the exception must be wrapped by
1071 // a UndeclaredThrowableException.
1072 Throwable* exception = self->GetException();
1073 self->ClearException();
1074 if (!exception->IsCheckedException()) {
1075 self->SetException(exception);
1076 } else {
1077 ObjectArray<Class>* declared_exceptions = proxy_method->GetExceptionTypes();
1078 Class* exception_class = exception->GetClass();
1079 bool declares_exception = false;
1080 for (int i = 0; i < declared_exceptions->GetLength() && !declares_exception; i++) {
1081 Class* declared_exception = declared_exceptions->Get(i);
1082 declares_exception = declared_exception->IsAssignableFrom(exception_class);
1083 }
1084 if (declares_exception) {
1085 self->SetException(exception);
1086 } else {
1087 ThrowNewUndeclaredThrowableException(self, env, exception);
1088 }
1089 }
Ian Rogersdfcdf1a2011-10-10 17:50:35 -07001090 }
1091}
1092
Shih-wei Liao2d831012011-09-28 22:06:53 -07001093/*
1094 * Float/double conversion requires clamping to min and max of integer form. If
1095 * target doesn't support this normally, use these.
1096 */
1097int64_t D2L(double d) {
1098 static const double kMaxLong = (double)(int64_t)0x7fffffffffffffffULL;
1099 static const double kMinLong = (double)(int64_t)0x8000000000000000ULL;
1100 if (d >= kMaxLong)
1101 return (int64_t)0x7fffffffffffffffULL;
1102 else if (d <= kMinLong)
1103 return (int64_t)0x8000000000000000ULL;
1104 else if (d != d) // NaN case
1105 return 0;
1106 else
1107 return (int64_t)d;
1108}
1109
1110int64_t F2L(float f) {
1111 static const float kMaxLong = (float)(int64_t)0x7fffffffffffffffULL;
1112 static const float kMinLong = (float)(int64_t)0x8000000000000000ULL;
1113 if (f >= kMaxLong)
1114 return (int64_t)0x7fffffffffffffffULL;
1115 else if (f <= kMinLong)
1116 return (int64_t)0x8000000000000000ULL;
1117 else if (f != f) // NaN case
1118 return 0;
1119 else
1120 return (int64_t)f;
1121}
1122
1123} // namespace art