blob: 61def350f992473c4790481a1749c5c8bcae8f89 [file] [log] [blame]
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001/*
2 * Copyright (C) 2015 The Android Open Source Project
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 "unstarted_runtime.h"
18
19#include <cmath>
20#include <unordered_map>
21
Andreas Gampeaacc25d2015-04-01 14:49:06 -070022#include "ScopedLocalRef.h"
23
Andreas Gampe2969bcd2015-03-09 12:57:41 -070024#include "base/logging.h"
25#include "base/macros.h"
26#include "class_linker.h"
27#include "common_throws.h"
28#include "entrypoints/entrypoint_utils-inl.h"
29#include "handle_scope-inl.h"
30#include "interpreter/interpreter_common.h"
31#include "mirror/array-inl.h"
32#include "mirror/art_method-inl.h"
33#include "mirror/class.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070034#include "mirror/field-inl.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070035#include "mirror/object-inl.h"
36#include "mirror/object_array-inl.h"
37#include "mirror/string-inl.h"
38#include "nth_caller_visitor.h"
39#include "thread.h"
Sebastien Hertz2fd7e692015-04-02 11:11:19 +020040#include "transaction.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070041#include "well_known_classes.h"
Andreas Gampef778eb22015-04-13 14:17:09 -070042#include "zip_archive.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070043
44namespace art {
45namespace interpreter {
46
Andreas Gampe068b0c02015-03-11 12:44:47 -070047static void AbortTransactionOrFail(Thread* self, const char* fmt, ...)
Sebastien Hertz45b15972015-04-03 16:07:05 +020048 __attribute__((__format__(__printf__, 2, 3)))
49 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
50
51static void AbortTransactionOrFail(Thread* self, const char* fmt, ...) {
Andreas Gampe068b0c02015-03-11 12:44:47 -070052 va_list args;
Andreas Gampe068b0c02015-03-11 12:44:47 -070053 if (Runtime::Current()->IsActiveTransaction()) {
Sebastien Hertz45b15972015-04-03 16:07:05 +020054 va_start(args, fmt);
55 AbortTransactionV(self, fmt, args);
Andreas Gampe068b0c02015-03-11 12:44:47 -070056 va_end(args);
57 } else {
Sebastien Hertz45b15972015-04-03 16:07:05 +020058 va_start(args, fmt);
59 std::string msg;
60 StringAppendV(&msg, fmt, args);
61 va_end(args);
62 LOG(FATAL) << "Trying to abort, but not in transaction mode: " << msg;
Andreas Gampe068b0c02015-03-11 12:44:47 -070063 UNREACHABLE();
64 }
65}
66
Andreas Gampe2969bcd2015-03-09 12:57:41 -070067// Helper function to deal with class loading in an unstarted runtime.
68static void UnstartedRuntimeFindClass(Thread* self, Handle<mirror::String> className,
69 Handle<mirror::ClassLoader> class_loader, JValue* result,
70 const std::string& method_name, bool initialize_class,
71 bool abort_if_not_found)
72 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
73 CHECK(className.Get() != nullptr);
74 std::string descriptor(DotToDescriptor(className->ToModifiedUtf8().c_str()));
75 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
76
77 mirror::Class* found = class_linker->FindClass(self, descriptor.c_str(), class_loader);
78 if (found == nullptr && abort_if_not_found) {
79 if (!self->IsExceptionPending()) {
Andreas Gampe068b0c02015-03-11 12:44:47 -070080 AbortTransactionOrFail(self, "%s failed in un-started runtime for class: %s",
81 method_name.c_str(), PrettyDescriptor(descriptor.c_str()).c_str());
Andreas Gampe2969bcd2015-03-09 12:57:41 -070082 }
83 return;
84 }
85 if (found != nullptr && initialize_class) {
86 StackHandleScope<1> hs(self);
87 Handle<mirror::Class> h_class(hs.NewHandle(found));
88 if (!class_linker->EnsureInitialized(self, h_class, true, true)) {
89 CHECK(self->IsExceptionPending());
90 return;
91 }
92 }
93 result->SetL(found);
94}
95
96// Common helper for class-loading cutouts in an unstarted runtime. We call Runtime methods that
97// rely on Java code to wrap errors in the correct exception class (i.e., NoClassDefFoundError into
98// ClassNotFoundException), so need to do the same. The only exception is if the exception is
Sebastien Hertz2fd7e692015-04-02 11:11:19 +020099// actually the transaction abort exception. This must not be wrapped, as it signals an
100// initialization abort.
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700101static void CheckExceptionGenerateClassNotFound(Thread* self)
102 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
103 if (self->IsExceptionPending()) {
Sebastien Hertz2fd7e692015-04-02 11:11:19 +0200104 // If it is not the transaction abort exception, wrap it.
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700105 std::string type(PrettyTypeOf(self->GetException()));
Sebastien Hertz2fd7e692015-04-02 11:11:19 +0200106 if (type != Transaction::kAbortExceptionDescriptor) {
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700107 self->ThrowNewWrappedException("Ljava/lang/ClassNotFoundException;",
108 "ClassNotFoundException");
109 }
110 }
111}
112
Andreas Gampe5d4bb1d2015-04-14 22:16:14 -0700113static mirror::String* GetClassName(Thread* self, ShadowFrame* shadow_frame, size_t arg_offset)
114 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
115 mirror::Object* param = shadow_frame->GetVRegReference(arg_offset);
116 if (param == nullptr) {
117 AbortTransactionOrFail(self, "Null-pointer in Class.forName.");
118 return nullptr;
119 }
120 return param->AsString();
121}
122
Andreas Gampedd9d0552015-03-09 12:57:41 -0700123static void UnstartedClassForName(
124 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700125 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe5d4bb1d2015-04-14 22:16:14 -0700126 mirror::String* class_name = GetClassName(self, shadow_frame, arg_offset);
127 if (class_name == nullptr) {
128 return;
129 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700130 StackHandleScope<1> hs(self);
131 Handle<mirror::String> h_class_name(hs.NewHandle(class_name));
132 UnstartedRuntimeFindClass(self, h_class_name, NullHandle<mirror::ClassLoader>(), result,
133 "Class.forName", true, false);
134 CheckExceptionGenerateClassNotFound(self);
135}
136
Andreas Gampedd9d0552015-03-09 12:57:41 -0700137static void UnstartedClassForNameLong(
138 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700139 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe5d4bb1d2015-04-14 22:16:14 -0700140 mirror::String* class_name = GetClassName(self, shadow_frame, arg_offset);
141 if (class_name == nullptr) {
Andreas Gampebf4d3af2015-04-14 10:10:33 -0700142 return;
143 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700144 bool initialize_class = shadow_frame->GetVReg(arg_offset + 1) != 0;
145 mirror::ClassLoader* class_loader =
146 down_cast<mirror::ClassLoader*>(shadow_frame->GetVRegReference(arg_offset + 2));
147 StackHandleScope<2> hs(self);
148 Handle<mirror::String> h_class_name(hs.NewHandle(class_name));
149 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
150 UnstartedRuntimeFindClass(self, h_class_name, h_class_loader, result, "Class.forName",
151 initialize_class, false);
152 CheckExceptionGenerateClassNotFound(self);
153}
154
Andreas Gampedd9d0552015-03-09 12:57:41 -0700155static void UnstartedClassClassForName(
156 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700157 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampe5d4bb1d2015-04-14 22:16:14 -0700158 mirror::String* class_name = GetClassName(self, shadow_frame, arg_offset);
159 if (class_name == nullptr) {
160 return;
161 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700162 bool initialize_class = shadow_frame->GetVReg(arg_offset + 1) != 0;
163 mirror::ClassLoader* class_loader =
164 down_cast<mirror::ClassLoader*>(shadow_frame->GetVRegReference(arg_offset + 2));
165 StackHandleScope<2> hs(self);
166 Handle<mirror::String> h_class_name(hs.NewHandle(class_name));
167 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
168 UnstartedRuntimeFindClass(self, h_class_name, h_class_loader, result, "Class.classForName",
169 initialize_class, false);
170 CheckExceptionGenerateClassNotFound(self);
171}
172
Andreas Gampedd9d0552015-03-09 12:57:41 -0700173static void UnstartedClassNewInstance(
174 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700175 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
176 StackHandleScope<3> hs(self); // Class, constructor, object.
Andreas Gampe5d4bb1d2015-04-14 22:16:14 -0700177 mirror::Object* param = shadow_frame->GetVRegReference(arg_offset);
178 if (param == nullptr) {
179 AbortTransactionOrFail(self, "Null-pointer in Class.newInstance.");
180 return;
181 }
182 mirror::Class* klass = param->AsClass();
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700183 Handle<mirror::Class> h_klass(hs.NewHandle(klass));
Andreas Gampe0f7e3d62015-03-11 13:24:35 -0700184
185 // Check that it's not null.
186 if (h_klass.Get() == nullptr) {
187 AbortTransactionOrFail(self, "Class reference is null for newInstance");
188 return;
189 }
190
191 // If we're in a transaction, class must not be finalizable (it or a superclass has a finalizer).
192 if (Runtime::Current()->IsActiveTransaction()) {
193 if (h_klass.Get()->IsFinalizable()) {
Sebastien Hertz45b15972015-04-03 16:07:05 +0200194 AbortTransactionF(self, "Class for newInstance is finalizable: '%s'",
195 PrettyClass(h_klass.Get()).c_str());
Andreas Gampe0f7e3d62015-03-11 13:24:35 -0700196 return;
197 }
198 }
199
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700200 // There are two situations in which we'll abort this run.
201 // 1) If the class isn't yet initialized and initialization fails.
202 // 2) If we can't find the default constructor. We'll postpone the exception to runtime.
203 // Note that 2) could likely be handled here, but for safety abort the transaction.
204 bool ok = false;
205 if (Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_klass, true, true)) {
206 Handle<mirror::ArtMethod> h_cons(hs.NewHandle(
207 h_klass->FindDeclaredDirectMethod("<init>", "()V")));
208 if (h_cons.Get() != nullptr) {
209 Handle<mirror::Object> h_obj(hs.NewHandle(klass->AllocObject(self)));
210 CHECK(h_obj.Get() != nullptr); // We don't expect OOM at compile-time.
211 EnterInterpreterFromInvoke(self, h_cons.Get(), h_obj.Get(), nullptr, nullptr);
212 if (!self->IsExceptionPending()) {
213 result->SetL(h_obj.Get());
214 ok = true;
215 }
216 } else {
217 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
218 "Could not find default constructor for '%s'",
219 PrettyClass(h_klass.Get()).c_str());
220 }
221 }
222 if (!ok) {
Andreas Gampe068b0c02015-03-11 12:44:47 -0700223 AbortTransactionOrFail(self, "Failed in Class.newInstance for '%s' with %s",
224 PrettyClass(h_klass.Get()).c_str(),
225 PrettyTypeOf(self->GetException()).c_str());
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700226 }
227}
228
Andreas Gampedd9d0552015-03-09 12:57:41 -0700229static void UnstartedClassGetDeclaredField(
230 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700231 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
232 // Special managed code cut-out to allow field lookup in a un-started runtime that'd fail
233 // going the reflective Dex way.
234 mirror::Class* klass = shadow_frame->GetVRegReference(arg_offset)->AsClass();
235 mirror::String* name2 = shadow_frame->GetVRegReference(arg_offset + 1)->AsString();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700236 ArtField* found = nullptr;
237 ArtField* fields = klass->GetIFields();
238 for (int32_t i = 0, count = klass->NumInstanceFields(); i < count; ++i) {
239 ArtField* f = &fields[i];
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700240 if (name2->Equals(f->GetName())) {
241 found = f;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700242 break;
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700243 }
244 }
245 if (found == nullptr) {
246 fields = klass->GetSFields();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700247 for (int32_t i = 0, count = klass->NumStaticFields(); i < count; ++i) {
248 ArtField* f = &fields[i];
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700249 if (name2->Equals(f->GetName())) {
250 found = f;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700251 break;
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700252 }
253 }
254 }
Andreas Gampe068b0c02015-03-11 12:44:47 -0700255 if (found == nullptr) {
256 AbortTransactionOrFail(self, "Failed to find field in Class.getDeclaredField in un-started "
257 " runtime. name=%s class=%s", name2->ToModifiedUtf8().c_str(),
258 PrettyDescriptor(klass).c_str());
259 return;
260 }
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700261 if (Runtime::Current()->IsActiveTransaction()) {
262 result->SetL(mirror::Field::CreateFromArtField<true>(self, found, true));
263 } else {
264 result->SetL(mirror::Field::CreateFromArtField<false>(self, found, true));
265 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700266}
267
Andreas Gampedd9d0552015-03-09 12:57:41 -0700268static void UnstartedVmClassLoaderFindLoadedClass(
269 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700270 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
271 mirror::String* class_name = shadow_frame->GetVRegReference(arg_offset + 1)->AsString();
272 mirror::ClassLoader* class_loader =
273 down_cast<mirror::ClassLoader*>(shadow_frame->GetVRegReference(arg_offset));
274 StackHandleScope<2> hs(self);
275 Handle<mirror::String> h_class_name(hs.NewHandle(class_name));
276 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
277 UnstartedRuntimeFindClass(self, h_class_name, h_class_loader, result,
278 "VMClassLoader.findLoadedClass", false, false);
279 // This might have an error pending. But semantics are to just return null.
280 if (self->IsExceptionPending()) {
281 // If it is an InternalError, keep it. See CheckExceptionGenerateClassNotFound.
282 std::string type(PrettyTypeOf(self->GetException()));
283 if (type != "java.lang.InternalError") {
284 self->ClearException();
285 }
286 }
287}
288
289static void UnstartedVoidLookupType(Thread* self ATTRIBUTE_UNUSED,
290 ShadowFrame* shadow_frame ATTRIBUTE_UNUSED,
291 JValue* result,
292 size_t arg_offset ATTRIBUTE_UNUSED)
293 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
294 result->SetL(Runtime::Current()->GetClassLinker()->FindPrimitiveClass('V'));
295}
296
Andreas Gampe8e6c3fd2015-03-11 18:34:44 -0700297// Arraycopy emulation.
298// Note: we can't use any fast copy functions, as they are not available under transaction.
299
300template <typename T>
301static void PrimitiveArrayCopy(Thread* self,
302 mirror::Array* src_array, int32_t src_pos,
303 mirror::Array* dst_array, int32_t dst_pos,
304 int32_t length)
305 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
306 if (src_array->GetClass()->GetComponentType() != dst_array->GetClass()->GetComponentType()) {
307 AbortTransactionOrFail(self, "Types mismatched in arraycopy: %s vs %s.",
308 PrettyDescriptor(src_array->GetClass()->GetComponentType()).c_str(),
309 PrettyDescriptor(dst_array->GetClass()->GetComponentType()).c_str());
310 return;
311 }
312 mirror::PrimitiveArray<T>* src = down_cast<mirror::PrimitiveArray<T>*>(src_array);
313 mirror::PrimitiveArray<T>* dst = down_cast<mirror::PrimitiveArray<T>*>(dst_array);
314 const bool copy_forward = (dst_pos < src_pos) || (dst_pos - src_pos >= length);
315 if (copy_forward) {
316 for (int32_t i = 0; i < length; ++i) {
317 dst->Set(dst_pos + i, src->Get(src_pos + i));
318 }
319 } else {
320 for (int32_t i = 1; i <= length; ++i) {
321 dst->Set(dst_pos + length - i, src->Get(src_pos + length - i));
322 }
323 }
324}
325
Andreas Gampedd9d0552015-03-09 12:57:41 -0700326static void UnstartedSystemArraycopy(
327 Thread* self, ShadowFrame* shadow_frame, JValue* result ATTRIBUTE_UNUSED, size_t arg_offset)
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700328 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
329 // Special case array copying without initializing System.
Andreas Gampe8e6c3fd2015-03-11 18:34:44 -0700330 jint src_pos = shadow_frame->GetVReg(arg_offset + 1);
331 jint dst_pos = shadow_frame->GetVReg(arg_offset + 3);
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700332 jint length = shadow_frame->GetVReg(arg_offset + 4);
Andreas Gampe8e6c3fd2015-03-11 18:34:44 -0700333 mirror::Array* src_array = shadow_frame->GetVRegReference(arg_offset)->AsArray();
334 mirror::Array* dst_array = shadow_frame->GetVRegReference(arg_offset + 2)->AsArray();
335
336 // Null checking.
337 if (src_array == nullptr) {
338 AbortTransactionOrFail(self, "src is null in arraycopy.");
339 return;
340 }
341 if (dst_array == nullptr) {
342 AbortTransactionOrFail(self, "dst is null in arraycopy.");
343 return;
344 }
345
346 // Bounds checking.
347 if (UNLIKELY(src_pos < 0) || UNLIKELY(dst_pos < 0) || UNLIKELY(length < 0) ||
348 UNLIKELY(src_pos > src_array->GetLength() - length) ||
349 UNLIKELY(dst_pos > dst_array->GetLength() - length)) {
350 self->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;",
351 "src.length=%d srcPos=%d dst.length=%d dstPos=%d length=%d",
352 src_array->GetLength(), src_pos, dst_array->GetLength(), dst_pos,
353 length);
354 AbortTransactionOrFail(self, "Index out of bounds.");
355 return;
356 }
357
358 // Type checking.
359 mirror::Class* src_type = shadow_frame->GetVRegReference(arg_offset)->GetClass()->
360 GetComponentType();
361
362 if (!src_type->IsPrimitive()) {
363 // Check that the second type is not primitive.
364 mirror::Class* trg_type = shadow_frame->GetVRegReference(arg_offset + 2)->GetClass()->
365 GetComponentType();
366 if (trg_type->IsPrimitiveInt()) {
367 AbortTransactionOrFail(self, "Type mismatch in arraycopy: %s vs %s",
368 PrettyDescriptor(src_array->GetClass()->GetComponentType()).c_str(),
369 PrettyDescriptor(dst_array->GetClass()->GetComponentType()).c_str());
370 return;
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700371 }
Andreas Gampe8e6c3fd2015-03-11 18:34:44 -0700372
373 // For simplicity only do this if the component types are the same. Otherwise we have to copy
374 // even more code from the object-array functions.
375 if (src_type != trg_type) {
376 AbortTransactionOrFail(self, "Types not the same in arraycopy: %s vs %s",
377 PrettyDescriptor(src_array->GetClass()->GetComponentType()).c_str(),
378 PrettyDescriptor(dst_array->GetClass()->GetComponentType()).c_str());
379 return;
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700380 }
Andreas Gampe8e6c3fd2015-03-11 18:34:44 -0700381
382 mirror::ObjectArray<mirror::Object>* src = src_array->AsObjectArray<mirror::Object>();
383 mirror::ObjectArray<mirror::Object>* dst = dst_array->AsObjectArray<mirror::Object>();
384 if (src == dst) {
385 // Can overlap, but not have type mismatches.
386 const bool copy_forward = (dst_pos < src_pos) || (dst_pos - src_pos >= length);
387 if (copy_forward) {
388 for (int32_t i = 0; i < length; ++i) {
389 dst->Set(dst_pos + i, src->Get(src_pos + i));
390 }
391 } else {
392 for (int32_t i = 1; i <= length; ++i) {
393 dst->Set(dst_pos + length - i, src->Get(src_pos + length - i));
394 }
395 }
396 } else {
397 // Can't overlap. Would need type checks, but we abort above.
398 for (int32_t i = 0; i < length; ++i) {
399 dst->Set(dst_pos + i, src->Get(src_pos + i));
400 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700401 }
Andreas Gampe8e6c3fd2015-03-11 18:34:44 -0700402 } else if (src_type->IsPrimitiveChar()) {
403 PrimitiveArrayCopy<uint16_t>(self, src_array, src_pos, dst_array, dst_pos, length);
404 } else if (src_type->IsPrimitiveInt()) {
405 PrimitiveArrayCopy<int32_t>(self, src_array, src_pos, dst_array, dst_pos, length);
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700406 } else {
Andreas Gampe068b0c02015-03-11 12:44:47 -0700407 AbortTransactionOrFail(self, "Unimplemented System.arraycopy for type '%s'",
Andreas Gampe8e6c3fd2015-03-11 18:34:44 -0700408 PrettyDescriptor(src_type).c_str());
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700409 }
410}
411
Andreas Gampedd9d0552015-03-09 12:57:41 -0700412static void UnstartedThreadLocalGet(
413 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset ATTRIBUTE_UNUSED)
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700414 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
415 std::string caller(PrettyMethod(shadow_frame->GetLink()->GetMethod()));
416 bool ok = false;
417 if (caller == "java.lang.String java.lang.IntegralToString.convertInt"
418 "(java.lang.AbstractStringBuilder, int)") {
419 // Allocate non-threadlocal buffer.
420 result->SetL(mirror::CharArray::Alloc(self, 11));
421 ok = true;
422 } else if (caller == "java.lang.RealToString java.lang.RealToString.getInstance()") {
423 // Note: RealToString is implemented and used in a different fashion than IntegralToString.
424 // Conversion is done over an actual object of RealToString (the conversion method is an
425 // instance method). This means it is not as clear whether it is correct to return a new
426 // object each time. The caller needs to be inspected by hand to see whether it (incorrectly)
427 // stores the object for later use.
428 // See also b/19548084 for a possible rewrite and bringing it in line with IntegralToString.
429 if (shadow_frame->GetLink()->GetLink() != nullptr) {
430 std::string caller2(PrettyMethod(shadow_frame->GetLink()->GetLink()->GetMethod()));
431 if (caller2 == "java.lang.String java.lang.Double.toString(double)") {
432 // Allocate new object.
433 StackHandleScope<2> hs(self);
434 Handle<mirror::Class> h_real_to_string_class(hs.NewHandle(
435 shadow_frame->GetLink()->GetMethod()->GetDeclaringClass()));
436 Handle<mirror::Object> h_real_to_string_obj(hs.NewHandle(
437 h_real_to_string_class->AllocObject(self)));
438 if (h_real_to_string_obj.Get() != nullptr) {
439 mirror::ArtMethod* init_method =
440 h_real_to_string_class->FindDirectMethod("<init>", "()V");
441 if (init_method == nullptr) {
442 h_real_to_string_class->DumpClass(LOG(FATAL), mirror::Class::kDumpClassFullDetail);
443 } else {
444 JValue invoke_result;
445 EnterInterpreterFromInvoke(self, init_method, h_real_to_string_obj.Get(), nullptr,
446 nullptr);
447 if (!self->IsExceptionPending()) {
448 result->SetL(h_real_to_string_obj.Get());
449 ok = true;
450 }
451 }
452 }
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700453 }
454 }
455 }
456
457 if (!ok) {
Andreas Gampe068b0c02015-03-11 12:44:47 -0700458 AbortTransactionOrFail(self, "Could not create RealToString object");
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700459 }
460}
461
Andreas Gampedd9d0552015-03-09 12:57:41 -0700462static void UnstartedMathCeil(
463 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700464 double in = shadow_frame->GetVRegDouble(arg_offset);
465 double out;
466 // Special cases:
467 // 1) NaN, infinity, +0, -0 -> out := in. All are guaranteed by cmath.
468 // -1 < in < 0 -> out := -0.
469 if (-1.0 < in && in < 0) {
470 out = -0.0;
471 } else {
472 out = ceil(in);
473 }
474 result->SetD(out);
475}
476
Andreas Gampedd9d0552015-03-09 12:57:41 -0700477static void UnstartedArtMethodGetMethodName(
478 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700479 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
480 mirror::ArtMethod* method = shadow_frame->GetVRegReference(arg_offset)->AsArtMethod();
481 result->SetL(method->GetNameAsString(self));
482}
483
Andreas Gampedd9d0552015-03-09 12:57:41 -0700484static void UnstartedObjectHashCode(
485 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700486 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
487 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset);
488 result->SetI(obj->IdentityHashCode());
489}
490
Andreas Gampedd9d0552015-03-09 12:57:41 -0700491static void UnstartedDoubleDoubleToRawLongBits(
492 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700493 double in = shadow_frame->GetVRegDouble(arg_offset);
Roland Levillainda4d79b2015-03-24 14:36:11 +0000494 result->SetJ(bit_cast<int64_t, double>(in));
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700495}
496
Andreas Gampedd9d0552015-03-09 12:57:41 -0700497static mirror::Object* GetDexFromDexCache(Thread* self, mirror::DexCache* dex_cache)
498 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
499 const DexFile* dex_file = dex_cache->GetDexFile();
500 if (dex_file == nullptr) {
501 return nullptr;
502 }
503
504 // Create the direct byte buffer.
505 JNIEnv* env = self->GetJniEnv();
506 DCHECK(env != nullptr);
507 void* address = const_cast<void*>(reinterpret_cast<const void*>(dex_file->Begin()));
Andreas Gampeaacc25d2015-04-01 14:49:06 -0700508 ScopedLocalRef<jobject> byte_buffer(env, env->NewDirectByteBuffer(address, dex_file->Size()));
509 if (byte_buffer.get() == nullptr) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700510 DCHECK(self->IsExceptionPending());
511 return nullptr;
512 }
513
514 jvalue args[1];
Andreas Gampeaacc25d2015-04-01 14:49:06 -0700515 args[0].l = byte_buffer.get();
516
517 ScopedLocalRef<jobject> dex(env, env->CallStaticObjectMethodA(
518 WellKnownClasses::com_android_dex_Dex,
519 WellKnownClasses::com_android_dex_Dex_create,
520 args));
521
522 return self->DecodeJObject(dex.get());
Andreas Gampedd9d0552015-03-09 12:57:41 -0700523}
524
525static void UnstartedDexCacheGetDexNative(
526 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
527 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
528 // We will create the Dex object, but the image writer will release it before creating the
529 // art file.
530 mirror::Object* src = shadow_frame->GetVRegReference(arg_offset);
531 bool have_dex = false;
532 if (src != nullptr) {
533 mirror::Object* dex = GetDexFromDexCache(self, reinterpret_cast<mirror::DexCache*>(src));
534 if (dex != nullptr) {
535 have_dex = true;
536 result->SetL(dex);
537 }
538 }
539 if (!have_dex) {
540 self->ClearException();
Sebastien Hertz2fd7e692015-04-02 11:11:19 +0200541 Runtime::Current()->AbortTransactionAndThrowAbortError(self, "Could not create Dex object");
Andreas Gampedd9d0552015-03-09 12:57:41 -0700542 }
543}
544
545static void UnstartedMemoryPeek(
546 Primitive::Type type, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
547 int64_t address = shadow_frame->GetVRegLong(arg_offset);
548 // TODO: Check that this is in the heap somewhere. Otherwise we will segfault instead of
549 // aborting the transaction.
550
551 switch (type) {
552 case Primitive::kPrimByte: {
553 result->SetB(*reinterpret_cast<int8_t*>(static_cast<intptr_t>(address)));
554 return;
555 }
556
557 case Primitive::kPrimShort: {
558 result->SetS(*reinterpret_cast<int16_t*>(static_cast<intptr_t>(address)));
559 return;
560 }
561
562 case Primitive::kPrimInt: {
563 result->SetI(*reinterpret_cast<int32_t*>(static_cast<intptr_t>(address)));
564 return;
565 }
566
567 case Primitive::kPrimLong: {
568 result->SetJ(*reinterpret_cast<int64_t*>(static_cast<intptr_t>(address)));
569 return;
570 }
571
572 case Primitive::kPrimBoolean:
573 case Primitive::kPrimChar:
574 case Primitive::kPrimFloat:
575 case Primitive::kPrimDouble:
576 case Primitive::kPrimVoid:
577 case Primitive::kPrimNot:
578 LOG(FATAL) << "Not in the Memory API: " << type;
579 UNREACHABLE();
580 }
581 LOG(FATAL) << "Should not reach here";
582 UNREACHABLE();
583}
584
585static void UnstartedMemoryPeekEntry(
586 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
587 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
588 std::string name(PrettyMethod(shadow_frame->GetMethod()));
589 if (name == "byte libcore.io.Memory.peekByte(long)") {
590 UnstartedMemoryPeek(Primitive::kPrimByte, shadow_frame, result, arg_offset);
591 } else if (name == "short libcore.io.Memory.peekShortNative(long)") {
592 UnstartedMemoryPeek(Primitive::kPrimShort, shadow_frame, result, arg_offset);
593 } else if (name == "int libcore.io.Memory.peekIntNative(long)") {
594 UnstartedMemoryPeek(Primitive::kPrimInt, shadow_frame, result, arg_offset);
595 } else if (name == "long libcore.io.Memory.peekLongNative(long)") {
596 UnstartedMemoryPeek(Primitive::kPrimLong, shadow_frame, result, arg_offset);
597 } else {
598 LOG(FATAL) << "Unsupported Memory.peek entry: " << name;
599 UNREACHABLE();
600 }
601}
602
603static void UnstartedMemoryPeekArray(
604 Primitive::Type type, Thread* self, ShadowFrame* shadow_frame, size_t arg_offset)
605 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
606 int64_t address_long = shadow_frame->GetVRegLong(arg_offset);
607 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset + 2);
608 if (obj == nullptr) {
Sebastien Hertz2fd7e692015-04-02 11:11:19 +0200609 Runtime::Current()->AbortTransactionAndThrowAbortError(self, "Null pointer in peekArray");
Andreas Gampedd9d0552015-03-09 12:57:41 -0700610 return;
611 }
612 mirror::Array* array = obj->AsArray();
613
614 int offset = shadow_frame->GetVReg(arg_offset + 3);
615 int count = shadow_frame->GetVReg(arg_offset + 4);
616 if (offset < 0 || offset + count > array->GetLength()) {
617 std::string error_msg(StringPrintf("Array out of bounds in peekArray: %d/%d vs %d",
618 offset, count, array->GetLength()));
Sebastien Hertz2fd7e692015-04-02 11:11:19 +0200619 Runtime::Current()->AbortTransactionAndThrowAbortError(self, error_msg.c_str());
Andreas Gampedd9d0552015-03-09 12:57:41 -0700620 return;
621 }
622
623 switch (type) {
624 case Primitive::kPrimByte: {
625 int8_t* address = reinterpret_cast<int8_t*>(static_cast<intptr_t>(address_long));
626 mirror::ByteArray* byte_array = array->AsByteArray();
627 for (int32_t i = 0; i < count; ++i, ++address) {
628 byte_array->SetWithoutChecks<true>(i + offset, *address);
629 }
630 return;
631 }
632
633 case Primitive::kPrimShort:
634 case Primitive::kPrimInt:
635 case Primitive::kPrimLong:
636 LOG(FATAL) << "Type unimplemented for Memory Array API, should not reach here: " << type;
637 UNREACHABLE();
638
639 case Primitive::kPrimBoolean:
640 case Primitive::kPrimChar:
641 case Primitive::kPrimFloat:
642 case Primitive::kPrimDouble:
643 case Primitive::kPrimVoid:
644 case Primitive::kPrimNot:
645 LOG(FATAL) << "Not in the Memory API: " << type;
646 UNREACHABLE();
647 }
648 LOG(FATAL) << "Should not reach here";
649 UNREACHABLE();
650}
651
652static void UnstartedMemoryPeekArrayEntry(
653 Thread* self, ShadowFrame* shadow_frame, JValue* result ATTRIBUTE_UNUSED, size_t arg_offset)
654 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
655 std::string name(PrettyMethod(shadow_frame->GetMethod()));
656 if (name == "void libcore.io.Memory.peekByteArray(long, byte[], int, int)") {
657 UnstartedMemoryPeekArray(Primitive::kPrimByte, self, shadow_frame, arg_offset);
658 } else {
659 LOG(FATAL) << "Unsupported Memory.peekArray entry: " << name;
660 UNREACHABLE();
661 }
662}
663
Andreas Gampef778eb22015-04-13 14:17:09 -0700664// This allows reading security.properties in an unstarted runtime and initialize Security.
665static void UnstartedSecurityGetSecurityPropertiesReader(
666 Thread* self,
667 ShadowFrame* shadow_frame ATTRIBUTE_UNUSED,
668 JValue* result,
669 size_t arg_offset ATTRIBUTE_UNUSED)
670 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
671 Runtime* runtime = Runtime::Current();
672 const std::vector<const DexFile*>& path = runtime->GetClassLinker()->GetBootClassPath();
673 std::string canonical(DexFile::GetDexCanonicalLocation(path[0]->GetLocation().c_str()));
674 mirror::String* string_data;
675
676 // Use a block to enclose the I/O and MemMap code so buffers are released early.
677 {
678 std::string error_msg;
679 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(canonical.c_str(), &error_msg));
680 if (zip_archive.get() == nullptr) {
681 AbortTransactionOrFail(self, "Could not open zip file %s: %s", canonical.c_str(),
682 error_msg.c_str());
683 return;
684 }
685 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find("java/security/security.properties",
686 &error_msg));
687 if (zip_entry.get() == nullptr) {
688 AbortTransactionOrFail(self, "Could not find security.properties file in %s: %s",
689 canonical.c_str(), error_msg.c_str());
690 return;
691 }
692 std::unique_ptr<MemMap> map(zip_entry->ExtractToMemMap(canonical.c_str(),
693 "java/security/security.properties",
694 &error_msg));
695 if (map.get() == nullptr) {
696 AbortTransactionOrFail(self, "Could not unzip security.properties file in %s: %s",
697 canonical.c_str(), error_msg.c_str());
698 return;
699 }
700
701 uint32_t length = zip_entry->GetUncompressedLength();
702 std::unique_ptr<char[]> tmp(new char[length + 1]);
703 memcpy(tmp.get(), map->Begin(), length);
704 tmp.get()[length] = 0; // null terminator
705
706 string_data = mirror::String::AllocFromModifiedUtf8(self, tmp.get());
707 }
708
709 if (string_data == nullptr) {
710 AbortTransactionOrFail(self, "Could not create string from file content of %s",
711 canonical.c_str());
712 return;
713 }
714
715 // Create a StringReader.
716 StackHandleScope<3> hs(self);
717 Handle<mirror::String> h_string(hs.NewHandle(string_data));
718
719 Handle<mirror::Class> h_class(hs.NewHandle(
720 runtime->GetClassLinker()->FindClass(self,
721 "Ljava/io/StringReader;",
722 NullHandle<mirror::ClassLoader>())));
723 if (h_class.Get() == nullptr) {
724 AbortTransactionOrFail(self, "Could not find StringReader class");
725 return;
726 }
727
728 if (!runtime->GetClassLinker()->EnsureInitialized(self, h_class, true, true)) {
729 AbortTransactionOrFail(self, "Could not initialize StringReader class");
730 return;
731 }
732
733 Handle<mirror::Object> h_obj(hs.NewHandle(h_class->AllocObject(self)));
734 if (h_obj.Get() == nullptr) {
735 AbortTransactionOrFail(self, "Could not allocate StringReader object");
736 return;
737 }
738
739 mirror::ArtMethod* constructor = h_class->FindDeclaredDirectMethod("<init>",
740 "(Ljava/lang/String;)V");
741 if (constructor == nullptr) {
742 AbortTransactionOrFail(self, "Could not find StringReader constructor");
743 return;
744 }
745
746 uint32_t args[1];
747 args[0] = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(h_string.Get()));
748 EnterInterpreterFromInvoke(self, constructor, h_obj.Get(), args, nullptr);
749
750 if (self->IsExceptionPending()) {
751 AbortTransactionOrFail(self, "Could not run StringReader constructor");
752 return;
753 }
754
755 result->SetL(h_obj.Get());
756}
757
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700758static void UnstartedJNIVMRuntimeNewUnpaddedArray(Thread* self,
759 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
760 mirror::Object* receiver ATTRIBUTE_UNUSED,
761 uint32_t* args,
762 JValue* result)
763 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
764 int32_t length = args[1];
765 DCHECK_GE(length, 0);
766 mirror::Class* element_class = reinterpret_cast<mirror::Object*>(args[0])->AsClass();
767 Runtime* runtime = Runtime::Current();
768 mirror::Class* array_class = runtime->GetClassLinker()->FindArrayClass(self, &element_class);
769 DCHECK(array_class != nullptr);
770 gc::AllocatorType allocator = runtime->GetHeap()->GetCurrentAllocator();
771 result->SetL(mirror::Array::Alloc<true, true>(self, array_class, length,
772 array_class->GetComponentSizeShift(), allocator));
773}
774
775static void UnstartedJNIVMStackGetCallingClassLoader(Thread* self ATTRIBUTE_UNUSED,
776 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
777 mirror::Object* receiver ATTRIBUTE_UNUSED,
778 uint32_t* args ATTRIBUTE_UNUSED,
779 JValue* result) {
780 result->SetL(nullptr);
781}
782
783static void UnstartedJNIVMStackGetStackClass2(Thread* self,
784 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
785 mirror::Object* receiver ATTRIBUTE_UNUSED,
786 uint32_t* args ATTRIBUTE_UNUSED,
787 JValue* result)
788 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
789 NthCallerVisitor visitor(self, 3);
790 visitor.WalkStack();
791 if (visitor.caller != nullptr) {
792 result->SetL(visitor.caller->GetDeclaringClass());
793 }
794}
795
796static void UnstartedJNIMathLog(Thread* self ATTRIBUTE_UNUSED,
797 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
798 mirror::Object* receiver ATTRIBUTE_UNUSED,
799 uint32_t* args,
800 JValue* result) {
801 JValue value;
802 value.SetJ((static_cast<uint64_t>(args[1]) << 32) | args[0]);
803 result->SetD(log(value.GetD()));
804}
805
806static void UnstartedJNIMathExp(Thread* self ATTRIBUTE_UNUSED,
807 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
808 mirror::Object* receiver ATTRIBUTE_UNUSED,
809 uint32_t* args,
810 JValue* result) {
811 JValue value;
812 value.SetJ((static_cast<uint64_t>(args[1]) << 32) | args[0]);
813 result->SetD(exp(value.GetD()));
814}
815
816static void UnstartedJNIClassGetNameNative(Thread* self,
817 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
818 mirror::Object* receiver,
819 uint32_t* args ATTRIBUTE_UNUSED,
820 JValue* result)
821 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
822 StackHandleScope<1> hs(self);
823 result->SetL(mirror::Class::ComputeName(hs.NewHandle(receiver->AsClass())));
824}
825
826static void UnstartedJNIFloatFloatToRawIntBits(Thread* self ATTRIBUTE_UNUSED,
827 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
828 mirror::Object* receiver ATTRIBUTE_UNUSED,
829 uint32_t* args,
830 JValue* result) {
831 result->SetI(args[0]);
832}
833
834static void UnstartedJNIFloatIntBitsToFloat(Thread* self ATTRIBUTE_UNUSED,
835 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
836 mirror::Object* receiver ATTRIBUTE_UNUSED,
837 uint32_t* args,
838 JValue* result) {
839 result->SetI(args[0]);
840}
841
Andreas Gampeca714582015-04-03 19:41:34 -0700842static void UnstartedJNIObjectInternalClone(Thread* self,
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700843 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
844 mirror::Object* receiver,
845 uint32_t* args ATTRIBUTE_UNUSED,
846 JValue* result)
847 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
848 result->SetL(receiver->Clone(self));
849}
850
Andreas Gampeca714582015-04-03 19:41:34 -0700851static void UnstartedJNIObjectNotifyAll(Thread* self,
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700852 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
853 mirror::Object* receiver,
854 uint32_t* args ATTRIBUTE_UNUSED,
855 JValue* result ATTRIBUTE_UNUSED)
856 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
857 receiver->NotifyAll(self);
858}
859
860static void UnstartedJNIStringCompareTo(Thread* self,
861 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
862 mirror::Object* receiver,
863 uint32_t* args,
864 JValue* result)
865 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
866 mirror::String* rhs = reinterpret_cast<mirror::Object*>(args[0])->AsString();
867 if (rhs == nullptr) {
Andreas Gampe068b0c02015-03-11 12:44:47 -0700868 AbortTransactionOrFail(self, "String.compareTo with null object");
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700869 }
870 result->SetI(receiver->AsString()->CompareTo(rhs));
871}
872
873static void UnstartedJNIStringIntern(Thread* self ATTRIBUTE_UNUSED,
874 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
875 mirror::Object* receiver,
876 uint32_t* args ATTRIBUTE_UNUSED,
877 JValue* result)
878 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
879 result->SetL(receiver->AsString()->Intern());
880}
881
882static void UnstartedJNIStringFastIndexOf(Thread* self ATTRIBUTE_UNUSED,
883 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
884 mirror::Object* receiver,
885 uint32_t* args,
886 JValue* result)
887 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
888 result->SetI(receiver->AsString()->FastIndexOf(args[0], args[1]));
889}
890
891static void UnstartedJNIArrayCreateMultiArray(Thread* self,
892 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
893 mirror::Object* receiver ATTRIBUTE_UNUSED,
894 uint32_t* args,
895 JValue* result)
896 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
897 StackHandleScope<2> hs(self);
898 auto h_class(hs.NewHandle(reinterpret_cast<mirror::Class*>(args[0])->AsClass()));
899 auto h_dimensions(hs.NewHandle(reinterpret_cast<mirror::IntArray*>(args[1])->AsIntArray()));
900 result->SetL(mirror::Array::CreateMultiArray(self, h_class, h_dimensions));
901}
902
Andreas Gampee598e042015-04-10 14:57:10 -0700903static void UnstartedJNIArrayCreateObjectArray(Thread* self,
904 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
905 mirror::Object* receiver ATTRIBUTE_UNUSED,
906 uint32_t* args,
907 JValue* result)
908 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
909 int32_t length = static_cast<int32_t>(args[1]);
910 if (length < 0) {
911 ThrowNegativeArraySizeException(length);
912 return;
913 }
914 mirror::Class* element_class = reinterpret_cast<mirror::Class*>(args[0])->AsClass();
915 Runtime* runtime = Runtime::Current();
916 ClassLinker* class_linker = runtime->GetClassLinker();
917 mirror::Class* array_class = class_linker->FindArrayClass(self, &element_class);
918 if (UNLIKELY(array_class == NULL)) {
919 CHECK(self->IsExceptionPending());
920 return;
921 }
922 DCHECK(array_class->IsObjectArrayClass());
923 mirror::Array* new_array = mirror::ObjectArray<mirror::Object*>::Alloc(
924 self, array_class, length, runtime->GetHeap()->GetCurrentAllocator());
925 result->SetL(new_array);
926}
927
Andreas Gampe2969bcd2015-03-09 12:57:41 -0700928static void UnstartedJNIThrowableNativeFillInStackTrace(Thread* self,
929 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
930 mirror::Object* receiver ATTRIBUTE_UNUSED,
931 uint32_t* args ATTRIBUTE_UNUSED,
932 JValue* result)
933 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
934 ScopedObjectAccessUnchecked soa(self);
935 if (Runtime::Current()->IsActiveTransaction()) {
936 result->SetL(soa.Decode<mirror::Object*>(self->CreateInternalStackTrace<true>(soa)));
937 } else {
938 result->SetL(soa.Decode<mirror::Object*>(self->CreateInternalStackTrace<false>(soa)));
939 }
940}
941
942static void UnstartedJNISystemIdentityHashCode(Thread* self ATTRIBUTE_UNUSED,
943 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
944 mirror::Object* receiver ATTRIBUTE_UNUSED,
945 uint32_t* args,
946 JValue* result)
947 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
948 mirror::Object* obj = reinterpret_cast<mirror::Object*>(args[0]);
949 result->SetI((obj != nullptr) ? obj->IdentityHashCode() : 0);
950}
951
952static void UnstartedJNIByteOrderIsLittleEndian(Thread* self ATTRIBUTE_UNUSED,
953 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
954 mirror::Object* receiver ATTRIBUTE_UNUSED,
955 uint32_t* args ATTRIBUTE_UNUSED,
956 JValue* result) {
957 result->SetZ(JNI_TRUE);
958}
959
960static void UnstartedJNIUnsafeCompareAndSwapInt(Thread* self ATTRIBUTE_UNUSED,
961 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
962 mirror::Object* receiver ATTRIBUTE_UNUSED,
963 uint32_t* args,
964 JValue* result)
965 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
966 mirror::Object* obj = reinterpret_cast<mirror::Object*>(args[0]);
967 jlong offset = (static_cast<uint64_t>(args[2]) << 32) | args[1];
968 jint expectedValue = args[3];
969 jint newValue = args[4];
970 bool success;
971 if (Runtime::Current()->IsActiveTransaction()) {
972 success = obj->CasFieldStrongSequentiallyConsistent32<true>(MemberOffset(offset),
973 expectedValue, newValue);
974 } else {
975 success = obj->CasFieldStrongSequentiallyConsistent32<false>(MemberOffset(offset),
976 expectedValue, newValue);
977 }
978 result->SetZ(success ? JNI_TRUE : JNI_FALSE);
979}
980
981static void UnstartedJNIUnsafePutObject(Thread* self ATTRIBUTE_UNUSED,
982 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
983 mirror::Object* receiver ATTRIBUTE_UNUSED,
984 uint32_t* args,
985 JValue* result ATTRIBUTE_UNUSED)
986 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
987 mirror::Object* obj = reinterpret_cast<mirror::Object*>(args[0]);
988 jlong offset = (static_cast<uint64_t>(args[2]) << 32) | args[1];
989 mirror::Object* newValue = reinterpret_cast<mirror::Object*>(args[3]);
990 if (Runtime::Current()->IsActiveTransaction()) {
991 obj->SetFieldObject<true>(MemberOffset(offset), newValue);
992 } else {
993 obj->SetFieldObject<false>(MemberOffset(offset), newValue);
994 }
995}
996
997static void UnstartedJNIUnsafeGetArrayBaseOffsetForComponentType(
998 Thread* self ATTRIBUTE_UNUSED,
999 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
1000 mirror::Object* receiver ATTRIBUTE_UNUSED,
1001 uint32_t* args,
1002 JValue* result)
1003 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1004 mirror::Class* component = reinterpret_cast<mirror::Object*>(args[0])->AsClass();
1005 Primitive::Type primitive_type = component->GetPrimitiveType();
1006 result->SetI(mirror::Array::DataOffset(Primitive::ComponentSize(primitive_type)).Int32Value());
1007}
1008
1009static void UnstartedJNIUnsafeGetArrayIndexScaleForComponentType(
1010 Thread* self ATTRIBUTE_UNUSED,
1011 mirror::ArtMethod* method ATTRIBUTE_UNUSED,
1012 mirror::Object* receiver ATTRIBUTE_UNUSED,
1013 uint32_t* args,
1014 JValue* result)
1015 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1016 mirror::Class* component = reinterpret_cast<mirror::Object*>(args[0])->AsClass();
1017 Primitive::Type primitive_type = component->GetPrimitiveType();
1018 result->SetI(Primitive::ComponentSize(primitive_type));
1019}
1020
Andreas Gampedd9d0552015-03-09 12:57:41 -07001021typedef void (*InvokeHandler)(Thread* self, ShadowFrame* shadow_frame, JValue* result,
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001022 size_t arg_size);
1023
Andreas Gampedd9d0552015-03-09 12:57:41 -07001024typedef void (*JNIHandler)(Thread* self, mirror::ArtMethod* method, mirror::Object* receiver,
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001025 uint32_t* args, JValue* result);
1026
1027static bool tables_initialized_ = false;
1028static std::unordered_map<std::string, InvokeHandler> invoke_handlers_;
1029static std::unordered_map<std::string, JNIHandler> jni_handlers_;
1030
1031static void UnstartedRuntimeInitializeInvokeHandlers() {
1032 struct InvokeHandlerDef {
1033 std::string name;
1034 InvokeHandler function;
1035 };
1036
1037 InvokeHandlerDef defs[] {
1038 { "java.lang.Class java.lang.Class.forName(java.lang.String)",
1039 &UnstartedClassForName },
1040 { "java.lang.Class java.lang.Class.forName(java.lang.String, boolean, java.lang.ClassLoader)",
1041 &UnstartedClassForNameLong },
1042 { "java.lang.Class java.lang.Class.classForName(java.lang.String, boolean, java.lang.ClassLoader)",
1043 &UnstartedClassClassForName },
1044 { "java.lang.Class java.lang.VMClassLoader.findLoadedClass(java.lang.ClassLoader, java.lang.String)",
1045 &UnstartedVmClassLoaderFindLoadedClass },
1046 { "java.lang.Class java.lang.Void.lookupType()",
1047 &UnstartedVoidLookupType },
1048 { "java.lang.Object java.lang.Class.newInstance()",
1049 &UnstartedClassNewInstance },
1050 { "java.lang.reflect.Field java.lang.Class.getDeclaredField(java.lang.String)",
1051 &UnstartedClassGetDeclaredField },
1052 { "int java.lang.Object.hashCode()",
1053 &UnstartedObjectHashCode },
1054 { "java.lang.String java.lang.reflect.ArtMethod.getMethodName(java.lang.reflect.ArtMethod)",
1055 &UnstartedArtMethodGetMethodName },
1056 { "void java.lang.System.arraycopy(java.lang.Object, int, java.lang.Object, int, int)",
1057 &UnstartedSystemArraycopy},
1058 { "void java.lang.System.arraycopy(char[], int, char[], int, int)",
1059 &UnstartedSystemArraycopy },
1060 { "void java.lang.System.arraycopy(int[], int, int[], int, int)",
1061 &UnstartedSystemArraycopy },
1062 { "long java.lang.Double.doubleToRawLongBits(double)",
1063 &UnstartedDoubleDoubleToRawLongBits },
1064 { "double java.lang.Math.ceil(double)",
1065 &UnstartedMathCeil },
1066 { "java.lang.Object java.lang.ThreadLocal.get()",
1067 &UnstartedThreadLocalGet },
Andreas Gampedd9d0552015-03-09 12:57:41 -07001068 { "com.android.dex.Dex java.lang.DexCache.getDexNative()",
1069 &UnstartedDexCacheGetDexNative },
1070 { "byte libcore.io.Memory.peekByte(long)",
1071 &UnstartedMemoryPeekEntry },
1072 { "short libcore.io.Memory.peekShortNative(long)",
1073 &UnstartedMemoryPeekEntry },
1074 { "int libcore.io.Memory.peekIntNative(long)",
1075 &UnstartedMemoryPeekEntry },
1076 { "long libcore.io.Memory.peekLongNative(long)",
1077 &UnstartedMemoryPeekEntry },
1078 { "void libcore.io.Memory.peekByteArray(long, byte[], int, int)",
1079 &UnstartedMemoryPeekArrayEntry },
Andreas Gampef778eb22015-04-13 14:17:09 -07001080 { "java.io.Reader java.security.Security.getSecurityPropertiesReader()",
1081 &UnstartedSecurityGetSecurityPropertiesReader },
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001082 };
1083
1084 for (auto& def : defs) {
1085 invoke_handlers_.insert(std::make_pair(def.name, def.function));
1086 }
1087}
1088
1089static void UnstartedRuntimeInitializeJNIHandlers() {
1090 struct JNIHandlerDef {
1091 std::string name;
1092 JNIHandler function;
1093 };
1094
1095 JNIHandlerDef defs[] {
1096 { "java.lang.Object dalvik.system.VMRuntime.newUnpaddedArray(java.lang.Class, int)",
1097 &UnstartedJNIVMRuntimeNewUnpaddedArray },
1098 { "java.lang.ClassLoader dalvik.system.VMStack.getCallingClassLoader()",
1099 &UnstartedJNIVMStackGetCallingClassLoader },
1100 { "java.lang.Class dalvik.system.VMStack.getStackClass2()",
1101 &UnstartedJNIVMStackGetStackClass2 },
1102 { "double java.lang.Math.log(double)",
1103 &UnstartedJNIMathLog },
1104 { "java.lang.String java.lang.Class.getNameNative()",
1105 &UnstartedJNIClassGetNameNative },
1106 { "int java.lang.Float.floatToRawIntBits(float)",
1107 &UnstartedJNIFloatFloatToRawIntBits },
1108 { "float java.lang.Float.intBitsToFloat(int)",
1109 &UnstartedJNIFloatIntBitsToFloat },
1110 { "double java.lang.Math.exp(double)",
1111 &UnstartedJNIMathExp },
1112 { "java.lang.Object java.lang.Object.internalClone()",
1113 &UnstartedJNIObjectInternalClone },
1114 { "void java.lang.Object.notifyAll()",
1115 &UnstartedJNIObjectNotifyAll},
1116 { "int java.lang.String.compareTo(java.lang.String)",
1117 &UnstartedJNIStringCompareTo },
1118 { "java.lang.String java.lang.String.intern()",
1119 &UnstartedJNIStringIntern },
1120 { "int java.lang.String.fastIndexOf(int, int)",
1121 &UnstartedJNIStringFastIndexOf },
1122 { "java.lang.Object java.lang.reflect.Array.createMultiArray(java.lang.Class, int[])",
1123 &UnstartedJNIArrayCreateMultiArray },
Andreas Gampee598e042015-04-10 14:57:10 -07001124 { "java.lang.Object java.lang.reflect.Array.createObjectArray(java.lang.Class, int)",
1125 &UnstartedJNIArrayCreateObjectArray },
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001126 { "java.lang.Object java.lang.Throwable.nativeFillInStackTrace()",
1127 &UnstartedJNIThrowableNativeFillInStackTrace },
1128 { "int java.lang.System.identityHashCode(java.lang.Object)",
1129 &UnstartedJNISystemIdentityHashCode },
1130 { "boolean java.nio.ByteOrder.isLittleEndian()",
1131 &UnstartedJNIByteOrderIsLittleEndian },
1132 { "boolean sun.misc.Unsafe.compareAndSwapInt(java.lang.Object, long, int, int)",
1133 &UnstartedJNIUnsafeCompareAndSwapInt },
1134 { "void sun.misc.Unsafe.putObject(java.lang.Object, long, java.lang.Object)",
1135 &UnstartedJNIUnsafePutObject },
1136 { "int sun.misc.Unsafe.getArrayBaseOffsetForComponentType(java.lang.Class)",
1137 &UnstartedJNIUnsafeGetArrayBaseOffsetForComponentType },
1138 { "int sun.misc.Unsafe.getArrayIndexScaleForComponentType(java.lang.Class)",
1139 &UnstartedJNIUnsafeGetArrayIndexScaleForComponentType },
1140 };
1141
1142 for (auto& def : defs) {
1143 jni_handlers_.insert(std::make_pair(def.name, def.function));
1144 }
1145}
1146
1147void UnstartedRuntimeInitialize() {
1148 CHECK(!tables_initialized_);
1149
1150 UnstartedRuntimeInitializeInvokeHandlers();
1151 UnstartedRuntimeInitializeJNIHandlers();
1152
1153 tables_initialized_ = true;
1154}
1155
1156void UnstartedRuntimeInvoke(Thread* self, const DexFile::CodeItem* code_item,
1157 ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1158 // In a runtime that's not started we intercept certain methods to avoid complicated dependency
1159 // problems in core libraries.
1160 CHECK(tables_initialized_);
1161
1162 std::string name(PrettyMethod(shadow_frame->GetMethod()));
1163 const auto& iter = invoke_handlers_.find(name);
1164 if (iter != invoke_handlers_.end()) {
1165 (*iter->second)(self, shadow_frame, result, arg_offset);
1166 } else {
1167 // Not special, continue with regular interpreter execution.
1168 artInterpreterToInterpreterBridge(self, code_item, shadow_frame, result);
1169 }
1170}
1171
1172// Hand select a number of methods to be run in a not yet started runtime without using JNI.
1173void UnstartedRuntimeJni(Thread* self, mirror::ArtMethod* method, mirror::Object* receiver,
1174 uint32_t* args, JValue* result) {
1175 std::string name(PrettyMethod(method));
1176 const auto& iter = jni_handlers_.find(name);
1177 if (iter != jni_handlers_.end()) {
1178 (*iter->second)(self, method, receiver, args, result);
1179 } else if (Runtime::Current()->IsActiveTransaction()) {
Sebastien Hertz45b15972015-04-03 16:07:05 +02001180 AbortTransactionF(self, "Attempt to invoke native method in non-started runtime: %s",
1181 name.c_str());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001182 } else {
1183 LOG(FATAL) << "Calling native method " << PrettyMethod(method) << " in an unstarted "
1184 "non-transactional runtime";
1185 }
1186}
1187
1188} // namespace interpreter
1189} // namespace art