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