1 /*
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 <ctype.h>
20 #include <errno.h>
21 #include <stdlib.h>
22
23 #include <cmath>
24 #include <initializer_list>
25 #include <limits>
26 #include <locale>
27
28 #include <android-base/logging.h>
29 #include <android-base/stringprintf.h>
30
31 #include "art_method-inl.h"
32 #include "base/casts.h"
33 #include "base/enums.h"
34 #include "base/hash_map.h"
35 #include "base/macros.h"
36 #include "base/quasi_atomic.h"
37 #include "base/zip_archive.h"
38 #include "class_linker.h"
39 #include "common_throws.h"
40 #include "dex/descriptors_names.h"
41 #include "entrypoints/entrypoint_utils-inl.h"
42 #include "gc/reference_processor.h"
43 #include "handle_scope-inl.h"
44 #include "hidden_api.h"
45 #include "interpreter/interpreter_common.h"
46 #include "jvalue-inl.h"
47 #include "mirror/array-alloc-inl.h"
48 #include "mirror/array-inl.h"
49 #include "mirror/class-alloc-inl.h"
50 #include "mirror/executable-inl.h"
51 #include "mirror/field.h"
52 #include "mirror/method.h"
53 #include "mirror/object-inl.h"
54 #include "mirror/object_array-alloc-inl.h"
55 #include "mirror/object_array-inl.h"
56 #include "mirror/string-alloc-inl.h"
57 #include "mirror/string-inl.h"
58 #include "nativehelper/scoped_local_ref.h"
59 #include "nth_caller_visitor.h"
60 #include "reflection.h"
61 #include "thread-inl.h"
62 #include "transaction.h"
63 #include "unstarted_runtime_list.h"
64 #include "well_known_classes.h"
65
66 namespace art {
67 namespace interpreter {
68
69 using android::base::StringAppendV;
70 using android::base::StringPrintf;
71
72 static void AbortTransactionOrFail(Thread* self, const char* fmt, ...)
73 __attribute__((__format__(__printf__, 2, 3)))
74 REQUIRES_SHARED(Locks::mutator_lock_);
75
AbortTransactionOrFail(Thread * self,const char * fmt,...)76 static void AbortTransactionOrFail(Thread* self, const char* fmt, ...) {
77 va_list args;
78 if (Runtime::Current()->IsActiveTransaction()) {
79 va_start(args, fmt);
80 AbortTransactionV(self, fmt, args);
81 va_end(args);
82 } else {
83 va_start(args, fmt);
84 std::string msg;
85 StringAppendV(&msg, fmt, args);
86 va_end(args);
87 LOG(FATAL) << "Trying to abort, but not in transaction mode: " << msg;
88 UNREACHABLE();
89 }
90 }
91
92 // Restricted support for character upper case / lower case. Only support ASCII, where
93 // it's easy. Abort the transaction otherwise.
CharacterLowerUpper(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset,bool to_lower_case)94 static void CharacterLowerUpper(Thread* self,
95 ShadowFrame* shadow_frame,
96 JValue* result,
97 size_t arg_offset,
98 bool to_lower_case) REQUIRES_SHARED(Locks::mutator_lock_) {
99 uint32_t int_value = static_cast<uint32_t>(shadow_frame->GetVReg(arg_offset));
100
101 // Only ASCII (7-bit).
102 if (!isascii(int_value)) {
103 AbortTransactionOrFail(self,
104 "Only support ASCII characters for toLowerCase/toUpperCase: %u",
105 int_value);
106 return;
107 }
108
109 std::locale c_locale("C");
110 char char_value = static_cast<char>(int_value);
111
112 if (to_lower_case) {
113 result->SetI(std::tolower(char_value, c_locale));
114 } else {
115 result->SetI(std::toupper(char_value, c_locale));
116 }
117 }
118
UnstartedCharacterToLowerCase(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)119 void UnstartedRuntime::UnstartedCharacterToLowerCase(
120 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
121 CharacterLowerUpper(self, shadow_frame, result, arg_offset, true);
122 }
123
UnstartedCharacterToUpperCase(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)124 void UnstartedRuntime::UnstartedCharacterToUpperCase(
125 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
126 CharacterLowerUpper(self, shadow_frame, result, arg_offset, false);
127 }
128
129 // Helper function to deal with class loading in an unstarted runtime.
UnstartedRuntimeFindClass(Thread * self,Handle<mirror::String> className,Handle<mirror::ClassLoader> class_loader,JValue * result,bool initialize_class)130 static void UnstartedRuntimeFindClass(Thread* self,
131 Handle<mirror::String> className,
132 Handle<mirror::ClassLoader> class_loader,
133 JValue* result,
134 bool initialize_class)
135 REQUIRES_SHARED(Locks::mutator_lock_) {
136 CHECK(className != nullptr);
137 std::string descriptor(DotToDescriptor(className->ToModifiedUtf8().c_str()));
138 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
139
140 ObjPtr<mirror::Class> found = class_linker->FindClass(self, descriptor.c_str(), class_loader);
141 if (found != nullptr && initialize_class) {
142 StackHandleScope<1> hs(self);
143 HandleWrapperObjPtr<mirror::Class> h_class = hs.NewHandleWrapper(&found);
144 if (!class_linker->EnsureInitialized(self, h_class, true, true)) {
145 CHECK(self->IsExceptionPending());
146 return;
147 }
148 }
149 result->SetL(found);
150 }
151
152 // Common helper for class-loading cutouts in an unstarted runtime. We call Runtime methods that
153 // rely on Java code to wrap errors in the correct exception class (i.e., NoClassDefFoundError into
154 // ClassNotFoundException), so need to do the same. The only exception is if the exception is
155 // actually the transaction abort exception. This must not be wrapped, as it signals an
156 // initialization abort.
CheckExceptionGenerateClassNotFound(Thread * self)157 static void CheckExceptionGenerateClassNotFound(Thread* self)
158 REQUIRES_SHARED(Locks::mutator_lock_) {
159 if (self->IsExceptionPending()) {
160 Runtime* runtime = Runtime::Current();
161 DCHECK_EQ(runtime->IsTransactionAborted(),
162 self->GetException()->GetClass()->DescriptorEquals(
163 Transaction::kAbortExceptionDescriptor))
164 << self->GetException()->GetClass()->PrettyDescriptor();
165 if (runtime->IsActiveTransaction()) {
166 // The boot class path at run time may contain additional dex files with
167 // the required class definition(s). We cannot throw a normal exception at
168 // compile time because a class initializer could catch it and successfully
169 // initialize a class differently than when executing at run time.
170 // If we're not aborting the transaction yet, abort now. b/183691501
171 if (!runtime->IsTransactionAborted()) {
172 AbortTransactionF(self, "ClassNotFoundException");
173 }
174 } else {
175 // If not in a transaction, it cannot be the transaction abort exception. Wrap it.
176 DCHECK(!runtime->IsTransactionAborted());
177 self->ThrowNewWrappedException("Ljava/lang/ClassNotFoundException;",
178 "ClassNotFoundException");
179 }
180 }
181 }
182
GetClassName(Thread * self,ShadowFrame * shadow_frame,size_t arg_offset)183 static ObjPtr<mirror::String> GetClassName(Thread* self,
184 ShadowFrame* shadow_frame,
185 size_t arg_offset)
186 REQUIRES_SHARED(Locks::mutator_lock_) {
187 mirror::Object* param = shadow_frame->GetVRegReference(arg_offset);
188 if (param == nullptr) {
189 AbortTransactionOrFail(self, "Null-pointer in Class.forName.");
190 return nullptr;
191 }
192 return param->AsString();
193 }
194
GetHiddenapiAccessContextFunction(ShadowFrame * frame)195 static std::function<hiddenapi::AccessContext()> GetHiddenapiAccessContextFunction(
196 ShadowFrame* frame) {
197 return [=]() REQUIRES_SHARED(Locks::mutator_lock_) {
198 return hiddenapi::AccessContext(frame->GetMethod()->GetDeclaringClass());
199 };
200 }
201
202 template<typename T>
ShouldDenyAccessToMember(T * member,ShadowFrame * frame)203 static ALWAYS_INLINE bool ShouldDenyAccessToMember(T* member, ShadowFrame* frame)
204 REQUIRES_SHARED(Locks::mutator_lock_) {
205 // All uses in this file are from reflection
206 constexpr hiddenapi::AccessMethod kAccessMethod = hiddenapi::AccessMethod::kReflection;
207 return hiddenapi::ShouldDenyAccessToMember(member,
208 GetHiddenapiAccessContextFunction(frame),
209 kAccessMethod);
210 }
211
UnstartedClassForNameCommon(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset,bool long_form)212 void UnstartedRuntime::UnstartedClassForNameCommon(Thread* self,
213 ShadowFrame* shadow_frame,
214 JValue* result,
215 size_t arg_offset,
216 bool long_form) {
217 ObjPtr<mirror::String> class_name = GetClassName(self, shadow_frame, arg_offset);
218 if (class_name == nullptr) {
219 return;
220 }
221 bool initialize_class;
222 ObjPtr<mirror::ClassLoader> class_loader;
223 if (long_form) {
224 initialize_class = shadow_frame->GetVReg(arg_offset + 1) != 0;
225 class_loader =
226 ObjPtr<mirror::ClassLoader>::DownCast(shadow_frame->GetVRegReference(arg_offset + 2));
227 } else {
228 initialize_class = true;
229 // TODO: This is really only correct for the boot classpath, and for robustness we should
230 // check the caller.
231 class_loader = nullptr;
232 }
233
234 ScopedObjectAccessUnchecked soa(self);
235 if (class_loader != nullptr && !ClassLinker::IsBootClassLoader(soa, class_loader)) {
236 AbortTransactionOrFail(self,
237 "Only the boot classloader is supported: %s",
238 mirror::Object::PrettyTypeOf(class_loader).c_str());
239 return;
240 }
241
242 StackHandleScope<1> hs(self);
243 Handle<mirror::String> h_class_name(hs.NewHandle(class_name));
244 UnstartedRuntimeFindClass(self,
245 h_class_name,
246 ScopedNullHandle<mirror::ClassLoader>(),
247 result,
248 initialize_class);
249 CheckExceptionGenerateClassNotFound(self);
250 }
251
UnstartedClassForName(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)252 void UnstartedRuntime::UnstartedClassForName(
253 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
254 UnstartedClassForNameCommon(self, shadow_frame, result, arg_offset, /*long_form=*/ false);
255 }
256
UnstartedClassForNameLong(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)257 void UnstartedRuntime::UnstartedClassForNameLong(
258 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
259 UnstartedClassForNameCommon(self, shadow_frame, result, arg_offset, /*long_form=*/ true);
260 }
261
UnstartedClassGetPrimitiveClass(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)262 void UnstartedRuntime::UnstartedClassGetPrimitiveClass(
263 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
264 ObjPtr<mirror::String> class_name = GetClassName(self, shadow_frame, arg_offset);
265 ObjPtr<mirror::Class> klass = mirror::Class::GetPrimitiveClass(class_name);
266 if (UNLIKELY(klass == nullptr)) {
267 DCHECK(self->IsExceptionPending());
268 AbortTransactionOrFail(self,
269 "Class.getPrimitiveClass() failed: %s",
270 self->GetException()->GetDetailMessage()->ToModifiedUtf8().c_str());
271 return;
272 }
273 result->SetL(klass);
274 }
275
UnstartedClassClassForName(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)276 void UnstartedRuntime::UnstartedClassClassForName(
277 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
278 UnstartedClassForNameCommon(self, shadow_frame, result, arg_offset, /*long_form=*/ true);
279 }
280
UnstartedClassNewInstance(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)281 void UnstartedRuntime::UnstartedClassNewInstance(
282 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
283 StackHandleScope<2> hs(self); // Class, constructor, object.
284 mirror::Object* param = shadow_frame->GetVRegReference(arg_offset);
285 if (param == nullptr) {
286 AbortTransactionOrFail(self, "Null-pointer in Class.newInstance.");
287 return;
288 }
289 Handle<mirror::Class> h_klass(hs.NewHandle(param->AsClass()));
290
291 // Check that it's not null.
292 if (h_klass == nullptr) {
293 AbortTransactionOrFail(self, "Class reference is null for newInstance");
294 return;
295 }
296
297 // If we're in a transaction, class must not be finalizable (it or a superclass has a finalizer).
298 if (Runtime::Current()->IsActiveTransaction()) {
299 if (h_klass->IsFinalizable()) {
300 AbortTransactionF(self, "Class for newInstance is finalizable: '%s'",
301 h_klass->PrettyClass().c_str());
302 return;
303 }
304 }
305
306 // There are two situations in which we'll abort this run.
307 // 1) If the class isn't yet initialized and initialization fails.
308 // 2) If we can't find the default constructor. We'll postpone the exception to runtime.
309 // Note that 2) could likely be handled here, but for safety abort the transaction.
310 bool ok = false;
311 auto* cl = Runtime::Current()->GetClassLinker();
312 if (cl->EnsureInitialized(self, h_klass, true, true)) {
313 ArtMethod* cons = h_klass->FindConstructor("()V", cl->GetImagePointerSize());
314 if (cons != nullptr && ShouldDenyAccessToMember(cons, shadow_frame)) {
315 cons = nullptr;
316 }
317 if (cons != nullptr) {
318 Handle<mirror::Object> h_obj(hs.NewHandle(h_klass->AllocObject(self)));
319 CHECK(h_obj != nullptr); // We don't expect OOM at compile-time.
320 EnterInterpreterFromInvoke(self, cons, h_obj.Get(), nullptr, nullptr);
321 if (!self->IsExceptionPending()) {
322 result->SetL(h_obj.Get());
323 ok = true;
324 }
325 } else {
326 self->ThrowNewExceptionF("Ljava/lang/InternalError;",
327 "Could not find default constructor for '%s'",
328 h_klass->PrettyClass().c_str());
329 }
330 }
331 if (!ok) {
332 AbortTransactionOrFail(self, "Failed in Class.newInstance for '%s' with %s",
333 h_klass->PrettyClass().c_str(),
334 mirror::Object::PrettyTypeOf(self->GetException()).c_str());
335 }
336 }
337
UnstartedClassGetDeclaredField(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)338 void UnstartedRuntime::UnstartedClassGetDeclaredField(
339 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
340 // Special managed code cut-out to allow field lookup in a un-started runtime that'd fail
341 // going the reflective Dex way.
342 ObjPtr<mirror::Class> klass = shadow_frame->GetVRegReference(arg_offset)->AsClass();
343 ObjPtr<mirror::String> name2 = shadow_frame->GetVRegReference(arg_offset + 1)->AsString();
344 ArtField* found = nullptr;
345 for (ArtField& field : klass->GetIFields()) {
346 if (name2->Equals(field.GetName())) {
347 found = &field;
348 break;
349 }
350 }
351 if (found == nullptr) {
352 for (ArtField& field : klass->GetSFields()) {
353 if (name2->Equals(field.GetName())) {
354 found = &field;
355 break;
356 }
357 }
358 }
359 if (found != nullptr && ShouldDenyAccessToMember(found, shadow_frame)) {
360 found = nullptr;
361 }
362 if (found == nullptr) {
363 AbortTransactionOrFail(self, "Failed to find field in Class.getDeclaredField in un-started "
364 " runtime. name=%s class=%s", name2->ToModifiedUtf8().c_str(),
365 klass->PrettyDescriptor().c_str());
366 return;
367 }
368 ObjPtr<mirror::Field> field = mirror::Field::CreateFromArtField(self, found, true);
369 result->SetL(field);
370 }
371
UnstartedClassGetDeclaredFields(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)372 void UnstartedRuntime::UnstartedClassGetDeclaredFields(
373 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
374 // Special managed code cut-out to allow field lookup in a un-started runtime that'd fail
375 // going the reflective Dex way.
376 ObjPtr<mirror::Class> klass = shadow_frame->GetVRegReference(arg_offset)->AsClass();
377 auto object_array = klass->GetDeclaredFields(self,
378 /*public_only=*/ false,
379 /*force_resolve=*/ true);
380 if (object_array != nullptr) {
381 result->SetL(object_array);
382 }
383 }
384
UnstartedClassGetPublicDeclaredFields(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)385 void UnstartedRuntime::UnstartedClassGetPublicDeclaredFields(
386 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
387 ObjPtr<mirror::Class> klass = shadow_frame->GetVRegReference(arg_offset)->AsClass();
388 auto object_array = klass->GetDeclaredFields(self,
389 /*public_only=*/ true,
390 /*force_resolve=*/ true);
391 if (object_array != nullptr) {
392 result->SetL(object_array);
393 }
394 }
395
396 // This is required for Enum(Set) code, as that uses reflection to inspect enum classes.
UnstartedClassGetDeclaredMethod(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)397 void UnstartedRuntime::UnstartedClassGetDeclaredMethod(
398 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
399 // Special managed code cut-out to allow method lookup in a un-started runtime.
400 ObjPtr<mirror::Class> klass = shadow_frame->GetVRegReference(arg_offset)->AsClass();
401 if (klass == nullptr) {
402 ThrowNullPointerExceptionForMethodAccess(shadow_frame->GetMethod(), InvokeType::kVirtual);
403 return;
404 }
405 ObjPtr<mirror::String> name = shadow_frame->GetVRegReference(arg_offset + 1)->AsString();
406 ObjPtr<mirror::ObjectArray<mirror::Class>> args =
407 shadow_frame->GetVRegReference(arg_offset + 2)->AsObjectArray<mirror::Class>();
408 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
409 auto fn_hiddenapi_access_context = GetHiddenapiAccessContextFunction(shadow_frame);
410 ObjPtr<mirror::Method> method = (pointer_size == PointerSize::k64)
411 ? mirror::Class::GetDeclaredMethodInternal<PointerSize::k64>(
412 self, klass, name, args, fn_hiddenapi_access_context)
413 : mirror::Class::GetDeclaredMethodInternal<PointerSize::k32>(
414 self, klass, name, args, fn_hiddenapi_access_context);
415 if (method != nullptr && ShouldDenyAccessToMember(method->GetArtMethod(), shadow_frame)) {
416 method = nullptr;
417 }
418 result->SetL(method);
419 }
420
421 // Special managed code cut-out to allow constructor lookup in a un-started runtime.
UnstartedClassGetDeclaredConstructor(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)422 void UnstartedRuntime::UnstartedClassGetDeclaredConstructor(
423 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
424 ObjPtr<mirror::Class> klass = shadow_frame->GetVRegReference(arg_offset)->AsClass();
425 if (klass == nullptr) {
426 ThrowNullPointerExceptionForMethodAccess(shadow_frame->GetMethod(), InvokeType::kVirtual);
427 return;
428 }
429 ObjPtr<mirror::ObjectArray<mirror::Class>> args =
430 shadow_frame->GetVRegReference(arg_offset + 1)->AsObjectArray<mirror::Class>();
431 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
432 ObjPtr<mirror::Constructor> constructor = (pointer_size == PointerSize::k64)
433 ? mirror::Class::GetDeclaredConstructorInternal<PointerSize::k64>(self, klass, args)
434 : mirror::Class::GetDeclaredConstructorInternal<PointerSize::k32>(self, klass, args);
435 if (constructor != nullptr &&
436 ShouldDenyAccessToMember(constructor->GetArtMethod(), shadow_frame)) {
437 constructor = nullptr;
438 }
439 result->SetL(constructor);
440 }
441
UnstartedClassGetDeclaringClass(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)442 void UnstartedRuntime::UnstartedClassGetDeclaringClass(
443 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
444 StackHandleScope<1> hs(self);
445 Handle<mirror::Class> klass(hs.NewHandle(
446 reinterpret_cast<mirror::Class*>(shadow_frame->GetVRegReference(arg_offset))));
447 if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
448 result->SetL(nullptr);
449 return;
450 }
451 // Return null for anonymous classes.
452 JValue is_anon_result;
453 UnstartedClassIsAnonymousClass(self, shadow_frame, &is_anon_result, arg_offset);
454 if (is_anon_result.GetZ() != 0) {
455 result->SetL(nullptr);
456 return;
457 }
458 result->SetL(annotations::GetDeclaringClass(klass));
459 }
460
UnstartedClassGetEnclosingClass(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)461 void UnstartedRuntime::UnstartedClassGetEnclosingClass(
462 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
463 StackHandleScope<1> hs(self);
464 Handle<mirror::Class> klass(hs.NewHandle(shadow_frame->GetVRegReference(arg_offset)->AsClass()));
465 if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
466 result->SetL(nullptr);
467 }
468 result->SetL(annotations::GetEnclosingClass(klass));
469 }
470
UnstartedClassGetInnerClassFlags(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)471 void UnstartedRuntime::UnstartedClassGetInnerClassFlags(
472 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
473 StackHandleScope<1> hs(self);
474 Handle<mirror::Class> klass(hs.NewHandle(
475 reinterpret_cast<mirror::Class*>(shadow_frame->GetVRegReference(arg_offset))));
476 const int32_t default_value = shadow_frame->GetVReg(arg_offset + 1);
477 result->SetI(mirror::Class::GetInnerClassFlags(klass, default_value));
478 }
479
UnstartedClassGetSignatureAnnotation(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)480 void UnstartedRuntime::UnstartedClassGetSignatureAnnotation(
481 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
482 StackHandleScope<1> hs(self);
483 Handle<mirror::Class> klass(hs.NewHandle(
484 reinterpret_cast<mirror::Class*>(shadow_frame->GetVRegReference(arg_offset))));
485
486 if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
487 result->SetL(nullptr);
488 return;
489 }
490
491 result->SetL(annotations::GetSignatureAnnotationForClass(klass));
492 }
493
UnstartedClassIsAnonymousClass(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)494 void UnstartedRuntime::UnstartedClassIsAnonymousClass(
495 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
496 StackHandleScope<1> hs(self);
497 Handle<mirror::Class> klass(hs.NewHandle(
498 reinterpret_cast<mirror::Class*>(shadow_frame->GetVRegReference(arg_offset))));
499 if (klass->IsProxyClass() || klass->GetDexCache() == nullptr) {
500 result->SetZ(false);
501 return;
502 }
503 ObjPtr<mirror::String> class_name = nullptr;
504 if (!annotations::GetInnerClass(klass, &class_name)) {
505 result->SetZ(false);
506 return;
507 }
508 result->SetZ(class_name == nullptr);
509 }
510
FindAndExtractEntry(const std::string & bcp_jar_file,int jar_fd,const char * entry_name,size_t * size,std::string * error_msg)511 static MemMap FindAndExtractEntry(const std::string& bcp_jar_file,
512 int jar_fd,
513 const char* entry_name,
514 size_t* size,
515 std::string* error_msg) {
516 CHECK(size != nullptr);
517
518 std::unique_ptr<ZipArchive> zip_archive;
519 if (jar_fd >= 0) {
520 zip_archive.reset(ZipArchive::OpenFromOwnedFd(jar_fd, bcp_jar_file.c_str(), error_msg));
521 } else {
522 zip_archive.reset(ZipArchive::Open(bcp_jar_file.c_str(), error_msg));
523 }
524 if (zip_archive == nullptr) {
525 return MemMap::Invalid();
526 }
527 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(entry_name, error_msg));
528 if (zip_entry == nullptr) {
529 return MemMap::Invalid();
530 }
531 MemMap tmp_map = zip_entry->ExtractToMemMap(bcp_jar_file.c_str(), entry_name, error_msg);
532 if (!tmp_map.IsValid()) {
533 return MemMap::Invalid();
534 }
535
536 // OK, from here everything seems fine.
537 *size = zip_entry->GetUncompressedLength();
538 return tmp_map;
539 }
540
GetResourceAsStream(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)541 static void GetResourceAsStream(Thread* self,
542 ShadowFrame* shadow_frame,
543 JValue* result,
544 size_t arg_offset) REQUIRES_SHARED(Locks::mutator_lock_) {
545 mirror::Object* resource_obj = shadow_frame->GetVRegReference(arg_offset + 1);
546 if (resource_obj == nullptr) {
547 AbortTransactionOrFail(self, "null name for getResourceAsStream");
548 return;
549 }
550 CHECK(resource_obj->IsString());
551 ObjPtr<mirror::String> resource_name = resource_obj->AsString();
552
553 std::string resource_name_str = resource_name->ToModifiedUtf8();
554 if (resource_name_str.empty() || resource_name_str == "/") {
555 AbortTransactionOrFail(self,
556 "Unsupported name %s for getResourceAsStream",
557 resource_name_str.c_str());
558 return;
559 }
560 const char* resource_cstr = resource_name_str.c_str();
561 if (resource_cstr[0] == '/') {
562 resource_cstr++;
563 }
564
565 Runtime* runtime = Runtime::Current();
566
567 const std::vector<std::string>& boot_class_path = Runtime::Current()->GetBootClassPath();
568 if (boot_class_path.empty()) {
569 AbortTransactionOrFail(self, "Boot classpath not set");
570 return;
571 }
572
573 const std::vector<int>& boot_class_path_fds = Runtime::Current()->GetBootClassPathFds();
574 DCHECK(boot_class_path_fds.empty() || boot_class_path_fds.size() == boot_class_path.size());
575
576 MemMap mem_map;
577 size_t map_size;
578 std::string last_error_msg; // Only store the last message (we could concatenate).
579
580 bool has_bcp_fds = !boot_class_path_fds.empty();
581 for (size_t i = 0; i < boot_class_path.size(); ++i) {
582 const std::string& jar_file = boot_class_path[i];
583 const int jar_fd = has_bcp_fds ? boot_class_path_fds[i] : -1;
584 mem_map = FindAndExtractEntry(jar_file, jar_fd, resource_cstr, &map_size, &last_error_msg);
585 if (mem_map.IsValid()) {
586 break;
587 }
588 }
589
590 if (!mem_map.IsValid()) {
591 // Didn't find it. There's a good chance this will be the same at runtime, but still
592 // conservatively abort the transaction here.
593 AbortTransactionOrFail(self,
594 "Could not find resource %s. Last error was %s.",
595 resource_name_str.c_str(),
596 last_error_msg.c_str());
597 return;
598 }
599
600 StackHandleScope<3> hs(self);
601
602 // Create byte array for content.
603 Handle<mirror::ByteArray> h_array(hs.NewHandle(mirror::ByteArray::Alloc(self, map_size)));
604 if (h_array == nullptr) {
605 AbortTransactionOrFail(self, "Could not find/create byte array class");
606 return;
607 }
608 // Copy in content.
609 memcpy(h_array->GetData(), mem_map.Begin(), map_size);
610 // Be proactive releasing memory.
611 mem_map.Reset();
612
613 // Create a ByteArrayInputStream.
614 Handle<mirror::Class> h_class(hs.NewHandle(
615 runtime->GetClassLinker()->FindClass(self,
616 "Ljava/io/ByteArrayInputStream;",
617 ScopedNullHandle<mirror::ClassLoader>())));
618 if (h_class == nullptr) {
619 AbortTransactionOrFail(self, "Could not find ByteArrayInputStream class");
620 return;
621 }
622 if (!runtime->GetClassLinker()->EnsureInitialized(self, h_class, true, true)) {
623 AbortTransactionOrFail(self, "Could not initialize ByteArrayInputStream class");
624 return;
625 }
626
627 Handle<mirror::Object> h_obj(hs.NewHandle(h_class->AllocObject(self)));
628 if (h_obj == nullptr) {
629 AbortTransactionOrFail(self, "Could not allocate ByteArrayInputStream object");
630 return;
631 }
632
633 auto* cl = Runtime::Current()->GetClassLinker();
634 ArtMethod* constructor = h_class->FindConstructor("([B)V", cl->GetImagePointerSize());
635 if (constructor == nullptr) {
636 AbortTransactionOrFail(self, "Could not find ByteArrayInputStream constructor");
637 return;
638 }
639
640 uint32_t args[1];
641 args[0] = reinterpret_cast32<uint32_t>(h_array.Get());
642 EnterInterpreterFromInvoke(self, constructor, h_obj.Get(), args, nullptr);
643
644 if (self->IsExceptionPending()) {
645 AbortTransactionOrFail(self, "Could not run ByteArrayInputStream constructor");
646 return;
647 }
648
649 result->SetL(h_obj.Get());
650 }
651
UnstartedClassLoaderGetResourceAsStream(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)652 void UnstartedRuntime::UnstartedClassLoaderGetResourceAsStream(
653 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
654 {
655 mirror::Object* this_obj = shadow_frame->GetVRegReference(arg_offset);
656 CHECK(this_obj != nullptr);
657 CHECK(this_obj->IsClassLoader());
658
659 StackHandleScope<1> hs(self);
660 Handle<mirror::Class> this_classloader_class(hs.NewHandle(this_obj->GetClass()));
661
662 if (self->DecodeJObject(WellKnownClasses::java_lang_BootClassLoader) !=
663 this_classloader_class.Get()) {
664 AbortTransactionOrFail(self,
665 "Unsupported classloader type %s for getResourceAsStream",
666 mirror::Class::PrettyClass(this_classloader_class.Get()).c_str());
667 return;
668 }
669 }
670
671 GetResourceAsStream(self, shadow_frame, result, arg_offset);
672 }
673
UnstartedConstructorNewInstance0(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)674 void UnstartedRuntime::UnstartedConstructorNewInstance0(
675 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
676 // This is a cutdown version of java_lang_reflect_Constructor.cc's implementation.
677 StackHandleScope<4> hs(self);
678 Handle<mirror::Constructor> m = hs.NewHandle(
679 reinterpret_cast<mirror::Constructor*>(shadow_frame->GetVRegReference(arg_offset)));
680 Handle<mirror::ObjectArray<mirror::Object>> args = hs.NewHandle(
681 reinterpret_cast<mirror::ObjectArray<mirror::Object>*>(
682 shadow_frame->GetVRegReference(arg_offset + 1)));
683 Handle<mirror::Class> c(hs.NewHandle(m->GetDeclaringClass()));
684 if (UNLIKELY(c->IsAbstract())) {
685 AbortTransactionOrFail(self, "Cannot handle abstract classes");
686 return;
687 }
688 // Verify that we can access the class.
689 if (!m->IsAccessible() && !c->IsPublic()) {
690 // Go 2 frames back, this method is always called from newInstance0, which is called from
691 // Constructor.newInstance(Object... args).
692 ObjPtr<mirror::Class> caller = GetCallingClass(self, 2);
693 // If caller is null, then we called from JNI, just avoid the check since JNI avoids most
694 // access checks anyways. TODO: Investigate if this the correct behavior.
695 if (caller != nullptr && !caller->CanAccess(c.Get())) {
696 AbortTransactionOrFail(self, "Cannot access class");
697 return;
698 }
699 }
700 if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, c, true, true)) {
701 DCHECK(self->IsExceptionPending());
702 return;
703 }
704 if (c->IsClassClass()) {
705 AbortTransactionOrFail(self, "new Class() is not supported");
706 return;
707 }
708
709 // String constructor is replaced by a StringFactory method in InvokeMethod.
710 if (c->IsStringClass()) {
711 // We don't support strings.
712 AbortTransactionOrFail(self, "String construction is not supported");
713 return;
714 }
715
716 Handle<mirror::Object> receiver = hs.NewHandle(c->AllocObject(self));
717 if (receiver == nullptr) {
718 AbortTransactionOrFail(self, "Could not allocate");
719 return;
720 }
721
722 // It's easier to use reflection to make the call, than create the uint32_t array.
723 {
724 ScopedObjectAccessUnchecked soa(self);
725 ScopedLocalRef<jobject> method_ref(self->GetJniEnv(),
726 soa.AddLocalReference<jobject>(m.Get()));
727 ScopedLocalRef<jobject> object_ref(self->GetJniEnv(),
728 soa.AddLocalReference<jobject>(receiver.Get()));
729 ScopedLocalRef<jobject> args_ref(self->GetJniEnv(),
730 soa.AddLocalReference<jobject>(args.Get()));
731 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
732 if (pointer_size == PointerSize::k64) {
733 InvokeMethod<PointerSize::k64>(soa, method_ref.get(), object_ref.get(), args_ref.get(), 2);
734 } else {
735 InvokeMethod<PointerSize::k32>(soa, method_ref.get(), object_ref.get(), args_ref.get(), 2);
736 }
737 }
738 if (self->IsExceptionPending()) {
739 AbortTransactionOrFail(self, "Failed running constructor");
740 } else {
741 result->SetL(receiver.Get());
742 }
743 }
744
UnstartedVmClassLoaderFindLoadedClass(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)745 void UnstartedRuntime::UnstartedVmClassLoaderFindLoadedClass(
746 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
747 ObjPtr<mirror::String> class_name = shadow_frame->GetVRegReference(arg_offset + 1)->AsString();
748 ObjPtr<mirror::ClassLoader> class_loader =
749 ObjPtr<mirror::ClassLoader>::DownCast(shadow_frame->GetVRegReference(arg_offset));
750 StackHandleScope<2> hs(self);
751 Handle<mirror::String> h_class_name(hs.NewHandle(class_name));
752 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
753 UnstartedRuntimeFindClass(self,
754 h_class_name,
755 h_class_loader,
756 result,
757 /*initialize_class=*/ false);
758 // This might have an error pending. But semantics are to just return null.
759 if (self->IsExceptionPending()) {
760 Runtime* runtime = Runtime::Current();
761 DCHECK_EQ(runtime->IsTransactionAborted(),
762 self->GetException()->GetClass()->DescriptorEquals(
763 Transaction::kAbortExceptionDescriptor))
764 << self->GetException()->GetClass()->PrettyDescriptor();
765 if (runtime->IsActiveTransaction()) {
766 // If we're not aborting the transaction yet, abort now. b/183691501
767 // See CheckExceptionGenerateClassNotFound() for more detailed explanation.
768 if (!runtime->IsTransactionAborted()) {
769 AbortTransactionF(self, "ClassNotFoundException");
770 }
771 } else {
772 // If not in a transaction, it cannot be the transaction abort exception. Clear it.
773 DCHECK(!runtime->IsTransactionAborted());
774 self->ClearException();
775 }
776 }
777 }
778
779 // Arraycopy emulation.
780 // Note: we can't use any fast copy functions, as they are not available under transaction.
781
782 template <typename T>
PrimitiveArrayCopy(Thread * self,ObjPtr<mirror::Array> src_array,int32_t src_pos,ObjPtr<mirror::Array> dst_array,int32_t dst_pos,int32_t length)783 static void PrimitiveArrayCopy(Thread* self,
784 ObjPtr<mirror::Array> src_array,
785 int32_t src_pos,
786 ObjPtr<mirror::Array> dst_array,
787 int32_t dst_pos,
788 int32_t length)
789 REQUIRES_SHARED(Locks::mutator_lock_) {
790 if (src_array->GetClass()->GetComponentType() != dst_array->GetClass()->GetComponentType()) {
791 AbortTransactionOrFail(self,
792 "Types mismatched in arraycopy: %s vs %s.",
793 mirror::Class::PrettyDescriptor(
794 src_array->GetClass()->GetComponentType()).c_str(),
795 mirror::Class::PrettyDescriptor(
796 dst_array->GetClass()->GetComponentType()).c_str());
797 return;
798 }
799 ObjPtr<mirror::PrimitiveArray<T>> src = ObjPtr<mirror::PrimitiveArray<T>>::DownCast(src_array);
800 ObjPtr<mirror::PrimitiveArray<T>> dst = ObjPtr<mirror::PrimitiveArray<T>>::DownCast(dst_array);
801 const bool copy_forward = (dst_pos < src_pos) || (dst_pos - src_pos >= length);
802 if (copy_forward) {
803 for (int32_t i = 0; i < length; ++i) {
804 dst->Set(dst_pos + i, src->Get(src_pos + i));
805 }
806 } else {
807 for (int32_t i = 1; i <= length; ++i) {
808 dst->Set(dst_pos + length - i, src->Get(src_pos + length - i));
809 }
810 }
811 }
812
UnstartedSystemArraycopy(Thread * self,ShadowFrame * shadow_frame,JValue * result ATTRIBUTE_UNUSED,size_t arg_offset)813 void UnstartedRuntime::UnstartedSystemArraycopy(
814 Thread* self, ShadowFrame* shadow_frame, JValue* result ATTRIBUTE_UNUSED, size_t arg_offset) {
815 // Special case array copying without initializing System.
816 jint src_pos = shadow_frame->GetVReg(arg_offset + 1);
817 jint dst_pos = shadow_frame->GetVReg(arg_offset + 3);
818 jint length = shadow_frame->GetVReg(arg_offset + 4);
819
820 mirror::Object* src_obj = shadow_frame->GetVRegReference(arg_offset);
821 mirror::Object* dst_obj = shadow_frame->GetVRegReference(arg_offset + 2);
822 // Null checking. For simplicity, abort transaction.
823 if (src_obj == nullptr) {
824 AbortTransactionOrFail(self, "src is null in arraycopy.");
825 return;
826 }
827 if (dst_obj == nullptr) {
828 AbortTransactionOrFail(self, "dst is null in arraycopy.");
829 return;
830 }
831 // Test for arrayness. Throw ArrayStoreException.
832 if (!src_obj->IsArrayInstance() || !dst_obj->IsArrayInstance()) {
833 self->ThrowNewException("Ljava/lang/ArrayStoreException;", "src or trg is not an array");
834 return;
835 }
836
837 ObjPtr<mirror::Array> src_array = src_obj->AsArray();
838 ObjPtr<mirror::Array> dst_array = dst_obj->AsArray();
839
840 // Bounds checking. Throw IndexOutOfBoundsException.
841 if (UNLIKELY(src_pos < 0) || UNLIKELY(dst_pos < 0) || UNLIKELY(length < 0) ||
842 UNLIKELY(src_pos > src_array->GetLength() - length) ||
843 UNLIKELY(dst_pos > dst_array->GetLength() - length)) {
844 self->ThrowNewExceptionF("Ljava/lang/IndexOutOfBoundsException;",
845 "src.length=%d srcPos=%d dst.length=%d dstPos=%d length=%d",
846 src_array->GetLength(), src_pos, dst_array->GetLength(), dst_pos,
847 length);
848 return;
849 }
850
851 if (Runtime::Current()->IsActiveTransaction() && !CheckWriteConstraint(self, dst_obj)) {
852 DCHECK(self->IsExceptionPending());
853 return;
854 }
855
856 // Type checking.
857 ObjPtr<mirror::Class> src_type = shadow_frame->GetVRegReference(arg_offset)->GetClass()->
858 GetComponentType();
859
860 if (!src_type->IsPrimitive()) {
861 // Check that the second type is not primitive.
862 ObjPtr<mirror::Class> trg_type = shadow_frame->GetVRegReference(arg_offset + 2)->GetClass()->
863 GetComponentType();
864 if (trg_type->IsPrimitiveInt()) {
865 AbortTransactionOrFail(self, "Type mismatch in arraycopy: %s vs %s",
866 mirror::Class::PrettyDescriptor(
867 src_array->GetClass()->GetComponentType()).c_str(),
868 mirror::Class::PrettyDescriptor(
869 dst_array->GetClass()->GetComponentType()).c_str());
870 return;
871 }
872
873 ObjPtr<mirror::ObjectArray<mirror::Object>> src = src_array->AsObjectArray<mirror::Object>();
874 ObjPtr<mirror::ObjectArray<mirror::Object>> dst = dst_array->AsObjectArray<mirror::Object>();
875 if (src == dst) {
876 // Can overlap, but not have type mismatches.
877 // We cannot use ObjectArray::MemMove here, as it doesn't support transactions.
878 const bool copy_forward = (dst_pos < src_pos) || (dst_pos - src_pos >= length);
879 if (copy_forward) {
880 for (int32_t i = 0; i < length; ++i) {
881 dst->Set(dst_pos + i, src->Get(src_pos + i));
882 }
883 } else {
884 for (int32_t i = 1; i <= length; ++i) {
885 dst->Set(dst_pos + length - i, src->Get(src_pos + length - i));
886 }
887 }
888 } else {
889 // We're being lazy here. Optimally this could be a memcpy (if component types are
890 // assignable), but the ObjectArray implementation doesn't support transactions. The
891 // checking version, however, does.
892 if (Runtime::Current()->IsActiveTransaction()) {
893 dst->AssignableCheckingMemcpy<true>(
894 dst_pos, src, src_pos, length, /* throw_exception= */ true);
895 } else {
896 dst->AssignableCheckingMemcpy<false>(
897 dst_pos, src, src_pos, length, /* throw_exception= */ true);
898 }
899 }
900 } else if (src_type->IsPrimitiveByte()) {
901 PrimitiveArrayCopy<uint8_t>(self, src_array, src_pos, dst_array, dst_pos, length);
902 } else if (src_type->IsPrimitiveChar()) {
903 PrimitiveArrayCopy<uint16_t>(self, src_array, src_pos, dst_array, dst_pos, length);
904 } else if (src_type->IsPrimitiveInt()) {
905 PrimitiveArrayCopy<int32_t>(self, src_array, src_pos, dst_array, dst_pos, length);
906 } else {
907 AbortTransactionOrFail(self, "Unimplemented System.arraycopy for type '%s'",
908 src_type->PrettyDescriptor().c_str());
909 }
910 }
911
UnstartedSystemArraycopyByte(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)912 void UnstartedRuntime::UnstartedSystemArraycopyByte(
913 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
914 // Just forward.
915 UnstartedRuntime::UnstartedSystemArraycopy(self, shadow_frame, result, arg_offset);
916 }
917
UnstartedSystemArraycopyChar(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)918 void UnstartedRuntime::UnstartedSystemArraycopyChar(
919 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
920 // Just forward.
921 UnstartedRuntime::UnstartedSystemArraycopy(self, shadow_frame, result, arg_offset);
922 }
923
UnstartedSystemArraycopyInt(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)924 void UnstartedRuntime::UnstartedSystemArraycopyInt(
925 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
926 // Just forward.
927 UnstartedRuntime::UnstartedSystemArraycopy(self, shadow_frame, result, arg_offset);
928 }
929
UnstartedSystemGetSecurityManager(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame ATTRIBUTE_UNUSED,JValue * result,size_t arg_offset ATTRIBUTE_UNUSED)930 void UnstartedRuntime::UnstartedSystemGetSecurityManager(
931 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame ATTRIBUTE_UNUSED,
932 JValue* result, size_t arg_offset ATTRIBUTE_UNUSED) {
933 result->SetL(nullptr);
934 }
935
936 static constexpr const char* kAndroidHardcodedSystemPropertiesFieldName = "STATIC_PROPERTIES";
937
GetSystemProperty(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset,bool is_default_version)938 static void GetSystemProperty(Thread* self,
939 ShadowFrame* shadow_frame,
940 JValue* result,
941 size_t arg_offset,
942 bool is_default_version)
943 REQUIRES_SHARED(Locks::mutator_lock_) {
944 StackHandleScope<4> hs(self);
945 Handle<mirror::String> h_key(
946 hs.NewHandle(reinterpret_cast<mirror::String*>(shadow_frame->GetVRegReference(arg_offset))));
947 if (h_key == nullptr) {
948 AbortTransactionOrFail(self, "getProperty key was null");
949 return;
950 }
951
952 // This is overall inefficient, but reflecting the values here is not great, either. So
953 // for simplicity, and with the assumption that the number of getProperty calls is not
954 // too great, just iterate each time.
955
956 // Get the storage class.
957 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
958 Handle<mirror::Class> h_props_class(hs.NewHandle(
959 class_linker->FindClass(self,
960 "Ljava/lang/AndroidHardcodedSystemProperties;",
961 ScopedNullHandle<mirror::ClassLoader>())));
962 if (h_props_class == nullptr) {
963 AbortTransactionOrFail(self, "Could not find AndroidHardcodedSystemProperties");
964 return;
965 }
966 if (!class_linker->EnsureInitialized(self, h_props_class, true, true)) {
967 AbortTransactionOrFail(self, "Could not initialize AndroidHardcodedSystemProperties");
968 return;
969 }
970
971 // Get the storage array.
972 ArtField* static_properties =
973 h_props_class->FindDeclaredStaticField(kAndroidHardcodedSystemPropertiesFieldName,
974 "[[Ljava/lang/String;");
975 if (static_properties == nullptr) {
976 AbortTransactionOrFail(self,
977 "Could not find %s field",
978 kAndroidHardcodedSystemPropertiesFieldName);
979 return;
980 }
981 ObjPtr<mirror::Object> props = static_properties->GetObject(h_props_class.Get());
982 Handle<mirror::ObjectArray<mirror::ObjectArray<mirror::String>>> h_2string_array(hs.NewHandle(
983 props->AsObjectArray<mirror::ObjectArray<mirror::String>>()));
984 if (h_2string_array == nullptr) {
985 AbortTransactionOrFail(self, "Field %s is null", kAndroidHardcodedSystemPropertiesFieldName);
986 return;
987 }
988
989 // Iterate over it.
990 const int32_t prop_count = h_2string_array->GetLength();
991 // Use the third handle as mutable.
992 MutableHandle<mirror::ObjectArray<mirror::String>> h_string_array(
993 hs.NewHandle<mirror::ObjectArray<mirror::String>>(nullptr));
994 for (int32_t i = 0; i < prop_count; ++i) {
995 h_string_array.Assign(h_2string_array->Get(i));
996 if (h_string_array == nullptr ||
997 h_string_array->GetLength() != 2 ||
998 h_string_array->Get(0) == nullptr) {
999 AbortTransactionOrFail(self,
1000 "Unexpected content of %s",
1001 kAndroidHardcodedSystemPropertiesFieldName);
1002 return;
1003 }
1004 if (h_key->Equals(h_string_array->Get(0))) {
1005 // Found a value.
1006 if (h_string_array->Get(1) == nullptr && is_default_version) {
1007 // Null is being delegated to the default map, and then resolved to the given default value.
1008 // As there's no default map, return the given value.
1009 result->SetL(shadow_frame->GetVRegReference(arg_offset + 1));
1010 } else {
1011 result->SetL(h_string_array->Get(1));
1012 }
1013 return;
1014 }
1015 }
1016
1017 // Key is not supported.
1018 AbortTransactionOrFail(self, "getProperty key %s not supported", h_key->ToModifiedUtf8().c_str());
1019 }
1020
UnstartedSystemGetProperty(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1021 void UnstartedRuntime::UnstartedSystemGetProperty(
1022 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1023 GetSystemProperty(self, shadow_frame, result, arg_offset, false);
1024 }
1025
UnstartedSystemGetPropertyWithDefault(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1026 void UnstartedRuntime::UnstartedSystemGetPropertyWithDefault(
1027 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1028 GetSystemProperty(self, shadow_frame, result, arg_offset, true);
1029 }
1030
GetImmediateCaller(ShadowFrame * shadow_frame)1031 static std::string GetImmediateCaller(ShadowFrame* shadow_frame)
1032 REQUIRES_SHARED(Locks::mutator_lock_) {
1033 if (shadow_frame->GetLink() == nullptr) {
1034 return "<no caller>";
1035 }
1036 return ArtMethod::PrettyMethod(shadow_frame->GetLink()->GetMethod());
1037 }
1038
CheckCallers(ShadowFrame * shadow_frame,std::initializer_list<std::string> allowed_call_stack)1039 static bool CheckCallers(ShadowFrame* shadow_frame,
1040 std::initializer_list<std::string> allowed_call_stack)
1041 REQUIRES_SHARED(Locks::mutator_lock_) {
1042 for (const std::string& allowed_caller : allowed_call_stack) {
1043 if (shadow_frame->GetLink() == nullptr) {
1044 return false;
1045 }
1046
1047 std::string found_caller = ArtMethod::PrettyMethod(shadow_frame->GetLink()->GetMethod());
1048 if (allowed_caller != found_caller) {
1049 return false;
1050 }
1051
1052 shadow_frame = shadow_frame->GetLink();
1053 }
1054 return true;
1055 }
1056
CreateInstanceOf(Thread * self,const char * class_descriptor)1057 static ObjPtr<mirror::Object> CreateInstanceOf(Thread* self, const char* class_descriptor)
1058 REQUIRES_SHARED(Locks::mutator_lock_) {
1059 // Find the requested class.
1060 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1061 ObjPtr<mirror::Class> klass =
1062 class_linker->FindClass(self, class_descriptor, ScopedNullHandle<mirror::ClassLoader>());
1063 if (klass == nullptr) {
1064 AbortTransactionOrFail(self, "Could not load class %s", class_descriptor);
1065 return nullptr;
1066 }
1067
1068 StackHandleScope<2> hs(self);
1069 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1070 Handle<mirror::Object> h_obj(hs.NewHandle(h_class->AllocObject(self)));
1071 if (h_obj != nullptr) {
1072 ArtMethod* init_method = h_class->FindConstructor("()V", class_linker->GetImagePointerSize());
1073 if (init_method == nullptr) {
1074 AbortTransactionOrFail(self, "Could not find <init> for %s", class_descriptor);
1075 return nullptr;
1076 } else {
1077 JValue invoke_result;
1078 EnterInterpreterFromInvoke(self, init_method, h_obj.Get(), nullptr, nullptr);
1079 if (!self->IsExceptionPending()) {
1080 return h_obj.Get();
1081 }
1082 AbortTransactionOrFail(self, "Could not run <init> for %s", class_descriptor);
1083 }
1084 }
1085 AbortTransactionOrFail(self, "Could not allocate instance of %s", class_descriptor);
1086 return nullptr;
1087 }
1088
UnstartedThreadLocalGet(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset ATTRIBUTE_UNUSED)1089 void UnstartedRuntime::UnstartedThreadLocalGet(
1090 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset ATTRIBUTE_UNUSED) {
1091 if (CheckCallers(shadow_frame, { "jdk.internal.math.FloatingDecimal$BinaryToASCIIBuffer "
1092 "jdk.internal.math.FloatingDecimal.getBinaryToASCIIBuffer()" })) {
1093 result->SetL(CreateInstanceOf(self, "Ljdk/internal/math/FloatingDecimal$BinaryToASCIIBuffer;"));
1094 } else {
1095 AbortTransactionOrFail(self,
1096 "ThreadLocal.get() does not support %s",
1097 GetImmediateCaller(shadow_frame).c_str());
1098 }
1099 }
1100
UnstartedThreadCurrentThread(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset ATTRIBUTE_UNUSED)1101 void UnstartedRuntime::UnstartedThreadCurrentThread(
1102 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset ATTRIBUTE_UNUSED) {
1103 if (CheckCallers(shadow_frame,
1104 { "void java.lang.Thread.<init>(java.lang.ThreadGroup, java.lang.Runnable, "
1105 "java.lang.String, long, java.security.AccessControlContext, boolean)",
1106 "void java.lang.Thread.<init>(java.lang.ThreadGroup, java.lang.Runnable, "
1107 "java.lang.String, long)",
1108 "void java.lang.Thread.<init>()",
1109 "void java.util.logging.LogManager$Cleaner.<init>("
1110 "java.util.logging.LogManager)" })) {
1111 // Allow list LogManager$Cleaner, which is an unstarted Thread (for a shutdown hook). The
1112 // Thread constructor only asks for the current thread to set up defaults and add the
1113 // thread as unstarted to the ThreadGroup. A faked-up main thread peer is good enough for
1114 // these purposes.
1115 Runtime::Current()->InitThreadGroups(self);
1116 jobject main_peer =
1117 self->CreateCompileTimePeer(self->GetJniEnv(),
1118 "main",
1119 false,
1120 Runtime::Current()->GetMainThreadGroup());
1121 if (main_peer == nullptr) {
1122 AbortTransactionOrFail(self, "Failed allocating peer");
1123 return;
1124 }
1125
1126 result->SetL(self->DecodeJObject(main_peer));
1127 self->GetJniEnv()->DeleteLocalRef(main_peer);
1128 } else {
1129 AbortTransactionOrFail(self,
1130 "Thread.currentThread() does not support %s",
1131 GetImmediateCaller(shadow_frame).c_str());
1132 }
1133 }
1134
UnstartedThreadGetNativeState(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset ATTRIBUTE_UNUSED)1135 void UnstartedRuntime::UnstartedThreadGetNativeState(
1136 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset ATTRIBUTE_UNUSED) {
1137 if (CheckCallers(shadow_frame,
1138 { "java.lang.Thread$State java.lang.Thread.getState()",
1139 "java.lang.ThreadGroup java.lang.Thread.getThreadGroup()",
1140 "void java.lang.Thread.<init>(java.lang.ThreadGroup, java.lang.Runnable, "
1141 "java.lang.String, long, java.security.AccessControlContext, boolean)",
1142 "void java.lang.Thread.<init>(java.lang.ThreadGroup, java.lang.Runnable, "
1143 "java.lang.String, long)",
1144 "void java.lang.Thread.<init>()",
1145 "void java.util.logging.LogManager$Cleaner.<init>("
1146 "java.util.logging.LogManager)" })) {
1147 // Allow list reading the state of the "main" thread when creating another (unstarted) thread
1148 // for LogManager. Report the thread as "new" (it really only counts that it isn't terminated).
1149 constexpr int32_t kJavaRunnable = 1;
1150 result->SetI(kJavaRunnable);
1151 } else {
1152 AbortTransactionOrFail(self,
1153 "Thread.getNativeState() does not support %s",
1154 GetImmediateCaller(shadow_frame).c_str());
1155 }
1156 }
1157
UnstartedMathCeil(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1158 void UnstartedRuntime::UnstartedMathCeil(
1159 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1160 result->SetD(ceil(shadow_frame->GetVRegDouble(arg_offset)));
1161 }
1162
UnstartedMathFloor(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1163 void UnstartedRuntime::UnstartedMathFloor(
1164 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1165 result->SetD(floor(shadow_frame->GetVRegDouble(arg_offset)));
1166 }
1167
UnstartedMathSin(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1168 void UnstartedRuntime::UnstartedMathSin(
1169 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1170 result->SetD(sin(shadow_frame->GetVRegDouble(arg_offset)));
1171 }
1172
UnstartedMathCos(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1173 void UnstartedRuntime::UnstartedMathCos(
1174 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1175 result->SetD(cos(shadow_frame->GetVRegDouble(arg_offset)));
1176 }
1177
UnstartedMathPow(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1178 void UnstartedRuntime::UnstartedMathPow(
1179 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1180 result->SetD(pow(shadow_frame->GetVRegDouble(arg_offset),
1181 shadow_frame->GetVRegDouble(arg_offset + 2)));
1182 }
1183
UnstartedMathTan(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1184 void UnstartedRuntime::UnstartedMathTan(
1185 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1186 result->SetD(tan(shadow_frame->GetVRegDouble(arg_offset)));
1187 }
1188
UnstartedObjectHashCode(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1189 void UnstartedRuntime::UnstartedObjectHashCode(
1190 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1191 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset);
1192 result->SetI(obj->IdentityHashCode());
1193 }
1194
UnstartedDoubleDoubleToRawLongBits(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1195 void UnstartedRuntime::UnstartedDoubleDoubleToRawLongBits(
1196 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1197 double in = shadow_frame->GetVRegDouble(arg_offset);
1198 result->SetJ(bit_cast<int64_t, double>(in));
1199 }
1200
UnstartedMemoryPeek(Primitive::Type type,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1201 static void UnstartedMemoryPeek(
1202 Primitive::Type type, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1203 int64_t address = shadow_frame->GetVRegLong(arg_offset);
1204 // TODO: Check that this is in the heap somewhere. Otherwise we will segfault instead of
1205 // aborting the transaction.
1206
1207 switch (type) {
1208 case Primitive::kPrimByte: {
1209 result->SetB(*reinterpret_cast<int8_t*>(static_cast<intptr_t>(address)));
1210 return;
1211 }
1212
1213 case Primitive::kPrimShort: {
1214 using unaligned_short __attribute__((__aligned__(1))) = int16_t;
1215 result->SetS(*reinterpret_cast<unaligned_short*>(static_cast<intptr_t>(address)));
1216 return;
1217 }
1218
1219 case Primitive::kPrimInt: {
1220 using unaligned_int __attribute__((__aligned__(1))) = int32_t;
1221 result->SetI(*reinterpret_cast<unaligned_int*>(static_cast<intptr_t>(address)));
1222 return;
1223 }
1224
1225 case Primitive::kPrimLong: {
1226 using unaligned_long __attribute__((__aligned__(1))) = int64_t;
1227 result->SetJ(*reinterpret_cast<unaligned_long*>(static_cast<intptr_t>(address)));
1228 return;
1229 }
1230
1231 case Primitive::kPrimBoolean:
1232 case Primitive::kPrimChar:
1233 case Primitive::kPrimFloat:
1234 case Primitive::kPrimDouble:
1235 case Primitive::kPrimVoid:
1236 case Primitive::kPrimNot:
1237 LOG(FATAL) << "Not in the Memory API: " << type;
1238 UNREACHABLE();
1239 }
1240 LOG(FATAL) << "Should not reach here";
1241 UNREACHABLE();
1242 }
1243
UnstartedMemoryPeekByte(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1244 void UnstartedRuntime::UnstartedMemoryPeekByte(
1245 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1246 UnstartedMemoryPeek(Primitive::kPrimByte, shadow_frame, result, arg_offset);
1247 }
1248
UnstartedMemoryPeekShort(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1249 void UnstartedRuntime::UnstartedMemoryPeekShort(
1250 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1251 UnstartedMemoryPeek(Primitive::kPrimShort, shadow_frame, result, arg_offset);
1252 }
1253
UnstartedMemoryPeekInt(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1254 void UnstartedRuntime::UnstartedMemoryPeekInt(
1255 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1256 UnstartedMemoryPeek(Primitive::kPrimInt, shadow_frame, result, arg_offset);
1257 }
1258
UnstartedMemoryPeekLong(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1259 void UnstartedRuntime::UnstartedMemoryPeekLong(
1260 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1261 UnstartedMemoryPeek(Primitive::kPrimLong, shadow_frame, result, arg_offset);
1262 }
1263
UnstartedMemoryPeekArray(Primitive::Type type,Thread * self,ShadowFrame * shadow_frame,size_t arg_offset)1264 static void UnstartedMemoryPeekArray(
1265 Primitive::Type type, Thread* self, ShadowFrame* shadow_frame, size_t arg_offset)
1266 REQUIRES_SHARED(Locks::mutator_lock_) {
1267 int64_t address_long = shadow_frame->GetVRegLong(arg_offset);
1268 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset + 2);
1269 if (obj == nullptr) {
1270 Runtime::Current()->AbortTransactionAndThrowAbortError(self, "Null pointer in peekArray");
1271 return;
1272 }
1273 ObjPtr<mirror::Array> array = obj->AsArray();
1274
1275 int offset = shadow_frame->GetVReg(arg_offset + 3);
1276 int count = shadow_frame->GetVReg(arg_offset + 4);
1277 if (offset < 0 || offset + count > array->GetLength()) {
1278 std::string error_msg(StringPrintf("Array out of bounds in peekArray: %d/%d vs %d",
1279 offset, count, array->GetLength()));
1280 Runtime::Current()->AbortTransactionAndThrowAbortError(self, error_msg.c_str());
1281 return;
1282 }
1283
1284 switch (type) {
1285 case Primitive::kPrimByte: {
1286 int8_t* address = reinterpret_cast<int8_t*>(static_cast<intptr_t>(address_long));
1287 ObjPtr<mirror::ByteArray> byte_array = array->AsByteArray();
1288 for (int32_t i = 0; i < count; ++i, ++address) {
1289 byte_array->SetWithoutChecks<true>(i + offset, *address);
1290 }
1291 return;
1292 }
1293
1294 case Primitive::kPrimShort:
1295 case Primitive::kPrimInt:
1296 case Primitive::kPrimLong:
1297 LOG(FATAL) << "Type unimplemented for Memory Array API, should not reach here: " << type;
1298 UNREACHABLE();
1299
1300 case Primitive::kPrimBoolean:
1301 case Primitive::kPrimChar:
1302 case Primitive::kPrimFloat:
1303 case Primitive::kPrimDouble:
1304 case Primitive::kPrimVoid:
1305 case Primitive::kPrimNot:
1306 LOG(FATAL) << "Not in the Memory API: " << type;
1307 UNREACHABLE();
1308 }
1309 LOG(FATAL) << "Should not reach here";
1310 UNREACHABLE();
1311 }
1312
UnstartedMemoryPeekByteArray(Thread * self,ShadowFrame * shadow_frame,JValue * result ATTRIBUTE_UNUSED,size_t arg_offset)1313 void UnstartedRuntime::UnstartedMemoryPeekByteArray(
1314 Thread* self, ShadowFrame* shadow_frame, JValue* result ATTRIBUTE_UNUSED, size_t arg_offset) {
1315 UnstartedMemoryPeekArray(Primitive::kPrimByte, self, shadow_frame, arg_offset);
1316 }
1317
1318 // This allows reading the new style of String objects during compilation.
UnstartedStringGetCharsNoCheck(Thread * self,ShadowFrame * shadow_frame,JValue * result ATTRIBUTE_UNUSED,size_t arg_offset)1319 void UnstartedRuntime::UnstartedStringGetCharsNoCheck(
1320 Thread* self, ShadowFrame* shadow_frame, JValue* result ATTRIBUTE_UNUSED, size_t arg_offset) {
1321 jint start = shadow_frame->GetVReg(arg_offset + 1);
1322 jint end = shadow_frame->GetVReg(arg_offset + 2);
1323 jint index = shadow_frame->GetVReg(arg_offset + 4);
1324 ObjPtr<mirror::String> string = shadow_frame->GetVRegReference(arg_offset)->AsString();
1325 if (string == nullptr) {
1326 AbortTransactionOrFail(self, "String.getCharsNoCheck with null object");
1327 return;
1328 }
1329 DCHECK_GE(start, 0);
1330 DCHECK_LE(start, end);
1331 DCHECK_LE(end, string->GetLength());
1332 StackHandleScope<1> hs(self);
1333 Handle<mirror::CharArray> h_char_array(
1334 hs.NewHandle(shadow_frame->GetVRegReference(arg_offset + 3)->AsCharArray()));
1335 DCHECK_GE(index, 0);
1336 DCHECK_LE(index, h_char_array->GetLength());
1337 DCHECK_LE(end - start, h_char_array->GetLength() - index);
1338 string->GetChars(start, end, h_char_array, index);
1339 }
1340
1341 // This allows reading chars from the new style of String objects during compilation.
UnstartedStringCharAt(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1342 void UnstartedRuntime::UnstartedStringCharAt(
1343 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1344 jint index = shadow_frame->GetVReg(arg_offset + 1);
1345 ObjPtr<mirror::String> string = shadow_frame->GetVRegReference(arg_offset)->AsString();
1346 if (string == nullptr) {
1347 AbortTransactionOrFail(self, "String.charAt with null object");
1348 return;
1349 }
1350 result->SetC(string->CharAt(index));
1351 }
1352
1353 // This allows creating String objects with replaced characters during compilation.
1354 // String.doReplace(char, char) is called from String.replace(char, char) when there is a match.
UnstartedStringDoReplace(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1355 void UnstartedRuntime::UnstartedStringDoReplace(
1356 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1357 jchar old_c = shadow_frame->GetVReg(arg_offset + 1);
1358 jchar new_c = shadow_frame->GetVReg(arg_offset + 2);
1359 StackHandleScope<1> hs(self);
1360 Handle<mirror::String> string =
1361 hs.NewHandle(shadow_frame->GetVRegReference(arg_offset)->AsString());
1362 if (string == nullptr) {
1363 AbortTransactionOrFail(self, "String.replaceWithMatch with null object");
1364 return;
1365 }
1366 result->SetL(mirror::String::DoReplace(self, string, old_c, new_c));
1367 }
1368
1369 // This allows creating the new style of String objects during compilation.
UnstartedStringFactoryNewStringFromChars(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1370 void UnstartedRuntime::UnstartedStringFactoryNewStringFromChars(
1371 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1372 jint offset = shadow_frame->GetVReg(arg_offset);
1373 jint char_count = shadow_frame->GetVReg(arg_offset + 1);
1374 DCHECK_GE(char_count, 0);
1375 StackHandleScope<1> hs(self);
1376 Handle<mirror::CharArray> h_char_array(
1377 hs.NewHandle(shadow_frame->GetVRegReference(arg_offset + 2)->AsCharArray()));
1378 Runtime* runtime = Runtime::Current();
1379 gc::AllocatorType allocator = runtime->GetHeap()->GetCurrentAllocator();
1380 result->SetL(
1381 mirror::String::AllocFromCharArray(self, char_count, h_char_array, offset, allocator));
1382 }
1383
1384 // This allows creating the new style of String objects during compilation.
UnstartedStringFactoryNewStringFromString(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1385 void UnstartedRuntime::UnstartedStringFactoryNewStringFromString(
1386 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1387 ObjPtr<mirror::String> to_copy = shadow_frame->GetVRegReference(arg_offset)->AsString();
1388 if (to_copy == nullptr) {
1389 AbortTransactionOrFail(self, "StringFactory.newStringFromString with null object");
1390 return;
1391 }
1392 StackHandleScope<1> hs(self);
1393 Handle<mirror::String> h_string(hs.NewHandle(to_copy));
1394 Runtime* runtime = Runtime::Current();
1395 gc::AllocatorType allocator = runtime->GetHeap()->GetCurrentAllocator();
1396 result->SetL(
1397 mirror::String::AllocFromString(self, h_string->GetLength(), h_string, 0, allocator));
1398 }
1399
UnstartedStringFastSubstring(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1400 void UnstartedRuntime::UnstartedStringFastSubstring(
1401 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1402 jint start = shadow_frame->GetVReg(arg_offset + 1);
1403 jint length = shadow_frame->GetVReg(arg_offset + 2);
1404 DCHECK_GE(start, 0);
1405 DCHECK_GE(length, 0);
1406 StackHandleScope<1> hs(self);
1407 Handle<mirror::String> h_string(
1408 hs.NewHandle(shadow_frame->GetVRegReference(arg_offset)->AsString()));
1409 DCHECK_LE(start, h_string->GetLength());
1410 DCHECK_LE(start + length, h_string->GetLength());
1411 Runtime* runtime = Runtime::Current();
1412 gc::AllocatorType allocator = runtime->GetHeap()->GetCurrentAllocator();
1413 result->SetL(mirror::String::AllocFromString(self, length, h_string, start, allocator));
1414 }
1415
1416 // This allows getting the char array for new style of String objects during compilation.
UnstartedStringToCharArray(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1417 void UnstartedRuntime::UnstartedStringToCharArray(
1418 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
1419 REQUIRES_SHARED(Locks::mutator_lock_) {
1420 StackHandleScope<1> hs(self);
1421 Handle<mirror::String> string =
1422 hs.NewHandle(shadow_frame->GetVRegReference(arg_offset)->AsString());
1423 if (string == nullptr) {
1424 AbortTransactionOrFail(self, "String.charAt with null object");
1425 return;
1426 }
1427 result->SetL(mirror::String::ToCharArray(string, self));
1428 }
1429
1430 // This allows statically initializing ConcurrentHashMap and SynchronousQueue.
UnstartedReferenceGetReferent(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1431 void UnstartedRuntime::UnstartedReferenceGetReferent(
1432 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1433 const ObjPtr<mirror::Reference> ref = ObjPtr<mirror::Reference>::DownCast(
1434 shadow_frame->GetVRegReference(arg_offset));
1435 if (ref == nullptr) {
1436 AbortTransactionOrFail(self, "Reference.getReferent() with null object");
1437 return;
1438 }
1439 const ObjPtr<mirror::Object> referent =
1440 Runtime::Current()->GetHeap()->GetReferenceProcessor()->GetReferent(self, ref);
1441 result->SetL(referent);
1442 }
1443
UnstartedReferenceRefersTo(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1444 void UnstartedRuntime::UnstartedReferenceRefersTo(
1445 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1446 // Use the naive implementation that may block and needlessly extend the lifetime
1447 // of the referenced object.
1448 const ObjPtr<mirror::Reference> ref = ObjPtr<mirror::Reference>::DownCast(
1449 shadow_frame->GetVRegReference(arg_offset));
1450 if (ref == nullptr) {
1451 AbortTransactionOrFail(self, "Reference.refersTo() with null object");
1452 return;
1453 }
1454 const ObjPtr<mirror::Object> referent =
1455 Runtime::Current()->GetHeap()->GetReferenceProcessor()->GetReferent(self, ref);
1456 const ObjPtr<mirror::Object> o = shadow_frame->GetVRegReference(arg_offset + 1);
1457 result->SetZ(o == referent);
1458 }
1459
1460 // This allows statically initializing ConcurrentHashMap and SynchronousQueue. We use a somewhat
1461 // conservative upper bound. We restrict the callers to SynchronousQueue and ConcurrentHashMap,
1462 // where we can predict the behavior (somewhat).
1463 // Note: this is required (instead of lazy initialization) as these classes are used in the static
1464 // initialization of other classes, so will *use* the value.
UnstartedRuntimeAvailableProcessors(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset ATTRIBUTE_UNUSED)1465 void UnstartedRuntime::UnstartedRuntimeAvailableProcessors(
1466 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset ATTRIBUTE_UNUSED) {
1467 if (CheckCallers(shadow_frame, { "void java.util.concurrent.SynchronousQueue.<clinit>()" })) {
1468 // SynchronousQueue really only separates between single- and multiprocessor case. Return
1469 // 8 as a conservative upper approximation.
1470 result->SetI(8);
1471 } else if (CheckCallers(shadow_frame,
1472 { "void java.util.concurrent.ConcurrentHashMap.<clinit>()" })) {
1473 // ConcurrentHashMap uses it for striding. 8 still seems an OK general value, as it's likely
1474 // a good upper bound.
1475 // TODO: Consider resetting in the zygote?
1476 result->SetI(8);
1477 } else {
1478 // Not supported.
1479 AbortTransactionOrFail(self, "Accessing availableProcessors not allowed");
1480 }
1481 }
1482
1483 // This allows accessing ConcurrentHashMap/SynchronousQueue.
1484
UnstartedUnsafeCompareAndSwapLong(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1485 void UnstartedRuntime::UnstartedUnsafeCompareAndSwapLong(
1486 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1487 UnstartedJdkUnsafeCompareAndSwapLong(self, shadow_frame, result, arg_offset);
1488 }
1489
UnstartedUnsafeCompareAndSwapObject(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1490 void UnstartedRuntime::UnstartedUnsafeCompareAndSwapObject(
1491 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1492 UnstartedJdkUnsafeCompareAndSwapObject(self, shadow_frame, result, arg_offset);
1493 }
1494
UnstartedUnsafeGetObjectVolatile(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1495 void UnstartedRuntime::UnstartedUnsafeGetObjectVolatile(
1496 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
1497 REQUIRES_SHARED(Locks::mutator_lock_) {
1498 UnstartedJdkUnsafeGetObjectVolatile(self, shadow_frame, result, arg_offset);
1499 }
1500
UnstartedUnsafePutObjectVolatile(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1501 void UnstartedRuntime::UnstartedUnsafePutObjectVolatile(
1502 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
1503 REQUIRES_SHARED(Locks::mutator_lock_) {
1504 UnstartedJdkUnsafePutObjectVolatile(self, shadow_frame, result, arg_offset);
1505 }
1506
UnstartedUnsafePutOrderedObject(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1507 void UnstartedRuntime::UnstartedUnsafePutOrderedObject(
1508 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
1509 REQUIRES_SHARED(Locks::mutator_lock_) {
1510 UnstartedJdkUnsafePutOrderedObject(self, shadow_frame, result, arg_offset);
1511 }
1512
UnstartedJdkUnsafeCompareAndSwapLong(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1513 void UnstartedRuntime::UnstartedJdkUnsafeCompareAndSwapLong(
1514 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1515 // Argument 0 is the Unsafe instance, skip.
1516 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset + 1);
1517 if (obj == nullptr) {
1518 AbortTransactionOrFail(self, "Cannot access null object, retry at runtime.");
1519 return;
1520 }
1521 int64_t offset = shadow_frame->GetVRegLong(arg_offset + 2);
1522 int64_t expectedValue = shadow_frame->GetVRegLong(arg_offset + 4);
1523 int64_t newValue = shadow_frame->GetVRegLong(arg_offset + 6);
1524 bool success;
1525 // Check whether we're in a transaction, call accordingly.
1526 if (Runtime::Current()->IsActiveTransaction()) {
1527 if (!CheckWriteConstraint(self, obj)) {
1528 DCHECK(self->IsExceptionPending());
1529 return;
1530 }
1531 success = obj->CasFieldStrongSequentiallyConsistent64<true>(MemberOffset(offset),
1532 expectedValue,
1533 newValue);
1534 } else {
1535 success = obj->CasFieldStrongSequentiallyConsistent64<false>(MemberOffset(offset),
1536 expectedValue,
1537 newValue);
1538 }
1539 result->SetZ(success ? 1 : 0);
1540 }
1541
UnstartedJdkUnsafeCompareAndSetLong(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1542 void UnstartedRuntime::UnstartedJdkUnsafeCompareAndSetLong(
1543 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1544 UnstartedJdkUnsafeCompareAndSwapLong(self, shadow_frame, result, arg_offset);
1545 }
1546
UnstartedJdkUnsafeCompareAndSwapObject(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1547 void UnstartedRuntime::UnstartedJdkUnsafeCompareAndSwapObject(
1548 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1549 // Argument 0 is the Unsafe instance, skip.
1550 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset + 1);
1551 if (obj == nullptr) {
1552 AbortTransactionOrFail(self, "Cannot access null object, retry at runtime.");
1553 return;
1554 }
1555 int64_t offset = shadow_frame->GetVRegLong(arg_offset + 2);
1556 mirror::Object* expected_value = shadow_frame->GetVRegReference(arg_offset + 4);
1557 mirror::Object* new_value = shadow_frame->GetVRegReference(arg_offset + 5);
1558
1559 // Must use non transactional mode.
1560 if (kUseReadBarrier) {
1561 // Need to make sure the reference stored in the field is a to-space one before attempting the
1562 // CAS or the CAS could fail incorrectly.
1563 mirror::HeapReference<mirror::Object>* field_addr =
1564 reinterpret_cast<mirror::HeapReference<mirror::Object>*>(
1565 reinterpret_cast<uint8_t*>(obj) + static_cast<size_t>(offset));
1566 ReadBarrier::Barrier<
1567 mirror::Object,
1568 /* kIsVolatile= */ false,
1569 kWithReadBarrier,
1570 /* kAlwaysUpdateField= */ true>(
1571 obj,
1572 MemberOffset(offset),
1573 field_addr);
1574 }
1575 bool success;
1576 // Check whether we're in a transaction, call accordingly.
1577 if (Runtime::Current()->IsActiveTransaction()) {
1578 if (!CheckWriteConstraint(self, obj) || !CheckWriteValueConstraint(self, new_value)) {
1579 DCHECK(self->IsExceptionPending());
1580 return;
1581 }
1582 success = obj->CasFieldObject<true>(MemberOffset(offset),
1583 expected_value,
1584 new_value,
1585 CASMode::kStrong,
1586 std::memory_order_seq_cst);
1587 } else {
1588 success = obj->CasFieldObject<false>(MemberOffset(offset),
1589 expected_value,
1590 new_value,
1591 CASMode::kStrong,
1592 std::memory_order_seq_cst);
1593 }
1594 result->SetZ(success ? 1 : 0);
1595 }
1596
UnstartedJdkUnsafeCompareAndSetObject(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1597 void UnstartedRuntime::UnstartedJdkUnsafeCompareAndSetObject(
1598 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
1599 UnstartedJdkUnsafeCompareAndSwapObject(self, shadow_frame, result, arg_offset);
1600 }
1601
UnstartedJdkUnsafeGetObjectVolatile(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1602 void UnstartedRuntime::UnstartedJdkUnsafeGetObjectVolatile(
1603 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
1604 REQUIRES_SHARED(Locks::mutator_lock_) {
1605 // Argument 0 is the Unsafe instance, skip.
1606 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset + 1);
1607 if (obj == nullptr) {
1608 AbortTransactionOrFail(self, "Cannot access null object, retry at runtime.");
1609 return;
1610 }
1611 int64_t offset = shadow_frame->GetVRegLong(arg_offset + 2);
1612 ObjPtr<mirror::Object> value = obj->GetFieldObjectVolatile<mirror::Object>(MemberOffset(offset));
1613 result->SetL(value);
1614 }
1615
UnstartedJdkUnsafePutObjectVolatile(Thread * self,ShadowFrame * shadow_frame,JValue * result ATTRIBUTE_UNUSED,size_t arg_offset)1616 void UnstartedRuntime::UnstartedJdkUnsafePutObjectVolatile(
1617 Thread* self, ShadowFrame* shadow_frame, JValue* result ATTRIBUTE_UNUSED, size_t arg_offset)
1618 REQUIRES_SHARED(Locks::mutator_lock_) {
1619 // Argument 0 is the Unsafe instance, skip.
1620 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset + 1);
1621 if (obj == nullptr) {
1622 AbortTransactionOrFail(self, "Cannot access null object, retry at runtime.");
1623 return;
1624 }
1625 int64_t offset = shadow_frame->GetVRegLong(arg_offset + 2);
1626 mirror::Object* value = shadow_frame->GetVRegReference(arg_offset + 4);
1627 if (Runtime::Current()->IsActiveTransaction()) {
1628 if (!CheckWriteConstraint(self, obj) || !CheckWriteValueConstraint(self, value)) {
1629 DCHECK(self->IsExceptionPending());
1630 return;
1631 }
1632 obj->SetFieldObjectVolatile<true>(MemberOffset(offset), value);
1633 } else {
1634 obj->SetFieldObjectVolatile<false>(MemberOffset(offset), value);
1635 }
1636 }
1637
UnstartedJdkUnsafePutOrderedObject(Thread * self,ShadowFrame * shadow_frame,JValue * result ATTRIBUTE_UNUSED,size_t arg_offset)1638 void UnstartedRuntime::UnstartedJdkUnsafePutOrderedObject(
1639 Thread* self, ShadowFrame* shadow_frame, JValue* result ATTRIBUTE_UNUSED, size_t arg_offset)
1640 REQUIRES_SHARED(Locks::mutator_lock_) {
1641 // Argument 0 is the Unsafe instance, skip.
1642 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset + 1);
1643 if (obj == nullptr) {
1644 AbortTransactionOrFail(self, "Cannot access null object, retry at runtime.");
1645 return;
1646 }
1647 int64_t offset = shadow_frame->GetVRegLong(arg_offset + 2);
1648 mirror::Object* new_value = shadow_frame->GetVRegReference(arg_offset + 4);
1649 std::atomic_thread_fence(std::memory_order_release);
1650 if (Runtime::Current()->IsActiveTransaction()) {
1651 if (!CheckWriteConstraint(self, obj) || !CheckWriteValueConstraint(self, new_value)) {
1652 DCHECK(self->IsExceptionPending());
1653 return;
1654 }
1655 obj->SetFieldObject<true>(MemberOffset(offset), new_value);
1656 } else {
1657 obj->SetFieldObject<false>(MemberOffset(offset), new_value);
1658 }
1659 }
1660
1661 // A cutout for Integer.parseInt(String). Note: this code is conservative and will bail instead
1662 // of correctly handling the corner cases.
UnstartedIntegerParseInt(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1663 void UnstartedRuntime::UnstartedIntegerParseInt(
1664 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
1665 REQUIRES_SHARED(Locks::mutator_lock_) {
1666 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset);
1667 if (obj == nullptr) {
1668 AbortTransactionOrFail(self, "Cannot parse null string, retry at runtime.");
1669 return;
1670 }
1671
1672 std::string string_value = obj->AsString()->ToModifiedUtf8();
1673 if (string_value.empty()) {
1674 AbortTransactionOrFail(self, "Cannot parse empty string, retry at runtime.");
1675 return;
1676 }
1677
1678 const char* c_str = string_value.c_str();
1679 char *end;
1680 // Can we set errno to 0? Is this always a variable, and not a macro?
1681 // Worst case, we'll incorrectly fail a transaction. Seems OK.
1682 int64_t l = strtol(c_str, &end, 10);
1683
1684 if ((errno == ERANGE && l == LONG_MAX) || l > std::numeric_limits<int32_t>::max() ||
1685 (errno == ERANGE && l == LONG_MIN) || l < std::numeric_limits<int32_t>::min()) {
1686 AbortTransactionOrFail(self, "Cannot parse string %s, retry at runtime.", c_str);
1687 return;
1688 }
1689 if (l == 0) {
1690 // Check whether the string wasn't exactly zero.
1691 if (string_value != "0") {
1692 AbortTransactionOrFail(self, "Cannot parse string %s, retry at runtime.", c_str);
1693 return;
1694 }
1695 } else if (*end != '\0') {
1696 AbortTransactionOrFail(self, "Cannot parse string %s, retry at runtime.", c_str);
1697 return;
1698 }
1699
1700 result->SetI(static_cast<int32_t>(l));
1701 }
1702
1703 // A cutout for Long.parseLong.
1704 //
1705 // Note: for now use code equivalent to Integer.parseInt, as the full range may not be supported
1706 // well.
UnstartedLongParseLong(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1707 void UnstartedRuntime::UnstartedLongParseLong(
1708 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
1709 REQUIRES_SHARED(Locks::mutator_lock_) {
1710 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset);
1711 if (obj == nullptr) {
1712 AbortTransactionOrFail(self, "Cannot parse null string, retry at runtime.");
1713 return;
1714 }
1715
1716 std::string string_value = obj->AsString()->ToModifiedUtf8();
1717 if (string_value.empty()) {
1718 AbortTransactionOrFail(self, "Cannot parse empty string, retry at runtime.");
1719 return;
1720 }
1721
1722 const char* c_str = string_value.c_str();
1723 char *end;
1724 // Can we set errno to 0? Is this always a variable, and not a macro?
1725 // Worst case, we'll incorrectly fail a transaction. Seems OK.
1726 int64_t l = strtol(c_str, &end, 10);
1727
1728 // Note: comparing against int32_t min/max is intentional here.
1729 if ((errno == ERANGE && l == LONG_MAX) || l > std::numeric_limits<int32_t>::max() ||
1730 (errno == ERANGE && l == LONG_MIN) || l < std::numeric_limits<int32_t>::min()) {
1731 AbortTransactionOrFail(self, "Cannot parse string %s, retry at runtime.", c_str);
1732 return;
1733 }
1734 if (l == 0) {
1735 // Check whether the string wasn't exactly zero.
1736 if (string_value != "0") {
1737 AbortTransactionOrFail(self, "Cannot parse string %s, retry at runtime.", c_str);
1738 return;
1739 }
1740 } else if (*end != '\0') {
1741 AbortTransactionOrFail(self, "Cannot parse string %s, retry at runtime.", c_str);
1742 return;
1743 }
1744
1745 result->SetJ(l);
1746 }
1747
UnstartedMethodInvoke(Thread * self,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1748 void UnstartedRuntime::UnstartedMethodInvoke(
1749 Thread* self, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
1750 REQUIRES_SHARED(Locks::mutator_lock_) {
1751 JNIEnvExt* env = self->GetJniEnv();
1752 ScopedObjectAccessUnchecked soa(self);
1753
1754 ObjPtr<mirror::Object> java_method_obj = shadow_frame->GetVRegReference(arg_offset);
1755 ScopedLocalRef<jobject> java_method(env,
1756 java_method_obj == nullptr ? nullptr : env->AddLocalReference<jobject>(java_method_obj));
1757
1758 ObjPtr<mirror::Object> java_receiver_obj = shadow_frame->GetVRegReference(arg_offset + 1);
1759 ScopedLocalRef<jobject> java_receiver(env,
1760 java_receiver_obj == nullptr ? nullptr : env->AddLocalReference<jobject>(java_receiver_obj));
1761
1762 ObjPtr<mirror::Object> java_args_obj = shadow_frame->GetVRegReference(arg_offset + 2);
1763 ScopedLocalRef<jobject> java_args(env,
1764 java_args_obj == nullptr ? nullptr : env->AddLocalReference<jobject>(java_args_obj));
1765
1766 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1767 ScopedLocalRef<jobject> result_jobj(env,
1768 (pointer_size == PointerSize::k64)
1769 ? InvokeMethod<PointerSize::k64>(soa,
1770 java_method.get(),
1771 java_receiver.get(),
1772 java_args.get())
1773 : InvokeMethod<PointerSize::k32>(soa,
1774 java_method.get(),
1775 java_receiver.get(),
1776 java_args.get()));
1777
1778 result->SetL(self->DecodeJObject(result_jobj.get()));
1779
1780 // Conservatively flag all exceptions as transaction aborts. This way we don't need to unwrap
1781 // InvocationTargetExceptions.
1782 if (self->IsExceptionPending()) {
1783 AbortTransactionOrFail(self, "Failed Method.invoke");
1784 }
1785 }
1786
UnstartedSystemIdentityHashCode(Thread * self ATTRIBUTE_UNUSED,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)1787 void UnstartedRuntime::UnstartedSystemIdentityHashCode(
1788 Thread* self ATTRIBUTE_UNUSED, ShadowFrame* shadow_frame, JValue* result, size_t arg_offset)
1789 REQUIRES_SHARED(Locks::mutator_lock_) {
1790 mirror::Object* obj = shadow_frame->GetVRegReference(arg_offset);
1791 result->SetI((obj != nullptr) ? obj->IdentityHashCode() : 0);
1792 }
1793
1794 // Checks whether the runtime is s64-bit. This is needed for the clinit of
1795 // java.lang.invoke.VarHandle clinit. The clinit determines sets of
1796 // available VarHandle accessors and these differ based on machine
1797 // word size.
UnstartedJNIVMRuntimeIs64Bit(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)1798 void UnstartedRuntime::UnstartedJNIVMRuntimeIs64Bit(
1799 Thread* self ATTRIBUTE_UNUSED, ArtMethod* method ATTRIBUTE_UNUSED,
1800 mirror::Object* receiver ATTRIBUTE_UNUSED, uint32_t* args ATTRIBUTE_UNUSED, JValue* result) {
1801 PointerSize pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
1802 jboolean is64bit = (pointer_size == PointerSize::k64) ? JNI_TRUE : JNI_FALSE;
1803 result->SetZ(is64bit);
1804 }
1805
UnstartedJNIVMRuntimeNewUnpaddedArray(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)1806 void UnstartedRuntime::UnstartedJNIVMRuntimeNewUnpaddedArray(
1807 Thread* self,
1808 ArtMethod* method ATTRIBUTE_UNUSED,
1809 mirror::Object* receiver ATTRIBUTE_UNUSED,
1810 uint32_t* args,
1811 JValue* result) {
1812 int32_t length = args[1];
1813 DCHECK_GE(length, 0);
1814 ObjPtr<mirror::Object> element_class = reinterpret_cast32<mirror::Object*>(args[0])->AsClass();
1815 if (element_class == nullptr) {
1816 AbortTransactionOrFail(self, "VMRuntime.newUnpaddedArray with null element_class.");
1817 return;
1818 }
1819 Runtime* runtime = Runtime::Current();
1820 ObjPtr<mirror::Class> array_class =
1821 runtime->GetClassLinker()->FindArrayClass(self, element_class->AsClass());
1822 DCHECK(array_class != nullptr);
1823 gc::AllocatorType allocator = runtime->GetHeap()->GetCurrentAllocator();
1824 result->SetL(mirror::Array::Alloc</*kIsInstrumented=*/ true, /*kFillUsable=*/ true>(
1825 self, array_class, length, array_class->GetComponentSizeShift(), allocator));
1826 }
1827
UnstartedJNIVMStackGetCallingClassLoader(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)1828 void UnstartedRuntime::UnstartedJNIVMStackGetCallingClassLoader(
1829 Thread* self ATTRIBUTE_UNUSED, ArtMethod* method ATTRIBUTE_UNUSED,
1830 mirror::Object* receiver ATTRIBUTE_UNUSED, uint32_t* args ATTRIBUTE_UNUSED, JValue* result) {
1831 result->SetL(nullptr);
1832 }
1833
UnstartedJNIVMStackGetStackClass2(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)1834 void UnstartedRuntime::UnstartedJNIVMStackGetStackClass2(
1835 Thread* self, ArtMethod* method ATTRIBUTE_UNUSED, mirror::Object* receiver ATTRIBUTE_UNUSED,
1836 uint32_t* args ATTRIBUTE_UNUSED, JValue* result) {
1837 NthCallerVisitor visitor(self, 3);
1838 visitor.WalkStack();
1839 if (visitor.caller != nullptr) {
1840 result->SetL(visitor.caller->GetDeclaringClass());
1841 }
1842 }
1843
UnstartedJNIMathLog(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)1844 void UnstartedRuntime::UnstartedJNIMathLog(
1845 Thread* self ATTRIBUTE_UNUSED, ArtMethod* method ATTRIBUTE_UNUSED,
1846 mirror::Object* receiver ATTRIBUTE_UNUSED, uint32_t* args, JValue* result) {
1847 JValue value;
1848 value.SetJ((static_cast<uint64_t>(args[1]) << 32) | args[0]);
1849 result->SetD(log(value.GetD()));
1850 }
1851
UnstartedJNIMathExp(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)1852 void UnstartedRuntime::UnstartedJNIMathExp(
1853 Thread* self ATTRIBUTE_UNUSED, ArtMethod* method ATTRIBUTE_UNUSED,
1854 mirror::Object* receiver ATTRIBUTE_UNUSED, uint32_t* args, JValue* result) {
1855 JValue value;
1856 value.SetJ((static_cast<uint64_t>(args[1]) << 32) | args[0]);
1857 result->SetD(exp(value.GetD()));
1858 }
1859
UnstartedJNIAtomicLongVMSupportsCS8(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)1860 void UnstartedRuntime::UnstartedJNIAtomicLongVMSupportsCS8(
1861 Thread* self ATTRIBUTE_UNUSED,
1862 ArtMethod* method ATTRIBUTE_UNUSED,
1863 mirror::Object* receiver ATTRIBUTE_UNUSED,
1864 uint32_t* args ATTRIBUTE_UNUSED,
1865 JValue* result) {
1866 result->SetZ(QuasiAtomic::LongAtomicsUseMutexes(Runtime::Current()->GetInstructionSet())
1867 ? 0
1868 : 1);
1869 }
1870
UnstartedJNIClassGetNameNative(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)1871 void UnstartedRuntime::UnstartedJNIClassGetNameNative(
1872 Thread* self, ArtMethod* method ATTRIBUTE_UNUSED, mirror::Object* receiver,
1873 uint32_t* args ATTRIBUTE_UNUSED, JValue* result) {
1874 StackHandleScope<1> hs(self);
1875 result->SetL(mirror::Class::ComputeName(hs.NewHandle(receiver->AsClass())));
1876 }
1877
UnstartedJNIDoubleLongBitsToDouble(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)1878 void UnstartedRuntime::UnstartedJNIDoubleLongBitsToDouble(
1879 Thread* self ATTRIBUTE_UNUSED, ArtMethod* method ATTRIBUTE_UNUSED,
1880 mirror::Object* receiver ATTRIBUTE_UNUSED, uint32_t* args, JValue* result) {
1881 uint64_t long_input = args[0] | (static_cast<uint64_t>(args[1]) << 32);
1882 result->SetD(bit_cast<double>(long_input));
1883 }
1884
UnstartedJNIFloatFloatToRawIntBits(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)1885 void UnstartedRuntime::UnstartedJNIFloatFloatToRawIntBits(
1886 Thread* self ATTRIBUTE_UNUSED, ArtMethod* method ATTRIBUTE_UNUSED,
1887 mirror::Object* receiver ATTRIBUTE_UNUSED, uint32_t* args, JValue* result) {
1888 result->SetI(args[0]);
1889 }
1890
UnstartedJNIFloatIntBitsToFloat(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)1891 void UnstartedRuntime::UnstartedJNIFloatIntBitsToFloat(
1892 Thread* self ATTRIBUTE_UNUSED, ArtMethod* method ATTRIBUTE_UNUSED,
1893 mirror::Object* receiver ATTRIBUTE_UNUSED, uint32_t* args, JValue* result) {
1894 result->SetI(args[0]);
1895 }
1896
UnstartedJNIObjectInternalClone(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)1897 void UnstartedRuntime::UnstartedJNIObjectInternalClone(
1898 Thread* self, ArtMethod* method ATTRIBUTE_UNUSED, mirror::Object* receiver,
1899 uint32_t* args ATTRIBUTE_UNUSED, JValue* result) {
1900 StackHandleScope<1> hs(self);
1901 Handle<mirror::Object> h_receiver = hs.NewHandle(receiver);
1902 result->SetL(mirror::Object::Clone(h_receiver, self));
1903 }
1904
UnstartedJNIObjectNotifyAll(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver,uint32_t * args ATTRIBUTE_UNUSED,JValue * result ATTRIBUTE_UNUSED)1905 void UnstartedRuntime::UnstartedJNIObjectNotifyAll(
1906 Thread* self, ArtMethod* method ATTRIBUTE_UNUSED, mirror::Object* receiver,
1907 uint32_t* args ATTRIBUTE_UNUSED, JValue* result ATTRIBUTE_UNUSED) {
1908 receiver->NotifyAll(self);
1909 }
1910
UnstartedJNIStringCompareTo(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver,uint32_t * args,JValue * result)1911 void UnstartedRuntime::UnstartedJNIStringCompareTo(Thread* self,
1912 ArtMethod* method ATTRIBUTE_UNUSED,
1913 mirror::Object* receiver,
1914 uint32_t* args,
1915 JValue* result) {
1916 ObjPtr<mirror::Object> rhs = reinterpret_cast32<mirror::Object*>(args[0]);
1917 if (rhs == nullptr) {
1918 AbortTransactionOrFail(self, "String.compareTo with null object.");
1919 return;
1920 }
1921 result->SetI(receiver->AsString()->CompareTo(rhs->AsString()));
1922 }
1923
UnstartedJNIStringIntern(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)1924 void UnstartedRuntime::UnstartedJNIStringIntern(
1925 Thread* self ATTRIBUTE_UNUSED, ArtMethod* method ATTRIBUTE_UNUSED, mirror::Object* receiver,
1926 uint32_t* args ATTRIBUTE_UNUSED, JValue* result) {
1927 result->SetL(receiver->AsString()->Intern());
1928 }
1929
UnstartedJNIArrayCreateMultiArray(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)1930 void UnstartedRuntime::UnstartedJNIArrayCreateMultiArray(
1931 Thread* self, ArtMethod* method ATTRIBUTE_UNUSED, mirror::Object* receiver ATTRIBUTE_UNUSED,
1932 uint32_t* args, JValue* result) {
1933 StackHandleScope<2> hs(self);
1934 auto h_class(hs.NewHandle(reinterpret_cast<mirror::Class*>(args[0])->AsClass()));
1935 auto h_dimensions(hs.NewHandle(reinterpret_cast<mirror::IntArray*>(args[1])->AsIntArray()));
1936 result->SetL(mirror::Array::CreateMultiArray(self, h_class, h_dimensions));
1937 }
1938
UnstartedJNIArrayCreateObjectArray(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)1939 void UnstartedRuntime::UnstartedJNIArrayCreateObjectArray(
1940 Thread* self, ArtMethod* method ATTRIBUTE_UNUSED, mirror::Object* receiver ATTRIBUTE_UNUSED,
1941 uint32_t* args, JValue* result) {
1942 int32_t length = static_cast<int32_t>(args[1]);
1943 if (length < 0) {
1944 ThrowNegativeArraySizeException(length);
1945 return;
1946 }
1947 ObjPtr<mirror::Class> element_class = reinterpret_cast<mirror::Class*>(args[0])->AsClass();
1948 Runtime* runtime = Runtime::Current();
1949 ClassLinker* class_linker = runtime->GetClassLinker();
1950 ObjPtr<mirror::Class> array_class = class_linker->FindArrayClass(self, element_class);
1951 if (UNLIKELY(array_class == nullptr)) {
1952 CHECK(self->IsExceptionPending());
1953 return;
1954 }
1955 DCHECK(array_class->IsObjectArrayClass());
1956 ObjPtr<mirror::Array> new_array = mirror::ObjectArray<mirror::Object>::Alloc(
1957 self, array_class, length, runtime->GetHeap()->GetCurrentAllocator());
1958 result->SetL(new_array);
1959 }
1960
UnstartedJNIThrowableNativeFillInStackTrace(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)1961 void UnstartedRuntime::UnstartedJNIThrowableNativeFillInStackTrace(
1962 Thread* self, ArtMethod* method ATTRIBUTE_UNUSED, mirror::Object* receiver ATTRIBUTE_UNUSED,
1963 uint32_t* args ATTRIBUTE_UNUSED, JValue* result) {
1964 ScopedObjectAccessUnchecked soa(self);
1965 ScopedLocalRef<jobject> stack_trace(self->GetJniEnv(), self->CreateInternalStackTrace(soa));
1966 result->SetL(soa.Decode<mirror::Object>(stack_trace.get()));
1967 }
1968
UnstartedJNIUnsafeCompareAndSwapInt(Thread * self,ArtMethod * method,mirror::Object * receiver,uint32_t * args,JValue * result)1969 void UnstartedRuntime::UnstartedJNIUnsafeCompareAndSwapInt(
1970 Thread* self,
1971 ArtMethod* method,
1972 mirror::Object* receiver,
1973 uint32_t* args,
1974 JValue* result) {
1975 UnstartedJNIJdkUnsafeCompareAndSwapInt(self, method, receiver, args, result);
1976 }
1977
UnstartedJNIUnsafeGetIntVolatile(Thread * self,ArtMethod * method,mirror::Object * receiver,uint32_t * args,JValue * result)1978 void UnstartedRuntime::UnstartedJNIUnsafeGetIntVolatile(Thread* self,
1979 ArtMethod* method,
1980 mirror::Object* receiver,
1981 uint32_t* args,
1982 JValue* result) {
1983 UnstartedJNIJdkUnsafeGetIntVolatile(self, method, receiver, args, result);
1984 }
1985
UnstartedJNIUnsafePutObject(Thread * self,ArtMethod * method,mirror::Object * receiver,uint32_t * args,JValue * result)1986 void UnstartedRuntime::UnstartedJNIUnsafePutObject(Thread* self,
1987 ArtMethod* method,
1988 mirror::Object* receiver,
1989 uint32_t* args,
1990 JValue* result) {
1991 UnstartedJNIJdkUnsafePutObject(self, method, receiver, args, result);
1992 }
1993
UnstartedJNIUnsafeGetArrayBaseOffsetForComponentType(Thread * self,ArtMethod * method,mirror::Object * receiver,uint32_t * args,JValue * result)1994 void UnstartedRuntime::UnstartedJNIUnsafeGetArrayBaseOffsetForComponentType(
1995 Thread* self,
1996 ArtMethod* method,
1997 mirror::Object* receiver,
1998 uint32_t* args,
1999 JValue* result) {
2000 UnstartedJNIJdkUnsafeGetArrayBaseOffsetForComponentType(self, method, receiver, args, result);
2001 }
2002
UnstartedJNIUnsafeGetArrayIndexScaleForComponentType(Thread * self,ArtMethod * method,mirror::Object * receiver,uint32_t * args,JValue * result)2003 void UnstartedRuntime::UnstartedJNIUnsafeGetArrayIndexScaleForComponentType(
2004 Thread* self,
2005 ArtMethod* method,
2006 mirror::Object* receiver,
2007 uint32_t* args,
2008 JValue* result) {
2009 UnstartedJNIJdkUnsafeGetArrayIndexScaleForComponentType(self, method, receiver, args, result);
2010 }
2011
UnstartedJNIJdkUnsafeAddressSize(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)2012 void UnstartedRuntime::UnstartedJNIJdkUnsafeAddressSize(
2013 Thread* self ATTRIBUTE_UNUSED,
2014 ArtMethod* method ATTRIBUTE_UNUSED,
2015 mirror::Object* receiver ATTRIBUTE_UNUSED,
2016 uint32_t* args ATTRIBUTE_UNUSED,
2017 JValue* result) {
2018 result->SetI(sizeof(void*));
2019 }
2020
UnstartedJNIJdkUnsafeCompareAndSwapInt(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)2021 void UnstartedRuntime::UnstartedJNIJdkUnsafeCompareAndSwapInt(
2022 Thread* self,
2023 ArtMethod* method ATTRIBUTE_UNUSED,
2024 mirror::Object* receiver ATTRIBUTE_UNUSED,
2025 uint32_t* args,
2026 JValue* result) {
2027 ObjPtr<mirror::Object> obj = reinterpret_cast32<mirror::Object*>(args[0]);
2028 if (obj == nullptr) {
2029 AbortTransactionOrFail(self, "Cannot access null object, retry at runtime.");
2030 return;
2031 }
2032 jlong offset = (static_cast<uint64_t>(args[2]) << 32) | args[1];
2033 jint expectedValue = args[3];
2034 jint newValue = args[4];
2035 bool success;
2036 if (Runtime::Current()->IsActiveTransaction()) {
2037 if (!CheckWriteConstraint(self, obj)) {
2038 DCHECK(self->IsExceptionPending());
2039 return;
2040 }
2041 success = obj->CasField32<true>(MemberOffset(offset),
2042 expectedValue,
2043 newValue,
2044 CASMode::kStrong,
2045 std::memory_order_seq_cst);
2046 } else {
2047 success = obj->CasField32<false>(MemberOffset(offset),
2048 expectedValue,
2049 newValue,
2050 CASMode::kStrong,
2051 std::memory_order_seq_cst);
2052 }
2053 result->SetZ(success ? JNI_TRUE : JNI_FALSE);
2054 }
2055
UnstartedJNIJdkUnsafeCompareAndSetInt(Thread * self,ArtMethod * method,mirror::Object * receiver,uint32_t * args,JValue * result)2056 void UnstartedRuntime::UnstartedJNIJdkUnsafeCompareAndSetInt(
2057 Thread* self,
2058 ArtMethod* method,
2059 mirror::Object* receiver,
2060 uint32_t* args,
2061 JValue* result) {
2062 UnstartedJNIJdkUnsafeCompareAndSwapInt(self, method, receiver, args, result);
2063 }
2064
UnstartedJNIJdkUnsafeGetIntVolatile(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)2065 void UnstartedRuntime::UnstartedJNIJdkUnsafeGetIntVolatile(Thread* self,
2066 ArtMethod* method ATTRIBUTE_UNUSED,
2067 mirror::Object* receiver ATTRIBUTE_UNUSED,
2068 uint32_t* args,
2069 JValue* result) {
2070 ObjPtr<mirror::Object> obj = reinterpret_cast32<mirror::Object*>(args[0]);
2071 if (obj == nullptr) {
2072 AbortTransactionOrFail(self, "Unsafe.compareAndSwapIntVolatile with null object.");
2073 return;
2074 }
2075
2076 jlong offset = (static_cast<uint64_t>(args[2]) << 32) | args[1];
2077 result->SetI(obj->GetField32Volatile(MemberOffset(offset)));
2078 }
2079
UnstartedJNIJdkUnsafePutObject(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result ATTRIBUTE_UNUSED)2080 void UnstartedRuntime::UnstartedJNIJdkUnsafePutObject(Thread* self,
2081 ArtMethod* method ATTRIBUTE_UNUSED,
2082 mirror::Object* receiver ATTRIBUTE_UNUSED,
2083 uint32_t* args,
2084 JValue* result ATTRIBUTE_UNUSED) {
2085 ObjPtr<mirror::Object> obj = reinterpret_cast32<mirror::Object*>(args[0]);
2086 if (obj == nullptr) {
2087 AbortTransactionOrFail(self, "Unsafe.putObject with null object.");
2088 return;
2089 }
2090 jlong offset = (static_cast<uint64_t>(args[2]) << 32) | args[1];
2091 ObjPtr<mirror::Object> new_value = reinterpret_cast32<mirror::Object*>(args[3]);
2092 if (Runtime::Current()->IsActiveTransaction()) {
2093 if (!CheckWriteConstraint(self, obj) || !CheckWriteValueConstraint(self, new_value)) {
2094 DCHECK(self->IsExceptionPending());
2095 return;
2096 }
2097 obj->SetFieldObject<true>(MemberOffset(offset), new_value);
2098 } else {
2099 obj->SetFieldObject<false>(MemberOffset(offset), new_value);
2100 }
2101 }
2102
UnstartedJNIJdkUnsafeGetArrayBaseOffsetForComponentType(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)2103 void UnstartedRuntime::UnstartedJNIJdkUnsafeGetArrayBaseOffsetForComponentType(
2104 Thread* self,
2105 ArtMethod* method ATTRIBUTE_UNUSED,
2106 mirror::Object* receiver ATTRIBUTE_UNUSED,
2107 uint32_t* args,
2108 JValue* result) {
2109 ObjPtr<mirror::Object> component = reinterpret_cast32<mirror::Object*>(args[0]);
2110 if (component == nullptr) {
2111 AbortTransactionOrFail(self, "Unsafe.getArrayBaseOffsetForComponentType with null component.");
2112 return;
2113 }
2114 Primitive::Type primitive_type = component->AsClass()->GetPrimitiveType();
2115 result->SetI(mirror::Array::DataOffset(Primitive::ComponentSize(primitive_type)).Int32Value());
2116 }
2117
UnstartedJNIJdkUnsafeGetArrayIndexScaleForComponentType(Thread * self,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver ATTRIBUTE_UNUSED,uint32_t * args,JValue * result)2118 void UnstartedRuntime::UnstartedJNIJdkUnsafeGetArrayIndexScaleForComponentType(
2119 Thread* self,
2120 ArtMethod* method ATTRIBUTE_UNUSED,
2121 mirror::Object* receiver ATTRIBUTE_UNUSED,
2122 uint32_t* args,
2123 JValue* result) {
2124 ObjPtr<mirror::Object> component = reinterpret_cast32<mirror::Object*>(args[0]);
2125 if (component == nullptr) {
2126 AbortTransactionOrFail(self, "Unsafe.getArrayIndexScaleForComponentType with null component.");
2127 return;
2128 }
2129 Primitive::Type primitive_type = component->AsClass()->GetPrimitiveType();
2130 result->SetI(Primitive::ComponentSize(primitive_type));
2131 }
2132
UnstartedJNIFieldGetArtField(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)2133 void UnstartedRuntime::UnstartedJNIFieldGetArtField(
2134 Thread* self ATTRIBUTE_UNUSED,
2135 ArtMethod* method ATTRIBUTE_UNUSED,
2136 mirror::Object* receiver,
2137 uint32_t* args ATTRIBUTE_UNUSED,
2138 JValue* result) {
2139 ObjPtr<mirror::Field> field = ObjPtr<mirror::Field>::DownCast(receiver);
2140 ArtField* art_field = field->GetArtField();
2141 result->SetJ(reinterpret_cast<int64_t>(art_field));
2142 }
2143
UnstartedJNIFieldGetNameInternal(Thread * self ATTRIBUTE_UNUSED,ArtMethod * method ATTRIBUTE_UNUSED,mirror::Object * receiver,uint32_t * args ATTRIBUTE_UNUSED,JValue * result)2144 void UnstartedRuntime::UnstartedJNIFieldGetNameInternal(
2145 Thread* self ATTRIBUTE_UNUSED,
2146 ArtMethod* method ATTRIBUTE_UNUSED,
2147 mirror::Object* receiver,
2148 uint32_t* args ATTRIBUTE_UNUSED,
2149 JValue* result) {
2150 ObjPtr<mirror::Field> field = ObjPtr<mirror::Field>::DownCast(receiver);
2151 ArtField* art_field = field->GetArtField();
2152 result->SetL(art_field->ResolveNameString());
2153 }
2154
2155 using InvokeHandler = void(*)(Thread* self,
2156 ShadowFrame* shadow_frame,
2157 JValue* result,
2158 size_t arg_size);
2159
2160 using JNIHandler = void(*)(Thread* self,
2161 ArtMethod* method,
2162 mirror::Object* receiver,
2163 uint32_t* args,
2164 JValue* result);
2165
2166 #define ONE_PLUS(ShortNameIgnored, DescriptorIgnored, NameIgnored, SignatureIgnored) 1 +
2167 static constexpr size_t kInvokeHandlersSize = UNSTARTED_RUNTIME_DIRECT_LIST(ONE_PLUS) 0;
2168 static constexpr size_t kJniHandlersSize = UNSTARTED_RUNTIME_JNI_LIST(ONE_PLUS) 0;
2169 #undef ONE_PLUS
2170
2171 // The actual value of `kMinLoadFactor` is irrelevant because the HashMap<>s below
2172 // are never resized, but we still need to pass a reasonable value to the constructor.
2173 static constexpr double kMinLoadFactor = 0.5;
2174 static constexpr double kMaxLoadFactor = 0.7;
2175
BufferSize(size_t size)2176 constexpr size_t BufferSize(size_t size) {
2177 // Note: ceil() is not suitable for constexpr, so cast to size_t and adjust by 1 if needed.
2178 const size_t estimate = static_cast<size_t>(size / kMaxLoadFactor);
2179 return static_cast<size_t>(estimate * kMaxLoadFactor) == size ? estimate : estimate + 1u;
2180 }
2181
2182 static constexpr size_t kInvokeHandlersBufferSize = BufferSize(kInvokeHandlersSize);
2183 static_assert(
2184 static_cast<size_t>(kInvokeHandlersBufferSize * kMaxLoadFactor) == kInvokeHandlersSize);
2185 static constexpr size_t kJniHandlersBufferSize = BufferSize(kJniHandlersSize);
2186 static_assert(static_cast<size_t>(kJniHandlersBufferSize * kMaxLoadFactor) == kJniHandlersSize);
2187
2188 static bool tables_initialized_ = false;
2189 static std::pair<ArtMethod*, InvokeHandler> kInvokeHandlersBuffer[kInvokeHandlersBufferSize];
2190 static HashMap<ArtMethod*, InvokeHandler> invoke_handlers_(
2191 kMinLoadFactor, kMaxLoadFactor, kInvokeHandlersBuffer, kInvokeHandlersBufferSize);
2192 static std::pair<ArtMethod*, JNIHandler> kJniHandlersBuffer[kJniHandlersBufferSize];
2193 static HashMap<ArtMethod*, JNIHandler> jni_handlers_(
2194 kMinLoadFactor, kMaxLoadFactor, kJniHandlersBuffer, kJniHandlersBufferSize);
2195
FindMethod(Thread * self,ClassLinker * class_linker,const char * descriptor,std::string_view name,std::string_view signature)2196 static ArtMethod* FindMethod(Thread* self,
2197 ClassLinker* class_linker,
2198 const char* descriptor,
2199 std::string_view name,
2200 std::string_view signature) REQUIRES_SHARED(Locks::mutator_lock_) {
2201 ObjPtr<mirror::Class> klass = class_linker->FindSystemClass(self, descriptor);
2202 DCHECK(klass != nullptr) << descriptor;
2203 ArtMethod* method = klass->FindClassMethod(name, signature, class_linker->GetImagePointerSize());
2204 DCHECK(method != nullptr) << descriptor << "." << name << signature;
2205 return method;
2206 }
2207
InitializeInvokeHandlers(Thread * self)2208 void UnstartedRuntime::InitializeInvokeHandlers(Thread* self) {
2209 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2210 #define UNSTARTED_DIRECT(ShortName, Descriptor, Name, Signature) \
2211 { \
2212 ArtMethod* method = FindMethod(self, class_linker, Descriptor, Name, Signature); \
2213 invoke_handlers_.insert(std::make_pair(method, & UnstartedRuntime::Unstarted ## ShortName)); \
2214 }
2215 UNSTARTED_RUNTIME_DIRECT_LIST(UNSTARTED_DIRECT)
2216 #undef UNSTARTED_DIRECT
2217 DCHECK_EQ(invoke_handlers_.NumBuckets(), kInvokeHandlersBufferSize);
2218 }
2219
InitializeJNIHandlers(Thread * self)2220 void UnstartedRuntime::InitializeJNIHandlers(Thread* self) {
2221 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2222 #define UNSTARTED_JNI(ShortName, Descriptor, Name, Signature) \
2223 { \
2224 ArtMethod* method = FindMethod(self, class_linker, Descriptor, Name, Signature); \
2225 jni_handlers_.insert(std::make_pair(method, & UnstartedRuntime::UnstartedJNI ## ShortName)); \
2226 }
2227 UNSTARTED_RUNTIME_JNI_LIST(UNSTARTED_JNI)
2228 #undef UNSTARTED_JNI
2229 DCHECK_EQ(jni_handlers_.NumBuckets(), kJniHandlersBufferSize);
2230 }
2231
Initialize()2232 void UnstartedRuntime::Initialize() {
2233 CHECK(!tables_initialized_);
2234
2235 ScopedObjectAccess soa(Thread::Current());
2236 InitializeInvokeHandlers(soa.Self());
2237 InitializeJNIHandlers(soa.Self());
2238
2239 tables_initialized_ = true;
2240 }
2241
Reinitialize()2242 void UnstartedRuntime::Reinitialize() {
2243 CHECK(tables_initialized_);
2244
2245 // Note: HashSet::clear() abandons the pre-allocated storage which we need to keep.
2246 while (!invoke_handlers_.empty()) {
2247 invoke_handlers_.erase(invoke_handlers_.begin());
2248 }
2249 while (!jni_handlers_.empty()) {
2250 jni_handlers_.erase(jni_handlers_.begin());
2251 }
2252
2253 tables_initialized_ = false;
2254 Initialize();
2255 }
2256
Invoke(Thread * self,const CodeItemDataAccessor & accessor,ShadowFrame * shadow_frame,JValue * result,size_t arg_offset)2257 void UnstartedRuntime::Invoke(Thread* self, const CodeItemDataAccessor& accessor,
2258 ShadowFrame* shadow_frame, JValue* result, size_t arg_offset) {
2259 // In a runtime that's not started we intercept certain methods to avoid complicated dependency
2260 // problems in core libraries.
2261 CHECK(tables_initialized_);
2262
2263 const auto& iter = invoke_handlers_.find(shadow_frame->GetMethod());
2264 if (iter != invoke_handlers_.end()) {
2265 // Clear out the result in case it's not zeroed out.
2266 result->SetL(nullptr);
2267
2268 // Push the shadow frame. This is so the failing method can be seen in abort dumps.
2269 self->PushShadowFrame(shadow_frame);
2270
2271 (*iter->second)(self, shadow_frame, result, arg_offset);
2272
2273 self->PopShadowFrame();
2274 } else {
2275 // Not special, continue with regular interpreter execution.
2276 ArtInterpreterToInterpreterBridge(self, accessor, shadow_frame, result);
2277 }
2278 }
2279
2280 // Hand select a number of methods to be run in a not yet started runtime without using JNI.
Jni(Thread * self,ArtMethod * method,mirror::Object * receiver,uint32_t * args,JValue * result)2281 void UnstartedRuntime::Jni(Thread* self, ArtMethod* method, mirror::Object* receiver,
2282 uint32_t* args, JValue* result) {
2283 const auto& iter = jni_handlers_.find(method);
2284 if (iter != jni_handlers_.end()) {
2285 // Clear out the result in case it's not zeroed out.
2286 result->SetL(nullptr);
2287 (*iter->second)(self, method, receiver, args, result);
2288 } else if (Runtime::Current()->IsActiveTransaction()) {
2289 AbortTransactionF(self, "Attempt to invoke native method in non-started runtime: %s",
2290 ArtMethod::PrettyMethod(method).c_str());
2291 } else {
2292 LOG(FATAL) << "Calling native method " << ArtMethod::PrettyMethod(method) << " in an unstarted "
2293 "non-transactional runtime";
2294 }
2295 }
2296
2297 } // namespace interpreter
2298 } // namespace art
2299