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