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