1 /*
   2  * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/cdsConfig.hpp"
  29 #include "cds/heapShared.hpp"
  30 #include "cds/metaspaceShared.hpp"
  31 #include "classfile/altHashing.hpp"
  32 #include "classfile/classLoaderData.inline.hpp"
  33 #include "classfile/javaClasses.inline.hpp"
  34 #include "classfile/javaClassesImpl.hpp"
  35 #include "classfile/javaThreadStatus.hpp"
  36 #include "classfile/moduleEntry.hpp"
  37 #include "classfile/stringTable.hpp"
  38 #include "classfile/symbolTable.hpp"
  39 #include "classfile/systemDictionary.hpp"
  40 #include "classfile/vmClasses.hpp"
  41 #include "classfile/vmSymbols.hpp"
  42 #include "code/debugInfo.hpp"
  43 #include "code/dependencyContext.hpp"
  44 #include "code/pcDesc.hpp"
  45 #include "gc/shared/collectedHeap.inline.hpp"
  46 #include "interpreter/interpreter.hpp"
  47 #include "interpreter/linkResolver.hpp"
  48 #include "jvm.h"
  49 #include "logging/log.hpp"
  50 #include "logging/logStream.hpp"
  51 #include "memory/oopFactory.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "memory/universe.hpp"
  54 #include "oops/fieldInfo.hpp"
  55 #include "oops/fieldStreams.inline.hpp"
  56 #include "oops/instanceKlass.inline.hpp"
  57 #include "oops/instanceMirrorKlass.hpp"
  58 #include "oops/klass.hpp"
  59 #include "oops/klass.inline.hpp"
  60 #include "oops/method.inline.hpp"
  61 #include "oops/objArrayKlass.hpp"
  62 #include "oops/objArrayOop.inline.hpp"
  63 #include "oops/oopCast.inline.hpp"
  64 #include "oops/oop.inline.hpp"
  65 #include "oops/symbol.hpp"
  66 #include "oops/recordComponent.hpp"
  67 #include "oops/typeArrayOop.inline.hpp"
  68 #include "prims/jvmtiExport.hpp"
  69 #include "prims/methodHandles.hpp"
  70 #include "prims/resolvedMethodTable.hpp"
  71 #include "runtime/continuationEntry.inline.hpp"
  72 #include "runtime/continuationJavaClasses.inline.hpp"
  73 #include "runtime/fieldDescriptor.inline.hpp"
  74 #include "runtime/frame.inline.hpp"
  75 #include "runtime/handles.inline.hpp"
  76 #include "runtime/handshake.hpp"
  77 #include "runtime/init.hpp"
  78 #include "runtime/interfaceSupport.inline.hpp"
  79 #include "runtime/java.hpp"
  80 #include "runtime/javaCalls.hpp"
  81 #include "runtime/javaThread.hpp"
  82 #include "runtime/jniHandles.inline.hpp"
  83 #include "runtime/reflectionUtils.hpp"
  84 #include "runtime/safepoint.hpp"
  85 #include "runtime/safepointVerifiers.hpp"
  86 #include "runtime/threadSMR.hpp"
  87 #include "runtime/vframe.inline.hpp"
  88 #include "runtime/vm_version.hpp"
  89 #include "utilities/align.hpp"
  90 #include "utilities/globalDefinitions.hpp"
  91 #include "utilities/growableArray.hpp"
  92 #include "utilities/preserveException.hpp"
  93 #include "utilities/utf8.hpp"
  94 #if INCLUDE_JVMCI
  95 #include "jvmci/jvmciJavaClasses.hpp"
  96 #endif
  97 
  98 #define DECLARE_INJECTED_FIELD(klass, name, signature, may_be_java)           \
  99   { VM_CLASS_ID(klass), VM_SYMBOL_ENUM_NAME(name##_name), VM_SYMBOL_ENUM_NAME(signature), may_be_java },
 100 
 101 InjectedField JavaClasses::_injected_fields[] = {
 102   ALL_INJECTED_FIELDS(DECLARE_INJECTED_FIELD)
 103 };
 104 
 105 // Register native methods of Object
 106 void java_lang_Object::register_natives(TRAPS) {
 107   InstanceKlass* obj = vmClasses::Object_klass();
 108   Method::register_native(obj, vmSymbols::hashCode_name(),
 109                           vmSymbols::void_int_signature(), (address) &JVM_IHashCode, CHECK);
 110   Method::register_native(obj, vmSymbols::wait_name(),
 111                           vmSymbols::long_void_signature(), (address) &JVM_MonitorWait, CHECK);
 112   Method::register_native(obj, vmSymbols::notify_name(),
 113                           vmSymbols::void_method_signature(), (address) &JVM_MonitorNotify, CHECK);
 114   Method::register_native(obj, vmSymbols::notifyAll_name(),
 115                           vmSymbols::void_method_signature(), (address) &JVM_MonitorNotifyAll, CHECK);
 116   Method::register_native(obj, vmSymbols::clone_name(),
 117                           vmSymbols::void_object_signature(), (address) &JVM_Clone, THREAD);
 118 }
 119 
 120 int JavaClasses::compute_injected_offset(InjectedFieldID id) {
 121   return _injected_fields[(int)id].compute_offset();
 122 }
 123 
 124 InjectedField* JavaClasses::get_injected(Symbol* class_name, int* field_count) {
 125   *field_count = 0;
 126 
 127   vmSymbolID sid = vmSymbols::find_sid(class_name);
 128   if (sid == vmSymbolID::NO_SID) {
 129     // Only well known classes can inject fields
 130     return nullptr;
 131   }
 132 
 133   int count = 0;
 134   int start = -1;
 135 
 136 #define LOOKUP_INJECTED_FIELD(klass, name, signature, may_be_java) \
 137   if (sid == VM_SYMBOL_ENUM_NAME(klass)) {                         \
 138     count++;                                                       \
 139     if (start == -1) {                                             \
 140       start = (int)InjectedFieldID::klass##_##name##_enum;         \
 141     }                                                              \
 142   }
 143   ALL_INJECTED_FIELDS(LOOKUP_INJECTED_FIELD);
 144 #undef LOOKUP_INJECTED_FIELD
 145 
 146   if (start != -1) {
 147     *field_count = count;
 148     return _injected_fields + start;
 149   }
 150   return nullptr;
 151 }
 152 
 153 
 154 // Helpful routine for computing field offsets at run time rather than hardcoding them
 155 // Finds local fields only, including static fields.  Static field offsets are from the
 156 // beginning of the mirror.
 157 void JavaClasses::compute_offset(int &dest_offset,
 158                                  InstanceKlass* ik, Symbol* name_symbol, Symbol* signature_symbol,
 159                                  bool is_static) {
 160   fieldDescriptor fd;
 161   if (ik == nullptr) {
 162     ResourceMark rm;
 163     log_error(class)("Mismatch JDK version for field: %s type: %s", name_symbol->as_C_string(), signature_symbol->as_C_string());
 164     vm_exit_during_initialization("Invalid layout of well-known class");
 165   }
 166 
 167   if (!ik->find_local_field(name_symbol, signature_symbol, &fd) || fd.is_static() != is_static) {
 168     ResourceMark rm;
 169     log_error(class)("Invalid layout of %s field: %s type: %s", ik->external_name(),
 170                      name_symbol->as_C_string(), signature_symbol->as_C_string());
 171 #ifndef PRODUCT
 172     // Prints all fields and offsets
 173     Log(class) lt;
 174     LogStream ls(lt.error());
 175     ik->print_on(&ls);
 176 #endif //PRODUCT
 177     vm_exit_during_initialization("Invalid layout of well-known class: use -Xlog:class+load=info to see the origin of the problem class");
 178   }
 179   dest_offset = fd.offset();
 180 }
 181 
 182 // Overloading to pass name as a string.
 183 void JavaClasses::compute_offset(int& dest_offset, InstanceKlass* ik,
 184                                  const char* name_string, Symbol* signature_symbol,
 185                                  bool is_static) {
 186   TempNewSymbol name = SymbolTable::probe(name_string, (int)strlen(name_string));
 187   if (name == nullptr) {
 188     ResourceMark rm;
 189     log_error(class)("Name %s should be in the SymbolTable since its class is loaded", name_string);
 190     vm_exit_during_initialization("Invalid layout of well-known class", ik->external_name());
 191   }
 192   compute_offset(dest_offset, ik, name, signature_symbol, is_static);
 193 }
 194 
 195 // java_lang_String
 196 
 197 int java_lang_String::_value_offset;
 198 int java_lang_String::_hash_offset;
 199 int java_lang_String::_hashIsZero_offset;
 200 int java_lang_String::_coder_offset;
 201 int java_lang_String::_flags_offset;
 202 
 203 bool java_lang_String::_initialized;
 204 
 205 
 206 bool java_lang_String::test_and_set_flag(oop java_string, uint8_t flag_mask) {
 207   uint8_t* addr = flags_addr(java_string);
 208   uint8_t value = Atomic::load(addr);
 209   while ((value & flag_mask) == 0) {
 210     uint8_t old_value = value;
 211     value |= flag_mask;
 212     value = Atomic::cmpxchg(addr, old_value, value);
 213     if (value == old_value) return false; // Flag bit changed from 0 to 1.
 214   }
 215   return true;                  // Flag bit is already 1.
 216 }
 217 
 218 #define STRING_FIELDS_DO(macro) \
 219   macro(_value_offset, k, vmSymbols::value_name(), byte_array_signature, false); \
 220   macro(_hash_offset,  k, "hash",                  int_signature,        false); \
 221   macro(_hashIsZero_offset, k, "hashIsZero",       bool_signature,       false); \
 222   macro(_coder_offset, k, "coder",                 byte_signature,       false);
 223 
 224 void java_lang_String::compute_offsets() {
 225   if (_initialized) {
 226     return;
 227   }
 228 
 229   InstanceKlass* k = vmClasses::String_klass();
 230   STRING_FIELDS_DO(FIELD_COMPUTE_OFFSET);
 231   STRING_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 232 
 233   _initialized = true;
 234 }
 235 
 236 #if INCLUDE_CDS
 237 void java_lang_String::serialize_offsets(SerializeClosure* f) {
 238   STRING_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
 239   STRING_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
 240   f->do_bool(&_initialized);
 241 }
 242 #endif
 243 
 244 class CompactStringsFixup : public FieldClosure {
 245 private:
 246   bool _value;
 247 
 248 public:
 249   CompactStringsFixup(bool value) : _value(value) {}
 250 
 251   void do_field(fieldDescriptor* fd) {
 252     if (fd->name() == vmSymbols::compact_strings_name()) {
 253       oop mirror = fd->field_holder()->java_mirror();
 254       assert(fd->field_holder() == vmClasses::String_klass(), "Should be String");
 255       assert(mirror != nullptr, "String must have mirror already");
 256       mirror->bool_field_put(fd->offset(), _value);
 257     }
 258   }
 259 };
 260 
 261 void java_lang_String::set_compact_strings(bool value) {
 262   CompactStringsFixup fix(value);
 263   vmClasses::String_klass()->do_local_static_fields(&fix);
 264 }
 265 
 266 Handle java_lang_String::basic_create(int length, bool is_latin1, TRAPS) {
 267   assert(_initialized, "Must be initialized");
 268   assert(CompactStrings || !is_latin1, "Must be UTF16 without CompactStrings");
 269 
 270   // Create the String object first, so there's a chance that the String
 271   // and the char array it points to end up in the same cache line.
 272   oop obj;
 273   obj = vmClasses::String_klass()->allocate_instance(CHECK_NH);
 274 
 275   // Create the char array.  The String object must be handlized here
 276   // because GC can happen as a result of the allocation attempt.
 277   Handle h_obj(THREAD, obj);
 278   int arr_length = is_latin1 ? length : length << 1; // 2 bytes per UTF16.
 279   typeArrayOop buffer = oopFactory::new_byteArray(arr_length, CHECK_NH);;
 280 
 281   // Point the String at the char array
 282   obj = h_obj();
 283   set_value(obj, buffer);
 284   // No need to zero the offset, allocation zero'ed the entire String object
 285   set_coder(obj, is_latin1 ? CODER_LATIN1 : CODER_UTF16);
 286   return h_obj;
 287 }
 288 
 289 Handle java_lang_String::create_from_unicode(const jchar* unicode, int length, TRAPS) {
 290   bool is_latin1 = CompactStrings && UNICODE::is_latin1(unicode, length);
 291   Handle h_obj = basic_create(length, is_latin1, CHECK_NH);
 292   typeArrayOop buffer = value(h_obj());
 293   assert(TypeArrayKlass::cast(buffer->klass())->element_type() == T_BYTE, "only byte[]");
 294   if (is_latin1) {
 295     for (int index = 0; index < length; index++) {
 296       buffer->byte_at_put(index, (jbyte)unicode[index]);
 297     }
 298   } else {
 299     for (int index = 0; index < length; index++) {
 300       buffer->char_at_put(index, unicode[index]);
 301     }
 302   }
 303 
 304 #ifdef ASSERT
 305   {
 306     ResourceMark rm;
 307     char* expected = UNICODE::as_utf8(unicode, length);
 308     char* actual = as_utf8_string(h_obj());
 309     if (strcmp(expected, actual) != 0) {
 310       fatal("Unicode conversion failure: %s --> %s", expected, actual);
 311     }
 312   }
 313 #endif
 314 
 315   return h_obj;
 316 }
 317 
 318 oop java_lang_String::create_oop_from_unicode(const jchar* unicode, int length, TRAPS) {
 319   Handle h_obj = create_from_unicode(unicode, length, CHECK_NULL);
 320   return h_obj();
 321 }
 322 
 323 Handle java_lang_String::create_from_str(const char* utf8_str, TRAPS) {
 324   if (utf8_str == nullptr) {
 325     return Handle();
 326   }
 327   bool has_multibyte, is_latin1;
 328   int length = UTF8::unicode_length(utf8_str, is_latin1, has_multibyte);
 329   if (!CompactStrings) {
 330     has_multibyte = true;
 331     is_latin1 = false;
 332   }
 333 
 334   Handle h_obj = basic_create(length, is_latin1, CHECK_NH);
 335   if (length > 0) {
 336     if (!has_multibyte) {
 337       const jbyte* src = reinterpret_cast<const jbyte*>(utf8_str);
 338       ArrayAccess<>::arraycopy_from_native(src, value(h_obj()), typeArrayOopDesc::element_offset<jbyte>(0), length);
 339     } else if (is_latin1) {
 340       UTF8::convert_to_unicode(utf8_str, value(h_obj())->byte_at_addr(0), length);
 341     } else {
 342       UTF8::convert_to_unicode(utf8_str, value(h_obj())->char_at_addr(0), length);
 343     }
 344   }
 345 
 346 #ifdef ASSERT
 347   // This check is too strict when the input string is not a valid UTF8.
 348   // For example, it may be created with arbitrary content via jni_NewStringUTF.
 349   if (UTF8::is_legal_utf8((const unsigned char*)utf8_str, (int)strlen(utf8_str), false)) {
 350     ResourceMark rm;
 351     const char* expected = utf8_str;
 352     char* actual = as_utf8_string(h_obj());
 353     if (strcmp(expected, actual) != 0) {
 354       fatal("String conversion failure: %s --> %s", expected, actual);
 355     }
 356   }
 357 #endif
 358 
 359   return h_obj;
 360 }
 361 
 362 oop java_lang_String::create_oop_from_str(const char* utf8_str, TRAPS) {
 363   Handle h_obj = create_from_str(utf8_str, CHECK_NULL);
 364   return h_obj();
 365 }
 366 
 367 Handle java_lang_String::create_from_symbol(Symbol* symbol, TRAPS) {
 368   const char* utf8_str = (char*)symbol->bytes();
 369   int utf8_len = symbol->utf8_length();
 370 
 371   bool has_multibyte, is_latin1;
 372   int length = UTF8::unicode_length(utf8_str, utf8_len, is_latin1, has_multibyte);
 373   if (!CompactStrings) {
 374     has_multibyte = true;
 375     is_latin1 = false;
 376   }
 377 
 378   Handle h_obj = basic_create(length, is_latin1, CHECK_NH);
 379   if (length > 0) {
 380     if (!has_multibyte) {
 381       const jbyte* src = reinterpret_cast<const jbyte*>(utf8_str);
 382       ArrayAccess<>::arraycopy_from_native(src, value(h_obj()), typeArrayOopDesc::element_offset<jbyte>(0), length);
 383     } else if (is_latin1) {
 384       UTF8::convert_to_unicode(utf8_str, value(h_obj())->byte_at_addr(0), length);
 385     } else {
 386       UTF8::convert_to_unicode(utf8_str, value(h_obj())->char_at_addr(0), length);
 387     }
 388   }
 389 
 390 #ifdef ASSERT
 391   {
 392     ResourceMark rm;
 393     const char* expected = symbol->as_utf8();
 394     char* actual = as_utf8_string(h_obj());
 395     if (strncmp(expected, actual, utf8_len) != 0) {
 396       fatal("Symbol conversion failure: %s --> %s", expected, actual);
 397     }
 398   }
 399 #endif
 400 
 401   return h_obj;
 402 }
 403 
 404 // Converts a C string to a Java String based on current encoding
 405 Handle java_lang_String::create_from_platform_dependent_str(const char* str, TRAPS) {
 406   assert(str != nullptr, "bad arguments");
 407 
 408   typedef jstring (JNICALL *to_java_string_fn_t)(JNIEnv*, const char *);
 409   static to_java_string_fn_t _to_java_string_fn = nullptr;
 410 
 411   if (_to_java_string_fn == nullptr) {
 412     void *lib_handle = os::native_java_library();
 413     _to_java_string_fn = CAST_TO_FN_PTR(to_java_string_fn_t, os::dll_lookup(lib_handle, "JNU_NewStringPlatform"));
 414 #if defined(_WIN32) && !defined(_WIN64)
 415     if (_to_java_string_fn == nullptr) {
 416       // On 32 bit Windows, also try __stdcall decorated name
 417       _to_java_string_fn = CAST_TO_FN_PTR(to_java_string_fn_t, os::dll_lookup(lib_handle, "_JNU_NewStringPlatform@8"));
 418     }
 419 #endif
 420     if (_to_java_string_fn == nullptr) {
 421       fatal("JNU_NewStringPlatform missing");
 422     }
 423   }
 424 
 425   jstring js = nullptr;
 426   {
 427     JavaThread* thread = THREAD;
 428     HandleMark hm(thread);
 429     ThreadToNativeFromVM ttn(thread);
 430     js = (_to_java_string_fn)(thread->jni_environment(), str);
 431   }
 432 
 433   Handle native_platform_string(THREAD, JNIHandles::resolve(js));
 434   JNIHandles::destroy_local(js);  // destroy local JNIHandle.
 435   return native_platform_string;
 436 }
 437 
 438 // Converts a Java String to a native C string that can be used for
 439 // native OS calls.
 440 char* java_lang_String::as_platform_dependent_str(Handle java_string, TRAPS) {
 441   typedef char* (*to_platform_string_fn_t)(JNIEnv*, jstring, bool*);
 442   static to_platform_string_fn_t _to_platform_string_fn = nullptr;
 443 
 444   if (_to_platform_string_fn == nullptr) {
 445     void *lib_handle = os::native_java_library();
 446     _to_platform_string_fn = CAST_TO_FN_PTR(to_platform_string_fn_t, os::dll_lookup(lib_handle, "GetStringPlatformChars"));
 447     if (_to_platform_string_fn == nullptr) {
 448       fatal("GetStringPlatformChars missing");
 449     }
 450   }
 451 
 452   char *native_platform_string;
 453   jstring js;
 454   { JavaThread* thread = THREAD;
 455     js = (jstring) JNIHandles::make_local(thread, java_string());
 456     HandleMark hm(thread);
 457     ThreadToNativeFromVM ttn(thread);
 458     JNIEnv *env = thread->jni_environment();
 459     bool is_copy;
 460     native_platform_string = (_to_platform_string_fn)(env, js, &is_copy);
 461     assert(is_copy == JNI_TRUE, "is_copy value changed");
 462   }
 463 
 464   // Uses a store barrier and therefore needs to be in vm state
 465   JNIHandles::destroy_local(js);
 466 
 467   return native_platform_string;
 468 }
 469 
 470 Handle java_lang_String::externalize_classname(Symbol* java_name, TRAPS) {
 471   ResourceMark rm(THREAD);
 472   return create_from_str(java_name->as_klass_external_name(), THREAD);
 473 }
 474 
 475 jchar* java_lang_String::as_unicode_string(oop java_string, int& length, TRAPS) {
 476   jchar* result = as_unicode_string_or_null(java_string, length);
 477   if (result == nullptr) {
 478     THROW_MSG_0(vmSymbols::java_lang_OutOfMemoryError(), "could not allocate Unicode string");
 479   }
 480   return result;
 481 }
 482 
 483 jchar* java_lang_String::as_unicode_string_or_null(oop java_string, int& length) {
 484   typeArrayOop value  = java_lang_String::value(java_string);
 485                length = java_lang_String::length(java_string, value);
 486   bool      is_latin1 = java_lang_String::is_latin1(java_string);
 487 
 488   jchar* result = NEW_RESOURCE_ARRAY_RETURN_NULL(jchar, length);
 489   if (result != nullptr) {
 490     if (!is_latin1) {
 491       for (int index = 0; index < length; index++) {
 492         result[index] = value->char_at(index);
 493       }
 494     } else {
 495       for (int index = 0; index < length; index++) {
 496         result[index] = ((jchar) value->byte_at(index)) & 0xff;
 497       }
 498     }
 499   }
 500   return result;
 501 }
 502 
 503 inline unsigned int java_lang_String::hash_code_impl(oop java_string, bool update) {
 504   // The hash and hashIsZero fields are subject to a benign data race,
 505   // making it crucial to ensure that any observable result of the
 506   // calculation in this method stays correct under any possible read of
 507   // these fields. Necessary restrictions to allow this to be correct
 508   // without explicit memory fences or similar concurrency primitives is
 509   // that we can ever only write to one of these two fields for a given
 510   // String instance, and that the computation is idempotent and derived
 511   // from immutable state
 512   assert(_initialized && (_hash_offset > 0) && (_hashIsZero_offset > 0), "Must be initialized");
 513   if (java_lang_String::hash_is_set(java_string)) {
 514     return java_string->int_field(_hash_offset);
 515   }
 516 
 517   typeArrayOop value = java_lang_String::value(java_string);
 518   int         length = java_lang_String::length(java_string, value);
 519   bool     is_latin1 = java_lang_String::is_latin1(java_string);
 520 
 521   unsigned int hash = 0;
 522   if (length > 0) {
 523     if (is_latin1) {
 524       hash = java_lang_String::hash_code(value->byte_at_addr(0), length);
 525     } else {
 526       hash = java_lang_String::hash_code(value->char_at_addr(0), length);
 527     }
 528   }
 529 
 530   if (update) {
 531     if (hash != 0) {
 532       java_string->int_field_put(_hash_offset, hash);
 533     } else {
 534       java_string->bool_field_put(_hashIsZero_offset, true);
 535     }
 536   }
 537   return hash;
 538 }
 539 
 540 unsigned int java_lang_String::hash_code(oop java_string) {
 541   return hash_code_impl(java_string, /*update=*/true);
 542 }
 543 
 544 unsigned int java_lang_String::hash_code_noupdate(oop java_string) {
 545   return hash_code_impl(java_string, /*update=*/false);
 546 }
 547 
 548 
 549 char* java_lang_String::as_quoted_ascii(oop java_string) {
 550   typeArrayOop value  = java_lang_String::value(java_string);
 551   int          length = java_lang_String::length(java_string, value);
 552   bool      is_latin1 = java_lang_String::is_latin1(java_string);
 553 
 554   if (length == 0) return nullptr;
 555 
 556   char* result;
 557   int result_length;
 558   if (!is_latin1) {
 559     jchar* base = value->char_at_addr(0);
 560     result_length = UNICODE::quoted_ascii_length(base, length) + 1;
 561     result = NEW_RESOURCE_ARRAY(char, result_length);
 562     UNICODE::as_quoted_ascii(base, length, result, result_length);
 563   } else {
 564     jbyte* base = value->byte_at_addr(0);
 565     result_length = UNICODE::quoted_ascii_length(base, length) + 1;
 566     result = NEW_RESOURCE_ARRAY(char, result_length);
 567     UNICODE::as_quoted_ascii(base, length, result, result_length);
 568   }
 569   assert(result_length >= length + 1, "must not be shorter");
 570   assert(result_length == (int)strlen(result) + 1, "must match");
 571   return result;
 572 }
 573 
 574 Symbol* java_lang_String::as_symbol(oop java_string) {
 575   typeArrayOop value  = java_lang_String::value(java_string);
 576   int          length = java_lang_String::length(java_string, value);
 577   bool      is_latin1 = java_lang_String::is_latin1(java_string);
 578   if (!is_latin1) {
 579     jchar* base = (length == 0) ? nullptr : value->char_at_addr(0);
 580     Symbol* sym = SymbolTable::new_symbol(base, length);
 581     return sym;
 582   } else {
 583     ResourceMark rm;
 584     jbyte* position = (length == 0) ? nullptr : value->byte_at_addr(0);
 585     const char* base = UNICODE::as_utf8(position, length);
 586     Symbol* sym = SymbolTable::new_symbol(base, length);
 587     return sym;
 588   }
 589 }
 590 
 591 Symbol* java_lang_String::as_symbol_or_null(oop java_string) {
 592   typeArrayOop value  = java_lang_String::value(java_string);
 593   int          length = java_lang_String::length(java_string, value);
 594   bool      is_latin1 = java_lang_String::is_latin1(java_string);
 595   if (!is_latin1) {
 596     jchar* base = (length == 0) ? nullptr : value->char_at_addr(0);
 597     return SymbolTable::probe_unicode(base, length);
 598   } else {
 599     ResourceMark rm;
 600     jbyte* position = (length == 0) ? nullptr : value->byte_at_addr(0);
 601     const char* base = UNICODE::as_utf8(position, length);
 602     return SymbolTable::probe(base, length);
 603   }
 604 }
 605 
 606 int java_lang_String::utf8_length(oop java_string, typeArrayOop value) {
 607   assert(value_equals(value, java_lang_String::value(java_string)),
 608          "value must be same as java_lang_String::value(java_string)");
 609   int length = java_lang_String::length(java_string, value);
 610   if (length == 0) {
 611     return 0;
 612   }
 613   if (!java_lang_String::is_latin1(java_string)) {
 614     return UNICODE::utf8_length(value->char_at_addr(0), length);
 615   } else {
 616     return UNICODE::utf8_length(value->byte_at_addr(0), length);
 617   }
 618 }
 619 
 620 int java_lang_String::utf8_length(oop java_string) {
 621   typeArrayOop value = java_lang_String::value(java_string);
 622   return utf8_length(java_string, value);
 623 }
 624 
 625 char* java_lang_String::as_utf8_string(oop java_string) {
 626   int length;
 627   return as_utf8_string(java_string, length);
 628 }
 629 
 630 char* java_lang_String::as_utf8_string(oop java_string, int& length) {
 631   typeArrayOop value = java_lang_String::value(java_string);
 632   length             = java_lang_String::length(java_string, value);
 633   bool     is_latin1 = java_lang_String::is_latin1(java_string);
 634   if (!is_latin1) {
 635     jchar* position = (length == 0) ? nullptr : value->char_at_addr(0);
 636     return UNICODE::as_utf8(position, length);
 637   } else {
 638     jbyte* position = (length == 0) ? nullptr : value->byte_at_addr(0);
 639     return UNICODE::as_utf8(position, length);
 640   }
 641 }
 642 
 643 // Uses a provided buffer if it's sufficiently large, otherwise allocates
 644 // a resource array to fit
 645 char* java_lang_String::as_utf8_string_full(oop java_string, char* buf, int buflen, int& utf8_len) {
 646   typeArrayOop value = java_lang_String::value(java_string);
 647   int            len = java_lang_String::length(java_string, value);
 648   bool     is_latin1 = java_lang_String::is_latin1(java_string);
 649   if (!is_latin1) {
 650     jchar *position = (len == 0) ? nullptr : value->char_at_addr(0);
 651     utf8_len = UNICODE::utf8_length(position, len);
 652     if (utf8_len >= buflen) {
 653       buf = NEW_RESOURCE_ARRAY(char, utf8_len + 1);
 654     }
 655     return UNICODE::as_utf8(position, len, buf, utf8_len + 1);
 656   } else {
 657     jbyte *position = (len == 0) ? nullptr : value->byte_at_addr(0);
 658     utf8_len = UNICODE::utf8_length(position, len);
 659     if (utf8_len >= buflen) {
 660       buf = NEW_RESOURCE_ARRAY(char, utf8_len + 1);
 661     }
 662     return UNICODE::as_utf8(position, len, buf, utf8_len + 1);
 663   }
 664 }
 665 
 666 char* java_lang_String::as_utf8_string(oop java_string, typeArrayOop value, char* buf, int buflen) {
 667   assert(value_equals(value, java_lang_String::value(java_string)),
 668          "value must be same as java_lang_String::value(java_string)");
 669   int     length = java_lang_String::length(java_string, value);
 670   bool is_latin1 = java_lang_String::is_latin1(java_string);
 671   if (!is_latin1) {
 672     jchar* position = (length == 0) ? nullptr : value->char_at_addr(0);
 673     return UNICODE::as_utf8(position, length, buf, buflen);
 674   } else {
 675     jbyte* position = (length == 0) ? nullptr : value->byte_at_addr(0);
 676     return UNICODE::as_utf8(position, length, buf, buflen);
 677   }
 678 }
 679 
 680 char* java_lang_String::as_utf8_string(oop java_string, char* buf, int buflen) {
 681   typeArrayOop value = java_lang_String::value(java_string);
 682   return as_utf8_string(java_string, value, buf, buflen);
 683 }
 684 
 685 char* java_lang_String::as_utf8_string(oop java_string, int start, int len) {
 686   typeArrayOop value  = java_lang_String::value(java_string);
 687   bool      is_latin1 = java_lang_String::is_latin1(java_string);
 688   assert(start + len <= java_lang_String::length(java_string), "just checking");
 689   if (!is_latin1) {
 690     jchar* position = value->char_at_addr(start);
 691     return UNICODE::as_utf8(position, len);
 692   } else {
 693     jbyte* position = value->byte_at_addr(start);
 694     return UNICODE::as_utf8(position, len);
 695   }
 696 }
 697 
 698 char* java_lang_String::as_utf8_string(oop java_string, typeArrayOop value, int start, int len, char* buf, int buflen) {
 699   assert(value_equals(value, java_lang_String::value(java_string)),
 700          "value must be same as java_lang_String::value(java_string)");
 701   assert(start + len <= java_lang_String::length(java_string), "just checking");
 702   bool is_latin1 = java_lang_String::is_latin1(java_string);
 703   if (!is_latin1) {
 704     jchar* position = value->char_at_addr(start);
 705     return UNICODE::as_utf8(position, len, buf, buflen);
 706   } else {
 707     jbyte* position = value->byte_at_addr(start);
 708     return UNICODE::as_utf8(position, len, buf, buflen);
 709   }
 710 }
 711 
 712 bool java_lang_String::equals(oop java_string, const jchar* chars, int len) {
 713   assert(java_string->klass() == vmClasses::String_klass(),
 714          "must be java_string");
 715   typeArrayOop value = java_lang_String::value_no_keepalive(java_string);
 716   int length = java_lang_String::length(java_string, value);
 717   if (length != len) {
 718     return false;
 719   }
 720   bool is_latin1 = java_lang_String::is_latin1(java_string);
 721   if (!is_latin1) {
 722     for (int i = 0; i < len; i++) {
 723       if (value->char_at(i) != chars[i]) {
 724         return false;
 725       }
 726     }
 727   } else {
 728     for (int i = 0; i < len; i++) {
 729       if ((((jchar) value->byte_at(i)) & 0xff) != chars[i]) {
 730         return false;
 731       }
 732     }
 733   }
 734   return true;
 735 }
 736 
 737 bool java_lang_String::equals(oop str1, oop str2) {
 738   assert(str1->klass() == vmClasses::String_klass(),
 739          "must be java String");
 740   assert(str2->klass() == vmClasses::String_klass(),
 741          "must be java String");
 742   typeArrayOop value1    = java_lang_String::value_no_keepalive(str1);
 743   bool         is_latin1 = java_lang_String::is_latin1(str1);
 744   typeArrayOop value2    = java_lang_String::value_no_keepalive(str2);
 745   bool         is_latin2 = java_lang_String::is_latin1(str2);
 746 
 747   if (is_latin1 != is_latin2) {
 748     // Strings with different coders are never equal.
 749     return false;
 750   }
 751   return value_equals(value1, value2);
 752 }
 753 
 754 void java_lang_String::print(oop java_string, outputStream* st) {
 755   assert(java_string->klass() == vmClasses::String_klass(), "must be java_string");
 756   typeArrayOop value  = java_lang_String::value_no_keepalive(java_string);
 757 
 758   if (value == nullptr) {
 759     // This can happen if, e.g., printing a String
 760     // object before its initializer has been called
 761     st->print("nullptr");
 762     return;
 763   }
 764 
 765   int length = java_lang_String::length(java_string, value);
 766   bool is_latin1 = java_lang_String::is_latin1(java_string);
 767 
 768   st->print("\"");
 769   for (int index = 0; index < length; index++) {
 770     jchar c = (!is_latin1) ?  value->char_at(index) :
 771                              ((jchar) value->byte_at(index)) & 0xff;
 772     if (c < ' ') {
 773       st->print("\\x%02X", c); // print control characters e.g. \x0A
 774     } else {
 775       st->print("%c", c);
 776     }
 777   }
 778   st->print("\"");
 779 }
 780 
 781 // java_lang_Class
 782 
 783 int java_lang_Class::_klass_offset;
 784 int java_lang_Class::_array_klass_offset;
 785 int java_lang_Class::_oop_size_offset;
 786 int java_lang_Class::_static_oop_field_count_offset;
 787 int java_lang_Class::_class_loader_offset;
 788 int java_lang_Class::_module_offset;
 789 int java_lang_Class::_protection_domain_offset;
 790 int java_lang_Class::_component_mirror_offset;
 791 int java_lang_Class::_signers_offset;
 792 int java_lang_Class::_name_offset;
 793 int java_lang_Class::_source_file_offset;
 794 int java_lang_Class::_classData_offset;
 795 int java_lang_Class::_classRedefinedCount_offset;
 796 int java_lang_Class::_reflectionData_offset;
 797 
 798 bool java_lang_Class::_offsets_computed = false;
 799 GrowableArray<Klass*>* java_lang_Class::_fixup_mirror_list = nullptr;
 800 GrowableArray<Klass*>* java_lang_Class::_fixup_module_field_list = nullptr;
 801 
 802 #ifdef ASSERT
 803 inline static void assert_valid_static_string_field(fieldDescriptor* fd) {
 804   assert(fd->has_initial_value(), "caller should have checked this");
 805   assert(fd->field_type() == T_OBJECT, "caller should have checked this");
 806   assert(fd->signature() == vmSymbols::string_signature(), "just checking");
 807 }
 808 #endif
 809 
 810 static void initialize_static_string_field(fieldDescriptor* fd, Handle mirror, TRAPS) {
 811   DEBUG_ONLY(assert_valid_static_string_field(fd);)
 812   oop string = fd->string_initial_value(CHECK);
 813   mirror()->obj_field_put(fd->offset(), string);
 814 }
 815 
 816 static void initialize_static_primitive_field(fieldDescriptor* fd, Handle mirror) {
 817   assert(fd->has_initial_value(), "caller should have checked this");
 818   BasicType t = fd->field_type();
 819   switch (t) {
 820   case T_BYTE:
 821     mirror()->byte_field_put(fd->offset(), (jbyte)(fd->int_initial_value()));
 822     break;
 823   case T_BOOLEAN:
 824     mirror()->bool_field_put(fd->offset(), (jboolean)(fd->int_initial_value()));
 825     break;
 826   case T_CHAR:
 827     mirror()->char_field_put(fd->offset(), (jchar)(fd->int_initial_value()));
 828     break;
 829   case T_SHORT:
 830     mirror()->short_field_put(fd->offset(), (jshort)(fd->int_initial_value()));
 831     break;
 832   case T_INT:
 833     mirror()->int_field_put(fd->offset(), fd->int_initial_value());
 834     break;
 835   case T_FLOAT:
 836     mirror()->float_field_put(fd->offset(), fd->float_initial_value());
 837     break;
 838   case T_DOUBLE:
 839     mirror()->double_field_put(fd->offset(), fd->double_initial_value());
 840     break;
 841   case T_LONG:
 842     mirror()->long_field_put(fd->offset(), fd->long_initial_value());
 843     break;
 844   default:
 845     // Illegal ConstantValue attribute in class file should have been
 846     // caught during classfile parsing.
 847     ShouldNotReachHere();
 848   }
 849 }
 850 
 851 static void initialize_static_field(fieldDescriptor* fd, Handle mirror, TRAPS) {
 852   assert(mirror.not_null() && fd->is_static(), "just checking");
 853   if (fd->has_initial_value()) {
 854     if (fd->field_type() != T_OBJECT) {
 855       initialize_static_primitive_field(fd, mirror);
 856     } else {
 857       initialize_static_string_field(fd, mirror, CHECK);
 858     }
 859   }
 860 }
 861 
 862 void java_lang_Class::fixup_mirror(Klass* k, TRAPS) {
 863   assert(InstanceMirrorKlass::offset_of_static_fields() != 0, "must have been computed already");
 864 
 865   // If the offset was read from the shared archive, it was fixed up already
 866   if (!k->is_shared()) {
 867     if (k->is_instance_klass()) {
 868       // During bootstrap, java.lang.Class wasn't loaded so static field
 869       // offsets were computed without the size added it.  Go back and
 870       // update all the static field offsets to included the size.
 871 
 872       // Unfortunately, the FieldInfo stream is encoded with UNSIGNED5 which doesn't allow
 873       // content updates. So the FieldInfo stream has to be decompressed into a temporary array,
 874       // static fields offsets are updated in this array before reencoding everything into
 875       // a new UNSIGNED5 stream, and substitute it to the old FieldInfo stream.
 876 
 877       int java_fields;
 878       int injected_fields;
 879       InstanceKlass* ik = InstanceKlass::cast(k);
 880       GrowableArray<FieldInfo>* fields =
 881         FieldInfoStream::create_FieldInfoArray(ik->fieldinfo_stream(),
 882                                                &java_fields, &injected_fields);
 883       for (int i = 0; i < fields->length(); i++) {
 884         FieldInfo* fi = fields->adr_at(i);
 885         if (fi->access_flags().is_static()) {
 886           fi->set_offset(fi->offset() + InstanceMirrorKlass::offset_of_static_fields());
 887         }
 888       }
 889       Array<u1>* old_stream = ik->fieldinfo_stream();
 890       assert(fields->length() == (java_fields + injected_fields), "Must be");
 891       Array<u1>* new_fis = FieldInfoStream::create_FieldInfoStream(fields, java_fields, injected_fields, k->class_loader_data(), CHECK);
 892       ik->set_fieldinfo_stream(new_fis);
 893       MetadataFactory::free_array<u1>(k->class_loader_data(), old_stream);
 894     }
 895   }
 896 
 897   if (k->is_shared() && k->has_archived_mirror_index()) {
 898     if (ArchiveHeapLoader::is_in_use()) {
 899       bool present = restore_archived_mirror(k, Handle(), Handle(), Handle(), CHECK);
 900       assert(present, "Missing archived mirror for %s", k->external_name());
 901       return;
 902     } else {
 903       k->clear_java_mirror_handle();
 904       k->clear_archived_mirror_index();
 905     }
 906   }
 907   create_mirror(k, Handle(), Handle(), Handle(), Handle(), CHECK);
 908 }
 909 
 910 void java_lang_Class::initialize_mirror_fields(Klass* k,
 911                                                Handle mirror,
 912                                                Handle protection_domain,
 913                                                Handle classData,
 914                                                TRAPS) {
 915   // Set protection domain also
 916   set_protection_domain(mirror(), protection_domain());
 917 
 918   // Initialize static fields
 919   InstanceKlass::cast(k)->do_local_static_fields(&initialize_static_field, mirror, CHECK);
 920 
 921  // Set classData
 922   set_class_data(mirror(), classData());
 923 }
 924 
 925 // Set the java.lang.Module module field in the java_lang_Class mirror
 926 void java_lang_Class::set_mirror_module_field(JavaThread* current, Klass* k, Handle mirror, Handle module) {
 927   if (module.is_null()) {
 928     // During startup, the module may be null only if java.base has not been defined yet.
 929     // Put the class on the fixup_module_list to patch later when the java.lang.Module
 930     // for java.base is known. But note that since we captured the null module another
 931     // thread may have completed that initialization.
 932 
 933     bool javabase_was_defined = false;
 934     {
 935       MutexLocker m1(current, Module_lock);
 936       // Keep list of classes needing java.base module fixup
 937       if (!ModuleEntryTable::javabase_defined()) {
 938         assert(k->java_mirror() != nullptr, "Class's mirror is null");
 939         k->class_loader_data()->inc_keep_alive();
 940         assert(fixup_module_field_list() != nullptr, "fixup_module_field_list not initialized");
 941         fixup_module_field_list()->push(k);
 942       } else {
 943         javabase_was_defined = true;
 944       }
 945     }
 946 
 947     // If java.base was already defined then patch this particular class with java.base.
 948     if (javabase_was_defined) {
 949       ModuleEntry *javabase_entry = ModuleEntryTable::javabase_moduleEntry();
 950       assert(javabase_entry != nullptr && javabase_entry->module() != nullptr,
 951              "Setting class module field, " JAVA_BASE_NAME " should be defined");
 952       Handle javabase_handle(current, javabase_entry->module());
 953       set_module(mirror(), javabase_handle());
 954     }
 955   } else {
 956     assert(Universe::is_module_initialized() ||
 957            (ModuleEntryTable::javabase_defined() &&
 958             (module() == ModuleEntryTable::javabase_moduleEntry()->module())),
 959            "Incorrect java.lang.Module specification while creating mirror");
 960     set_module(mirror(), module());
 961   }
 962 }
 963 
 964 // Statically allocate fixup lists because they always get created.
 965 void java_lang_Class::allocate_fixup_lists() {
 966   GrowableArray<Klass*>* mirror_list =
 967     new (mtClass) GrowableArray<Klass*>(40, mtClass);
 968   set_fixup_mirror_list(mirror_list);
 969 
 970   GrowableArray<Klass*>* module_list =
 971     new (mtModule) GrowableArray<Klass*>(500, mtModule);
 972   set_fixup_module_field_list(module_list);
 973 }
 974 
 975 void java_lang_Class::allocate_mirror(Klass* k, bool is_scratch, Handle protection_domain, Handle classData,
 976                                       Handle& mirror, Handle& comp_mirror, TRAPS) {
 977   // Allocate mirror (java.lang.Class instance)
 978   oop mirror_oop = InstanceMirrorKlass::cast(vmClasses::Class_klass())->allocate_instance(k, CHECK);
 979   mirror = Handle(THREAD, mirror_oop);
 980 
 981   // Setup indirection from mirror->klass
 982   set_klass(mirror(), k);
 983 
 984   InstanceMirrorKlass* mk = InstanceMirrorKlass::cast(mirror->klass());
 985   assert(oop_size(mirror()) == mk->instance_size(k), "should have been set");
 986 
 987   set_static_oop_field_count(mirror(), mk->compute_static_oop_field_count(mirror()));
 988 
 989   // It might also have a component mirror.  This mirror must already exist.
 990   if (k->is_array_klass()) {
 991     if (k->is_typeArray_klass()) {
 992       BasicType type = TypeArrayKlass::cast(k)->element_type();
 993       if (is_scratch) {
 994         comp_mirror = Handle(THREAD, HeapShared::scratch_java_mirror(type));
 995       } else {
 996         comp_mirror = Handle(THREAD, Universe::java_mirror(type));
 997       }
 998     } else {
 999       assert(k->is_objArray_klass(), "Must be");
1000       Klass* element_klass = ObjArrayKlass::cast(k)->element_klass();
1001       assert(element_klass != nullptr, "Must have an element klass");
1002       if (is_scratch) {
1003         comp_mirror = Handle(THREAD, HeapShared::scratch_java_mirror(element_klass));
1004       } else {
1005         comp_mirror = Handle(THREAD, element_klass->java_mirror());
1006       }
1007     }
1008     assert(comp_mirror() != nullptr, "must have a mirror");
1009 
1010     // Two-way link between the array klass and its component mirror:
1011     // (array_klass) k -> mirror -> component_mirror -> array_klass -> k
1012     set_component_mirror(mirror(), comp_mirror());
1013     // See below for ordering dependencies between field array_klass in component mirror
1014     // and java_mirror in this klass.
1015   } else {
1016     assert(k->is_instance_klass(), "Must be");
1017 
1018     initialize_mirror_fields(k, mirror, protection_domain, classData, THREAD);
1019     if (HAS_PENDING_EXCEPTION) {
1020       // If any of the fields throws an exception like OOM remove the klass field
1021       // from the mirror so GC doesn't follow it after the klass has been deallocated.
1022       // This mirror looks like a primitive type, which logically it is because it
1023       // it represents no class.
1024       set_klass(mirror(), nullptr);
1025       return;
1026     }
1027   }
1028 }
1029 
1030 void java_lang_Class::create_mirror(Klass* k, Handle class_loader,
1031                                     Handle module, Handle protection_domain,
1032                                     Handle classData, TRAPS) {
1033   assert(k != nullptr, "Use create_basic_type_mirror for primitive types");
1034   assert(k->java_mirror() == nullptr, "should only assign mirror once");
1035 
1036   // Use this moment of initialization to cache modifier_flags also,
1037   // to support Class.getModifiers().  Instance classes recalculate
1038   // the cached flags after the class file is parsed, but before the
1039   // class is put into the system dictionary.
1040   int computed_modifiers = k->compute_modifier_flags();
1041   k->set_modifier_flags(computed_modifiers);
1042   // Class_klass has to be loaded because it is used to allocate
1043   // the mirror.
1044   if (vmClasses::Class_klass_loaded()) {
1045     Handle mirror;
1046     Handle comp_mirror;
1047 
1048     allocate_mirror(k, /*is_scratch=*/false, protection_domain, classData, mirror, comp_mirror, CHECK);
1049 
1050     // set the classLoader field in the java_lang_Class instance
1051     assert(class_loader() == k->class_loader(), "should be same");
1052     set_class_loader(mirror(), class_loader());
1053 
1054     // Setup indirection from klass->mirror
1055     // after any exceptions can happen during allocations.
1056     k->set_java_mirror(mirror);
1057 
1058     // Set the module field in the java_lang_Class instance.  This must be done
1059     // after the mirror is set.
1060     set_mirror_module_field(THREAD, k, mirror, module);
1061 
1062     if (comp_mirror() != nullptr) {
1063       // Set after k->java_mirror() is published, because compiled code running
1064       // concurrently doesn't expect a k to have a null java_mirror.
1065       release_set_array_klass(comp_mirror(), k);
1066     }
1067     if (CDSConfig::is_dumping_heap()) {
1068       create_scratch_mirror(k, CHECK);
1069     }
1070   } else {
1071     assert(fixup_mirror_list() != nullptr, "fixup_mirror_list not initialized");
1072     fixup_mirror_list()->push(k);
1073   }
1074 }
1075 
1076 #if INCLUDE_CDS_JAVA_HEAP
1077 // The "scratch mirror" stores the states of the mirror object that can be
1078 // decided at dump time (such as the initial values of the static fields, the
1079 // component mirror, etc). At runtime, more information is added to it by
1080 // java_lang_Class::restore_archived_mirror().
1081 //
1082 // Essentially, /*dumptime*/create_scratch_mirror() + /*runtime*/restore_archived_mirror()
1083 // produces the same result as /*runtime*/create_mirror().
1084 //
1085 // Note: we archive the "scratch mirror" instead of k->java_mirror(), because the
1086 // latter may contain dumptime-specific information that cannot be archived
1087 // (e.g., ClassLoaderData*, or static fields that are modified by Java code execution).
1088 void java_lang_Class::create_scratch_mirror(Klass* k, TRAPS) {
1089   if (k->class_loader() != nullptr &&
1090       k->class_loader() != SystemDictionary::java_platform_loader() &&
1091       k->class_loader() != SystemDictionary::java_system_loader()) {
1092     // We only archive the mirrors of classes loaded by the built-in loaders
1093     return;
1094   }
1095 
1096   Handle protection_domain, classData; // set to null. Will be reinitialized at runtime
1097   Handle mirror;
1098   Handle comp_mirror;
1099   allocate_mirror(k, /*is_scratch=*/true, protection_domain, classData, mirror, comp_mirror, CHECK);
1100 
1101   if (comp_mirror() != nullptr) {
1102     release_set_array_klass(comp_mirror(), k);
1103   }
1104 
1105   HeapShared::set_scratch_java_mirror(k, mirror());
1106 }
1107 
1108 // Returns true if the mirror is updated, false if no archived mirror
1109 // data is present. After the archived mirror object is restored, the
1110 // shared klass' _has_raw_archived_mirror flag is cleared.
1111 bool java_lang_Class::restore_archived_mirror(Klass *k,
1112                                               Handle class_loader, Handle module,
1113                                               Handle protection_domain, TRAPS) {
1114   // Postpone restoring archived mirror until java.lang.Class is loaded. Please
1115   // see more details in vmClasses::resolve_all().
1116   if (!vmClasses::Class_klass_loaded()) {
1117     assert(fixup_mirror_list() != nullptr, "fixup_mirror_list not initialized");
1118     fixup_mirror_list()->push(k);
1119     return true;
1120   }
1121 
1122   oop m = k->archived_java_mirror();
1123   assert(m != nullptr, "must have stored non-null archived mirror");
1124 
1125   // Sanity: clear it now to prevent re-initialization if any of the following fails
1126   k->clear_archived_mirror_index();
1127 
1128   // mirror is archived, restore
1129   log_debug(cds, mirror)("Archived mirror is: " PTR_FORMAT, p2i(m));
1130   assert(as_Klass(m) == k, "must be");
1131   Handle mirror(THREAD, m);
1132 
1133   if (!k->is_array_klass()) {
1134     // - local static final fields with initial values were initialized at dump time
1135 
1136     if (protection_domain.not_null()) {
1137       set_protection_domain(mirror(), protection_domain());
1138     }
1139   }
1140 
1141   assert(class_loader() == k->class_loader(), "should be same");
1142   if (class_loader.not_null()) {
1143     set_class_loader(mirror(), class_loader());
1144   }
1145 
1146   k->set_java_mirror(mirror);
1147 
1148   set_mirror_module_field(THREAD, k, mirror, module);
1149 
1150   if (log_is_enabled(Trace, cds, heap, mirror)) {
1151     ResourceMark rm(THREAD);
1152     log_trace(cds, heap, mirror)(
1153         "Restored %s archived mirror " PTR_FORMAT, k->external_name(), p2i(mirror()));
1154   }
1155 
1156   return true;
1157 }
1158 #endif // INCLUDE_CDS_JAVA_HEAP
1159 
1160 void java_lang_Class::fixup_module_field(Klass* k, Handle module) {
1161   assert(_module_offset != 0, "must have been computed already");
1162   set_module(k->java_mirror(), module());
1163 }
1164 
1165 void java_lang_Class::set_oop_size(HeapWord* java_class, size_t size) {
1166   assert(_oop_size_offset != 0, "must be set");
1167   assert(size > 0, "Oop size must be greater than zero, not " SIZE_FORMAT, size);
1168   assert(size <= INT_MAX, "Lossy conversion: " SIZE_FORMAT, size);
1169   *(int*)(((char*)java_class) + _oop_size_offset) = (int)size;
1170 }
1171 
1172 int  java_lang_Class::static_oop_field_count(oop java_class) {
1173   assert(_static_oop_field_count_offset != 0, "must be set");
1174   return java_class->int_field(_static_oop_field_count_offset);
1175 }
1176 
1177 void java_lang_Class::set_static_oop_field_count(oop java_class, int size) {
1178   assert(_static_oop_field_count_offset != 0, "must be set");
1179   java_class->int_field_put(_static_oop_field_count_offset, size);
1180 }
1181 
1182 oop java_lang_Class::protection_domain(oop java_class) {
1183   assert(_protection_domain_offset != 0, "must be set");
1184   return java_class->obj_field(_protection_domain_offset);
1185 }
1186 void java_lang_Class::set_protection_domain(oop java_class, oop pd) {
1187   assert(_protection_domain_offset != 0, "must be set");
1188   java_class->obj_field_put(_protection_domain_offset, pd);
1189 }
1190 
1191 void java_lang_Class::set_component_mirror(oop java_class, oop comp_mirror) {
1192   assert(_component_mirror_offset != 0, "must be set");
1193     java_class->obj_field_put(_component_mirror_offset, comp_mirror);
1194   }
1195 oop java_lang_Class::component_mirror(oop java_class) {
1196   assert(_component_mirror_offset != 0, "must be set");
1197   return java_class->obj_field(_component_mirror_offset);
1198 }
1199 
1200 objArrayOop java_lang_Class::signers(oop java_class) {
1201   assert(_signers_offset != 0, "must be set");
1202   return (objArrayOop)java_class->obj_field(_signers_offset);
1203 }
1204 void java_lang_Class::set_signers(oop java_class, objArrayOop signers) {
1205   assert(_signers_offset != 0, "must be set");
1206   java_class->obj_field_put(_signers_offset, signers);
1207 }
1208 
1209 oop java_lang_Class::class_data(oop java_class) {
1210   assert(_classData_offset != 0, "must be set");
1211   return java_class->obj_field(_classData_offset);
1212 }
1213 void java_lang_Class::set_class_data(oop java_class, oop class_data) {
1214   assert(_classData_offset != 0, "must be set");
1215   java_class->obj_field_put(_classData_offset, class_data);
1216 }
1217 
1218 oop java_lang_Class::reflection_data(oop java_class) {
1219   assert(_reflectionData_offset != 0, "must be set");
1220   return java_class->obj_field(_reflectionData_offset);
1221 }
1222 
1223 bool java_lang_Class::has_reflection_data(oop java_class) {
1224   return (java_lang_Class::reflection_data(java_class) != nullptr);
1225 }
1226 
1227 void java_lang_Class::set_reflection_data(oop java_class, oop reflection_data) {
1228   assert(_reflectionData_offset != 0, "must be set");
1229   java_class->obj_field_put(_reflectionData_offset, reflection_data);
1230 }
1231 
1232 void java_lang_Class::set_class_loader(oop java_class, oop loader) {
1233   assert(_class_loader_offset != 0, "offsets should have been initialized");
1234   java_class->obj_field_put(_class_loader_offset, loader);
1235 }
1236 
1237 oop java_lang_Class::class_loader(oop java_class) {
1238   assert(_class_loader_offset != 0, "must be set");
1239   return java_class->obj_field(_class_loader_offset);
1240 }
1241 
1242 oop java_lang_Class::module(oop java_class) {
1243   assert(_module_offset != 0, "must be set");
1244   return java_class->obj_field(_module_offset);
1245 }
1246 
1247 void java_lang_Class::set_module(oop java_class, oop module) {
1248   assert(_module_offset != 0, "must be set");
1249   java_class->obj_field_put(_module_offset, module);
1250 }
1251 
1252 oop java_lang_Class::name(Handle java_class, TRAPS) {
1253   assert(_name_offset != 0, "must be set");
1254   oop o = java_class->obj_field(_name_offset);
1255   if (o == nullptr) {
1256     o = StringTable::intern(as_external_name(java_class()), THREAD);
1257     java_class->obj_field_put(_name_offset, o);
1258   }
1259   return o;
1260 }
1261 
1262 oop java_lang_Class::source_file(oop java_class) {
1263   assert(_source_file_offset != 0, "must be set");
1264   return java_class->obj_field(_source_file_offset);
1265 }
1266 
1267 void java_lang_Class::set_source_file(oop java_class, oop source_file) {
1268   assert(_source_file_offset != 0, "must be set");
1269   java_class->obj_field_put(_source_file_offset, source_file);
1270 }
1271 
1272 oop java_lang_Class::create_basic_type_mirror(const char* basic_type_name, BasicType type, TRAPS) {
1273   // This should be improved by adding a field at the Java level or by
1274   // introducing a new VM klass (see comment in ClassFileParser)
1275   oop java_class = InstanceMirrorKlass::cast(vmClasses::Class_klass())->allocate_instance(nullptr, CHECK_NULL);
1276   if (type != T_VOID) {
1277     Klass* aklass = Universe::typeArrayKlassObj(type);
1278     assert(aklass != nullptr, "correct bootstrap");
1279     release_set_array_klass(java_class, aklass);
1280   }
1281 #ifdef ASSERT
1282   InstanceMirrorKlass* mk = InstanceMirrorKlass::cast(vmClasses::Class_klass());
1283   assert(static_oop_field_count(java_class) == 0, "should have been zeroed by allocation");
1284 #endif
1285   return java_class;
1286 }
1287 
1288 void java_lang_Class::set_klass(oop java_class, Klass* klass) {
1289   assert(is_instance(java_class), "must be a Class object");
1290   java_class->metadata_field_put(_klass_offset, klass);
1291 }
1292 
1293 
1294 void java_lang_Class::print_signature(oop java_class, outputStream* st) {
1295   assert(is_instance(java_class), "must be a Class object");
1296   Symbol* name = nullptr;
1297   bool is_instance = false;
1298   if (is_primitive(java_class)) {
1299     name = vmSymbols::type_signature(primitive_type(java_class));
1300   } else {
1301     Klass* k = as_Klass(java_class);
1302     is_instance = k->is_instance_klass();
1303     name = k->name();
1304   }
1305   if (name == nullptr) {
1306     st->print("<null>");
1307     return;
1308   }
1309   if (is_instance)  st->print("L");
1310   st->write((char*) name->base(), (int) name->utf8_length());
1311   if (is_instance)  st->print(";");
1312 }
1313 
1314 Symbol* java_lang_Class::as_signature(oop java_class, bool intern_if_not_found) {
1315   assert(is_instance(java_class), "must be a Class object");
1316   Symbol* name;
1317   if (is_primitive(java_class)) {
1318     name = vmSymbols::type_signature(primitive_type(java_class));
1319     // Because this can create a new symbol, the caller has to decrement
1320     // the refcount, so make adjustment here and below for symbols returned
1321     // that are not created or incremented due to a successful lookup.
1322     name->increment_refcount();
1323   } else {
1324     Klass* k = as_Klass(java_class);
1325     if (!k->is_instance_klass()) {
1326       name = k->name();
1327       name->increment_refcount();
1328     } else {
1329       ResourceMark rm;
1330       const char* sigstr = k->signature_name();
1331       int         siglen = (int) strlen(sigstr);
1332       if (!intern_if_not_found) {
1333         name = SymbolTable::probe(sigstr, siglen);
1334       } else {
1335         name = SymbolTable::new_symbol(sigstr, siglen);
1336       }
1337     }
1338   }
1339   return name;
1340 }
1341 
1342 // Returns the Java name for this Java mirror (Resource allocated)
1343 // See Klass::external_name().
1344 // For primitive type Java mirrors, its type name is returned.
1345 const char* java_lang_Class::as_external_name(oop java_class) {
1346   assert(is_instance(java_class), "must be a Class object");
1347   const char* name = nullptr;
1348   if (is_primitive(java_class)) {
1349     name = type2name(primitive_type(java_class));
1350   } else {
1351     name = as_Klass(java_class)->external_name();
1352   }
1353   if (name == nullptr) {
1354     name = "<null>";
1355   }
1356   return name;
1357 }
1358 
1359 Klass* java_lang_Class::array_klass_acquire(oop java_class) {
1360   Klass* k = ((Klass*)java_class->metadata_field_acquire(_array_klass_offset));
1361   assert(k == nullptr || (k->is_klass() && k->is_array_klass()), "should be array klass");
1362   return k;
1363 }
1364 
1365 
1366 void java_lang_Class::release_set_array_klass(oop java_class, Klass* klass) {
1367   assert(klass->is_klass() && klass->is_array_klass(), "should be array klass");
1368   java_class->release_metadata_field_put(_array_klass_offset, klass);
1369 }
1370 
1371 
1372 BasicType java_lang_Class::primitive_type(oop java_class) {
1373   assert(is_primitive(java_class), "just checking");
1374   Klass* ak = ((Klass*)java_class->metadata_field(_array_klass_offset));
1375   BasicType type = T_VOID;
1376   if (ak != nullptr) {
1377     // Note: create_basic_type_mirror above initializes ak to a non-null value.
1378     type = ArrayKlass::cast(ak)->element_type();
1379   } else {
1380     assert(java_class == Universe::void_mirror(), "only valid non-array primitive");
1381   }
1382 #ifdef ASSERT
1383   if (CDSConfig::is_dumping_heap()) {
1384     oop mirror = Universe::java_mirror(type);
1385     oop scratch_mirror = HeapShared::scratch_java_mirror(type);
1386     assert(java_class == mirror || java_class == scratch_mirror, "must be consistent");
1387   } else {
1388     assert(Universe::java_mirror(type) == java_class, "must be consistent");
1389   }
1390 #endif
1391   return type;
1392 }
1393 
1394 BasicType java_lang_Class::as_BasicType(oop java_class, Klass** reference_klass) {
1395   assert(is_instance(java_class), "must be a Class object");
1396   if (is_primitive(java_class)) {
1397     if (reference_klass != nullptr)
1398       (*reference_klass) = nullptr;
1399     return primitive_type(java_class);
1400   } else {
1401     if (reference_klass != nullptr)
1402       (*reference_klass) = as_Klass(java_class);
1403     return T_OBJECT;
1404   }
1405 }
1406 
1407 
1408 oop java_lang_Class::primitive_mirror(BasicType t) {
1409   oop mirror = Universe::java_mirror(t);
1410   assert(mirror != nullptr && mirror->is_a(vmClasses::Class_klass()), "must be a Class");
1411   assert(is_primitive(mirror), "must be primitive");
1412   return mirror;
1413 }
1414 
1415 #define CLASS_FIELDS_DO(macro) \
1416   macro(_classRedefinedCount_offset, k, "classRedefinedCount", int_signature,         false); \
1417   macro(_class_loader_offset,        k, "classLoader",         classloader_signature, false); \
1418   macro(_component_mirror_offset,    k, "componentType",       class_signature,       false); \
1419   macro(_module_offset,              k, "module",              module_signature,      false); \
1420   macro(_name_offset,                k, "name",                string_signature,      false); \
1421   macro(_classData_offset,           k, "classData",           object_signature,      false); \
1422   macro(_reflectionData_offset,      k, "reflectionData",      class_ReflectionData_signature, false); \
1423 
1424 void java_lang_Class::compute_offsets() {
1425   if (_offsets_computed) {
1426     return;
1427   }
1428 
1429   _offsets_computed = true;
1430 
1431   InstanceKlass* k = vmClasses::Class_klass();
1432   CLASS_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1433 
1434   CLASS_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
1435 }
1436 
1437 #if INCLUDE_CDS
1438 void java_lang_Class::serialize_offsets(SerializeClosure* f) {
1439   f->do_bool(&_offsets_computed);
1440 
1441   CLASS_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
1442 
1443   CLASS_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
1444 }
1445 #endif
1446 
1447 int java_lang_Class::classRedefinedCount(oop the_class_mirror) {
1448   assert(_classRedefinedCount_offset != 0, "offsets should have been initialized");
1449   return the_class_mirror->int_field(_classRedefinedCount_offset);
1450 }
1451 
1452 void java_lang_Class::set_classRedefinedCount(oop the_class_mirror, int value) {
1453   assert(_classRedefinedCount_offset != 0, "offsets should have been initialized");
1454   the_class_mirror->int_field_put(_classRedefinedCount_offset, value);
1455 }
1456 
1457 
1458 // Note: JDK1.1 and before had a privateInfo_offset field which was used for the
1459 //       platform thread structure, and a eetop offset which was used for thread
1460 //       local storage (and unused by the HotSpot VM). In JDK1.2 the two structures
1461 //       merged, so in the HotSpot VM we just use the eetop field for the thread
1462 //       instead of the privateInfo_offset.
1463 //
1464 // Note: The stackSize field is only present starting in 1.4.
1465 
1466 int java_lang_Thread_FieldHolder::_group_offset;
1467 int java_lang_Thread_FieldHolder::_priority_offset;
1468 int java_lang_Thread_FieldHolder::_stackSize_offset;
1469 int java_lang_Thread_FieldHolder::_daemon_offset;
1470 int java_lang_Thread_FieldHolder::_thread_status_offset;
1471 
1472 #define THREAD_FIELD_HOLDER_FIELDS_DO(macro) \
1473   macro(_group_offset,         k, vmSymbols::group_name(),    threadgroup_signature, false); \
1474   macro(_priority_offset,      k, vmSymbols::priority_name(), int_signature,         false); \
1475   macro(_stackSize_offset,     k, "stackSize",                long_signature,        false); \
1476   macro(_daemon_offset,        k, vmSymbols::daemon_name(),   bool_signature,        false); \
1477   macro(_thread_status_offset, k, "threadStatus",             int_signature,         false)
1478 
1479 void java_lang_Thread_FieldHolder::compute_offsets() {
1480   assert(_group_offset == 0, "offsets should be initialized only once");
1481 
1482   InstanceKlass* k = vmClasses::Thread_FieldHolder_klass();
1483   THREAD_FIELD_HOLDER_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1484 }
1485 
1486 #if INCLUDE_CDS
1487 void java_lang_Thread_FieldHolder::serialize_offsets(SerializeClosure* f) {
1488   THREAD_FIELD_HOLDER_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
1489 }
1490 #endif
1491 
1492 oop java_lang_Thread_FieldHolder::threadGroup(oop holder) {
1493   return holder->obj_field(_group_offset);
1494 }
1495 
1496 ThreadPriority java_lang_Thread_FieldHolder::priority(oop holder) {
1497   return (ThreadPriority)holder->int_field(_priority_offset);
1498 }
1499 
1500 void java_lang_Thread_FieldHolder::set_priority(oop holder, ThreadPriority priority) {
1501   holder->int_field_put(_priority_offset, priority);
1502 }
1503 
1504 jlong java_lang_Thread_FieldHolder::stackSize(oop holder) {
1505   return holder->long_field(_stackSize_offset);
1506 }
1507 
1508 bool java_lang_Thread_FieldHolder::is_daemon(oop holder) {
1509   return holder->bool_field(_daemon_offset) != 0;
1510 }
1511 
1512 void java_lang_Thread_FieldHolder::set_daemon(oop holder, bool val) {
1513   assert(val, "daemon status is never turned off");
1514   holder->bool_field_put(_daemon_offset, val);
1515 }
1516 
1517 void java_lang_Thread_FieldHolder::set_thread_status(oop holder, JavaThreadStatus status) {
1518   holder->int_field_put(_thread_status_offset, static_cast<int>(status));
1519 }
1520 
1521 JavaThreadStatus java_lang_Thread_FieldHolder::get_thread_status(oop holder) {
1522   return static_cast<JavaThreadStatus>(holder->int_field(_thread_status_offset));
1523 }
1524 
1525 
1526 int java_lang_Thread_Constants::_static_VTHREAD_GROUP_offset = 0;
1527 
1528 #define THREAD_CONSTANTS_STATIC_FIELDS_DO(macro) \
1529   macro(_static_VTHREAD_GROUP_offset,             k, "VTHREAD_GROUP",             threadgroup_signature, true);
1530 
1531 void java_lang_Thread_Constants::compute_offsets() {
1532   assert(_static_VTHREAD_GROUP_offset == 0, "offsets should be initialized only once");
1533 
1534   InstanceKlass* k = vmClasses::Thread_Constants_klass();
1535   THREAD_CONSTANTS_STATIC_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1536 }
1537 
1538 #if INCLUDE_CDS
1539 void java_lang_Thread_Constants::serialize_offsets(SerializeClosure* f) {
1540   THREAD_CONSTANTS_STATIC_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
1541 }
1542 #endif
1543 
1544 oop java_lang_Thread_Constants::get_VTHREAD_GROUP() {
1545   InstanceKlass* k = vmClasses::Thread_Constants_klass();
1546   oop base = k->static_field_base_raw();
1547   return base->obj_field(_static_VTHREAD_GROUP_offset);
1548 }
1549 
1550 
1551 int java_lang_Thread::_holder_offset;
1552 int java_lang_Thread::_name_offset;
1553 int java_lang_Thread::_contextClassLoader_offset;
1554 int java_lang_Thread::_inheritedAccessControlContext_offset;
1555 int java_lang_Thread::_eetop_offset;
1556 int java_lang_Thread::_jvmti_thread_state_offset;
1557 int java_lang_Thread::_jvmti_VTMS_transition_disable_count_offset;
1558 int java_lang_Thread::_jvmti_is_in_VTMS_transition_offset;
1559 int java_lang_Thread::_interrupted_offset;
1560 int java_lang_Thread::_tid_offset;
1561 int java_lang_Thread::_continuation_offset;
1562 int java_lang_Thread::_park_blocker_offset;
1563 int java_lang_Thread::_scopedValueBindings_offset;
1564 JFR_ONLY(int java_lang_Thread::_jfr_epoch_offset;)
1565 
1566 #define THREAD_FIELDS_DO(macro) \
1567   macro(_holder_offset,        k, "holder", thread_fieldholder_signature, false); \
1568   macro(_name_offset,          k, vmSymbols::name_name(), string_signature, false); \
1569   macro(_contextClassLoader_offset, k, vmSymbols::contextClassLoader_name(), classloader_signature, false); \
1570   macro(_inheritedAccessControlContext_offset, k, vmSymbols::inheritedAccessControlContext_name(), accesscontrolcontext_signature, false); \
1571   macro(_eetop_offset,         k, "eetop", long_signature, false); \
1572   macro(_interrupted_offset,   k, "interrupted", bool_signature, false); \
1573   macro(_tid_offset,           k, "tid", long_signature, false); \
1574   macro(_park_blocker_offset,  k, "parkBlocker", object_signature, false); \
1575   macro(_continuation_offset,  k, "cont", continuation_signature, false); \
1576   macro(_scopedValueBindings_offset, k, "scopedValueBindings", object_signature, false);
1577 
1578 void java_lang_Thread::compute_offsets() {
1579   assert(_holder_offset == 0, "offsets should be initialized only once");
1580 
1581   InstanceKlass* k = vmClasses::Thread_klass();
1582   THREAD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1583   THREAD_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
1584 }
1585 
1586 #if INCLUDE_CDS
1587 void java_lang_Thread::serialize_offsets(SerializeClosure* f) {
1588   THREAD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
1589   THREAD_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
1590 }
1591 #endif
1592 
1593 JavaThread* java_lang_Thread::thread(oop java_thread) {
1594   return reinterpret_cast<JavaThread*>(java_thread->address_field(_eetop_offset));
1595 }
1596 
1597 JavaThread* java_lang_Thread::thread_acquire(oop java_thread) {
1598   return reinterpret_cast<JavaThread*>(java_thread->address_field_acquire(_eetop_offset));
1599 }
1600 
1601 void java_lang_Thread::set_thread(oop java_thread, JavaThread* thread) {
1602   java_thread->address_field_put(_eetop_offset, (address)thread);
1603 }
1604 
1605 void java_lang_Thread::release_set_thread(oop java_thread, JavaThread* thread) {
1606   java_thread->release_address_field_put(_eetop_offset, (address)thread);
1607 }
1608 
1609 JvmtiThreadState* java_lang_Thread::jvmti_thread_state(oop java_thread) {
1610   return (JvmtiThreadState*)java_thread->address_field(_jvmti_thread_state_offset);
1611 }
1612 
1613 void java_lang_Thread::set_jvmti_thread_state(oop java_thread, JvmtiThreadState* state) {
1614   java_thread->address_field_put(_jvmti_thread_state_offset, (address)state);
1615 }
1616 
1617 int java_lang_Thread::VTMS_transition_disable_count(oop java_thread) {
1618   return java_thread->int_field(_jvmti_VTMS_transition_disable_count_offset);
1619 }
1620 
1621 void java_lang_Thread::inc_VTMS_transition_disable_count(oop java_thread) {
1622   assert(JvmtiVTMSTransition_lock->owned_by_self(), "Must be locked");
1623   int val = VTMS_transition_disable_count(java_thread);
1624   java_thread->int_field_put(_jvmti_VTMS_transition_disable_count_offset, val + 1);
1625 }
1626 
1627 void java_lang_Thread::dec_VTMS_transition_disable_count(oop java_thread) {
1628   assert(JvmtiVTMSTransition_lock->owned_by_self(), "Must be locked");
1629   int val = VTMS_transition_disable_count(java_thread);
1630   assert(val > 0, "VTMS_transition_disable_count should never be negative");
1631   java_thread->int_field_put(_jvmti_VTMS_transition_disable_count_offset, val - 1);
1632 }
1633 
1634 bool java_lang_Thread::is_in_VTMS_transition(oop java_thread) {
1635   return java_thread->bool_field_volatile(_jvmti_is_in_VTMS_transition_offset);
1636 }
1637 
1638 void java_lang_Thread::set_is_in_VTMS_transition(oop java_thread, bool val) {
1639   java_thread->bool_field_put_volatile(_jvmti_is_in_VTMS_transition_offset, val);
1640 }
1641 
1642 int java_lang_Thread::is_in_VTMS_transition_offset() {
1643   return _jvmti_is_in_VTMS_transition_offset;
1644 }
1645 
1646 void java_lang_Thread::clear_scopedValueBindings(oop java_thread) {
1647   assert(java_thread != nullptr, "need a java_lang_Thread pointer here");
1648   java_thread->obj_field_put(_scopedValueBindings_offset, nullptr);
1649 }
1650 
1651 oop java_lang_Thread::holder(oop java_thread) {
1652   // Note: may return null if the thread is still attaching
1653   return java_thread->obj_field(_holder_offset);
1654 }
1655 
1656 bool java_lang_Thread::interrupted(oop java_thread) {
1657   // Make sure the caller can safely access oops.
1658   assert(Thread::current()->is_VM_thread() ||
1659          (JavaThread::current()->thread_state() != _thread_blocked &&
1660           JavaThread::current()->thread_state() != _thread_in_native),
1661          "Unsafe access to oop");
1662   return java_thread->bool_field_volatile(_interrupted_offset);
1663 }
1664 
1665 void java_lang_Thread::set_interrupted(oop java_thread, bool val) {
1666   // Make sure the caller can safely access oops.
1667   assert(Thread::current()->is_VM_thread() ||
1668          (JavaThread::current()->thread_state() != _thread_blocked &&
1669           JavaThread::current()->thread_state() != _thread_in_native),
1670          "Unsafe access to oop");
1671   java_thread->bool_field_put_volatile(_interrupted_offset, val);
1672 }
1673 
1674 
1675 oop java_lang_Thread::name(oop java_thread) {
1676   return java_thread->obj_field(_name_offset);
1677 }
1678 
1679 
1680 void java_lang_Thread::set_name(oop java_thread, oop name) {
1681   java_thread->obj_field_put(_name_offset, name);
1682 }
1683 
1684 // Convenience macros for setting and getting Thread fields that
1685 // are actually stored in the FieldHolder object of the thread.
1686 // The FieldHolder can be null whilst a thread is attaching via
1687 // JNI, and when the main thread is attaching.
1688 
1689 // The default value should be the default/zero initialized value
1690 // of the field as it would be in java.lang.Thread.FieldHolder.
1691 #define GET_FIELDHOLDER_FIELD(java_thread, field, default_val)  \
1692   {                                                             \
1693     oop holder = java_lang_Thread::holder(java_thread);         \
1694     if (holder != nullptr)                                      \
1695       return java_lang_Thread_FieldHolder::field(holder);       \
1696     else                                                        \
1697       return default_val;                                       \
1698   }
1699 
1700 // We should never be trying to set a field of an attaching thread.
1701 #define SET_FIELDHOLDER_FIELD(java_thread, field, value)        \
1702   {                                                             \
1703     oop holder = java_lang_Thread::holder(java_thread);         \
1704     assert(holder != nullptr, "Thread not fully initialized");  \
1705     java_lang_Thread_FieldHolder::set_##field(holder, value);   \
1706   }
1707 
1708 
1709 ThreadPriority java_lang_Thread::priority(oop java_thread) {
1710   GET_FIELDHOLDER_FIELD(java_thread, priority, (ThreadPriority)0);
1711 }
1712 
1713 
1714 void java_lang_Thread::set_priority(oop java_thread, ThreadPriority priority) {
1715   SET_FIELDHOLDER_FIELD(java_thread, priority, priority)
1716 }
1717 
1718 
1719 oop java_lang_Thread::threadGroup(oop java_thread) {
1720   GET_FIELDHOLDER_FIELD(java_thread, threadGroup, nullptr);
1721 }
1722 
1723 
1724 bool java_lang_Thread::is_alive(oop java_thread) {
1725   JavaThread* thr = java_lang_Thread::thread(java_thread);
1726   return (thr != nullptr);
1727 }
1728 
1729 
1730 bool java_lang_Thread::is_daemon(oop java_thread) {
1731   GET_FIELDHOLDER_FIELD(java_thread, is_daemon, false);
1732 }
1733 
1734 
1735 void java_lang_Thread::set_daemon(oop java_thread) {
1736   SET_FIELDHOLDER_FIELD(java_thread, daemon, true);
1737 }
1738 
1739 oop java_lang_Thread::context_class_loader(oop java_thread) {
1740   return java_thread->obj_field(_contextClassLoader_offset);
1741 }
1742 
1743 oop java_lang_Thread::inherited_access_control_context(oop java_thread) {
1744   return java_thread->obj_field(_inheritedAccessControlContext_offset);
1745 }
1746 
1747 
1748 jlong java_lang_Thread::stackSize(oop java_thread) {
1749   GET_FIELDHOLDER_FIELD(java_thread, stackSize, 0);
1750 }
1751 
1752 // Write the thread status value to threadStatus field in java.lang.Thread java class.
1753 void java_lang_Thread::set_thread_status(oop java_thread, JavaThreadStatus status) {
1754   SET_FIELDHOLDER_FIELD(java_thread, thread_status, status);
1755 }
1756 
1757 // Read thread status value from threadStatus field in java.lang.Thread java class.
1758 JavaThreadStatus java_lang_Thread::get_thread_status(oop java_thread) {
1759   // Make sure the caller is operating on behalf of the VM or is
1760   // running VM code (state == _thread_in_vm).
1761   assert(Threads_lock->owned_by_self() || Thread::current()->is_VM_thread() ||
1762          JavaThread::current()->thread_state() == _thread_in_vm,
1763          "Java Thread is not running in vm");
1764   GET_FIELDHOLDER_FIELD(java_thread, get_thread_status, JavaThreadStatus::NEW /* not initialized */);
1765 }
1766 
1767 ByteSize java_lang_Thread::thread_id_offset() {
1768   return in_ByteSize(_tid_offset);
1769 }
1770 
1771 oop java_lang_Thread::park_blocker(oop java_thread) {
1772   return java_thread->obj_field(_park_blocker_offset);
1773 }
1774 
1775 oop java_lang_Thread::async_get_stack_trace(oop java_thread, TRAPS) {
1776   ThreadsListHandle tlh(JavaThread::current());
1777   JavaThread* thread;
1778   bool is_virtual = java_lang_VirtualThread::is_instance(java_thread);
1779   if (is_virtual) {
1780     oop carrier_thread = java_lang_VirtualThread::carrier_thread(java_thread);
1781     if (carrier_thread == nullptr) {
1782       return nullptr;
1783     }
1784     thread = java_lang_Thread::thread(carrier_thread);
1785   } else {
1786     thread = java_lang_Thread::thread(java_thread);
1787   }
1788   if (thread == nullptr) {
1789     return nullptr;
1790   }
1791 
1792   class GetStackTraceClosure : public HandshakeClosure {
1793   public:
1794     const Handle _java_thread;
1795     int _depth;
1796     bool _retry_handshake;
1797     GrowableArray<Method*>* _methods;
1798     GrowableArray<int>*     _bcis;
1799 
1800     GetStackTraceClosure(Handle java_thread) :
1801         HandshakeClosure("GetStackTraceClosure"), _java_thread(java_thread), _depth(0), _retry_handshake(false),
1802         _methods(nullptr), _bcis(nullptr) {
1803     }
1804     ~GetStackTraceClosure() {
1805       delete _methods;
1806       delete _bcis;
1807     }
1808 
1809     bool read_reset_retry() {
1810       bool ret = _retry_handshake;
1811       // If we re-execute the handshake this method need to return false
1812       // when the handshake cannot be performed. (E.g. thread terminating)
1813       _retry_handshake = false;
1814       return ret;
1815     }
1816 
1817     void do_thread(Thread* th) {
1818       if (!Thread::current()->is_Java_thread()) {
1819         _retry_handshake = true;
1820         return;
1821       }
1822 
1823       JavaThread* thread = JavaThread::cast(th);
1824 
1825       if (!thread->has_last_Java_frame()) {
1826         return;
1827       }
1828 
1829       bool carrier = false;
1830       if (java_lang_VirtualThread::is_instance(_java_thread())) {
1831         // if (thread->vthread() != _java_thread()) // We might be inside a System.executeOnCarrierThread
1832         const ContinuationEntry* ce = thread->vthread_continuation();
1833         if (ce == nullptr || ce->cont_oop(thread) != java_lang_VirtualThread::continuation(_java_thread())) {
1834           return; // not mounted
1835         }
1836       } else {
1837         carrier = (thread->vthread_continuation() != nullptr);
1838       }
1839 
1840       const int max_depth = MaxJavaStackTraceDepth;
1841       const bool skip_hidden = !ShowHiddenFrames;
1842 
1843       // Pick minimum length that will cover most cases
1844       int init_length = 64;
1845       _methods = new (mtInternal) GrowableArray<Method*>(init_length, mtInternal);
1846       _bcis = new (mtInternal) GrowableArray<int>(init_length, mtInternal);
1847 
1848       int total_count = 0;
1849       for (vframeStream vfst(thread, false, false, carrier); // we don't process frames as we don't care about oops
1850            !vfst.at_end() && (max_depth == 0 || max_depth != total_count);
1851            vfst.next()) {
1852 
1853         if (skip_hidden && (vfst.method()->is_hidden() ||
1854                             vfst.method()->is_continuation_enter_intrinsic())) {
1855           continue;
1856         }
1857 
1858         _methods->push(vfst.method());
1859         _bcis->push(vfst.bci());
1860         total_count++;
1861       }
1862 
1863       _depth = total_count;
1864     }
1865   };
1866 
1867   // Handshake with target
1868   ResourceMark rm(THREAD);
1869   HandleMark   hm(THREAD);
1870   GetStackTraceClosure gstc(Handle(THREAD, java_thread));
1871   do {
1872    Handshake::execute(&gstc, &tlh, thread);
1873   } while (gstc.read_reset_retry());
1874 
1875   // Stop if no stack trace is found.
1876   if (gstc._depth == 0) {
1877     return nullptr;
1878   }
1879 
1880   // Convert to StackTraceElement array
1881   InstanceKlass* k = vmClasses::StackTraceElement_klass();
1882   assert(k != nullptr, "must be loaded in 1.4+");
1883   if (k->should_be_initialized()) {
1884     k->initialize(CHECK_NULL);
1885   }
1886   objArrayHandle trace = oopFactory::new_objArray_handle(k, gstc._depth, CHECK_NULL);
1887 
1888   for (int i = 0; i < gstc._depth; i++) {
1889     methodHandle method(THREAD, gstc._methods->at(i));
1890     oop element = java_lang_StackTraceElement::create(method,
1891                                                       gstc._bcis->at(i),
1892                                                       CHECK_NULL);
1893     trace->obj_at_put(i, element);
1894   }
1895 
1896   return trace();
1897 }
1898 
1899 const char* java_lang_Thread::thread_status_name(oop java_thread) {
1900   JavaThreadStatus status = get_thread_status(java_thread);
1901   switch (status) {
1902     case JavaThreadStatus::NEW                      : return "NEW";
1903     case JavaThreadStatus::RUNNABLE                 : return "RUNNABLE";
1904     case JavaThreadStatus::SLEEPING                 : return "TIMED_WAITING (sleeping)";
1905     case JavaThreadStatus::IN_OBJECT_WAIT           : return "WAITING (on object monitor)";
1906     case JavaThreadStatus::IN_OBJECT_WAIT_TIMED     : return "TIMED_WAITING (on object monitor)";
1907     case JavaThreadStatus::PARKED                   : return "WAITING (parking)";
1908     case JavaThreadStatus::PARKED_TIMED             : return "TIMED_WAITING (parking)";
1909     case JavaThreadStatus::BLOCKED_ON_MONITOR_ENTER : return "BLOCKED (on object monitor)";
1910     case JavaThreadStatus::TERMINATED               : return "TERMINATED";
1911     default                       : return "UNKNOWN";
1912   };
1913 }
1914 int java_lang_ThreadGroup::_parent_offset;
1915 int java_lang_ThreadGroup::_name_offset;
1916 int java_lang_ThreadGroup::_maxPriority_offset;
1917 int java_lang_ThreadGroup::_daemon_offset;
1918 
1919 oop  java_lang_ThreadGroup::parent(oop java_thread_group) {
1920   assert(oopDesc::is_oop(java_thread_group), "thread group must be oop");
1921   return java_thread_group->obj_field(_parent_offset);
1922 }
1923 
1924 // ("name as oop" accessor is not necessary)
1925 
1926 const char* java_lang_ThreadGroup::name(oop java_thread_group) {
1927   oop name = java_thread_group->obj_field(_name_offset);
1928   // ThreadGroup.name can be null
1929   if (name != nullptr) {
1930     return java_lang_String::as_utf8_string(name);
1931   }
1932   return nullptr;
1933 }
1934 
1935 ThreadPriority java_lang_ThreadGroup::maxPriority(oop java_thread_group) {
1936   assert(oopDesc::is_oop(java_thread_group), "thread group must be oop");
1937   return (ThreadPriority) java_thread_group->int_field(_maxPriority_offset);
1938 }
1939 
1940 bool java_lang_ThreadGroup::is_daemon(oop java_thread_group) {
1941   assert(oopDesc::is_oop(java_thread_group), "thread group must be oop");
1942   return java_thread_group->bool_field(_daemon_offset) != 0;
1943 }
1944 
1945 #define THREADGROUP_FIELDS_DO(macro) \
1946   macro(_parent_offset,      k, vmSymbols::parent_name(),      threadgroup_signature,         false); \
1947   macro(_name_offset,        k, vmSymbols::name_name(),        string_signature,              false); \
1948   macro(_maxPriority_offset, k, vmSymbols::maxPriority_name(), int_signature,                 false); \
1949   macro(_daemon_offset,      k, vmSymbols::daemon_name(),      bool_signature,                false);
1950 
1951 void java_lang_ThreadGroup::compute_offsets() {
1952   assert(_parent_offset == 0, "offsets should be initialized only once");
1953 
1954   InstanceKlass* k = vmClasses::ThreadGroup_klass();
1955   THREADGROUP_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1956 }
1957 
1958 #if INCLUDE_CDS
1959 void java_lang_ThreadGroup::serialize_offsets(SerializeClosure* f) {
1960   THREADGROUP_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
1961 }
1962 #endif
1963 
1964 
1965 // java_lang_VirtualThread
1966 
1967 int java_lang_VirtualThread::static_vthread_scope_offset;
1968 int java_lang_VirtualThread::_carrierThread_offset;
1969 int java_lang_VirtualThread::_continuation_offset;
1970 int java_lang_VirtualThread::_state_offset;
1971 
1972 #define VTHREAD_FIELDS_DO(macro) \
1973   macro(static_vthread_scope_offset,       k, "VTHREAD_SCOPE",      continuationscope_signature, true);  \
1974   macro(_carrierThread_offset,             k, "carrierThread",      thread_signature,            false); \
1975   macro(_continuation_offset,              k, "cont",               continuation_signature,      false); \
1976   macro(_state_offset,                     k, "state",              int_signature,               false)
1977 
1978 
1979 void java_lang_VirtualThread::compute_offsets() {
1980   InstanceKlass* k = vmClasses::VirtualThread_klass();
1981   VTHREAD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1982 }
1983 
1984 bool java_lang_VirtualThread::is_instance(oop obj) {
1985   return obj != nullptr && is_subclass(obj->klass());
1986 }
1987 
1988 oop java_lang_VirtualThread::carrier_thread(oop vthread) {
1989   oop thread = vthread->obj_field(_carrierThread_offset);
1990   return thread;
1991 }
1992 
1993 oop java_lang_VirtualThread::continuation(oop vthread) {
1994   oop cont = vthread->obj_field(_continuation_offset);
1995   return cont;
1996 }
1997 
1998 int java_lang_VirtualThread::state(oop vthread) {
1999   return vthread->int_field_acquire(_state_offset);
2000 }
2001 
2002 JavaThreadStatus java_lang_VirtualThread::map_state_to_thread_status(int state) {
2003   JavaThreadStatus status = JavaThreadStatus::NEW;
2004   switch (state & ~SUSPENDED) {
2005     case NEW:
2006       status = JavaThreadStatus::NEW;
2007       break;
2008     case STARTED:
2009     case RUNNING:
2010     case PARKING:
2011     case TIMED_PARKING:
2012     case UNPARKED:
2013     case YIELDING:
2014     case YIELDED:
2015       status = JavaThreadStatus::RUNNABLE;
2016       break;
2017     case PARKED:
2018     case PINNED:
2019       status = JavaThreadStatus::PARKED;
2020       break;
2021     case TIMED_PARKED:
2022     case TIMED_PINNED:
2023       status = JavaThreadStatus::PARKED_TIMED;
2024       break;
2025     case TERMINATED:
2026       status = JavaThreadStatus::TERMINATED;
2027       break;
2028     default:
2029       ShouldNotReachHere();
2030   }
2031   return status;
2032 }
2033 
2034 #if INCLUDE_CDS
2035 void java_lang_VirtualThread::serialize_offsets(SerializeClosure* f) {
2036    VTHREAD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
2037 }
2038 #endif
2039 
2040 // java_lang_Throwable
2041 
2042 int java_lang_Throwable::_backtrace_offset;
2043 int java_lang_Throwable::_detailMessage_offset;
2044 int java_lang_Throwable::_stackTrace_offset;
2045 int java_lang_Throwable::_depth_offset;
2046 int java_lang_Throwable::_cause_offset;
2047 int java_lang_Throwable::_static_unassigned_stacktrace_offset;
2048 
2049 #define THROWABLE_FIELDS_DO(macro) \
2050   macro(_backtrace_offset,     k, "backtrace",     object_signature,                  false); \
2051   macro(_detailMessage_offset, k, "detailMessage", string_signature,                  false); \
2052   macro(_stackTrace_offset,    k, "stackTrace",    java_lang_StackTraceElement_array, false); \
2053   macro(_depth_offset,         k, "depth",         int_signature,                     false); \
2054   macro(_cause_offset,         k, "cause",         throwable_signature,               false); \
2055   macro(_static_unassigned_stacktrace_offset, k, "UNASSIGNED_STACK", java_lang_StackTraceElement_array, true)
2056 
2057 void java_lang_Throwable::compute_offsets() {
2058   InstanceKlass* k = vmClasses::Throwable_klass();
2059   THROWABLE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
2060 }
2061 
2062 #if INCLUDE_CDS
2063 void java_lang_Throwable::serialize_offsets(SerializeClosure* f) {
2064   THROWABLE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
2065 }
2066 #endif
2067 
2068 oop java_lang_Throwable::unassigned_stacktrace() {
2069   InstanceKlass* ik = vmClasses::Throwable_klass();
2070   oop base = ik->static_field_base_raw();
2071   return base->obj_field(_static_unassigned_stacktrace_offset);
2072 }
2073 
2074 oop java_lang_Throwable::backtrace(oop throwable) {
2075   return throwable->obj_field_acquire(_backtrace_offset);
2076 }
2077 
2078 
2079 void java_lang_Throwable::set_backtrace(oop throwable, oop value) {
2080   throwable->release_obj_field_put(_backtrace_offset, value);
2081 }
2082 
2083 int java_lang_Throwable::depth(oop throwable) {
2084   return throwable->int_field(_depth_offset);
2085 }
2086 
2087 void java_lang_Throwable::set_depth(oop throwable, int value) {
2088   throwable->int_field_put(_depth_offset, value);
2089 }
2090 
2091 oop java_lang_Throwable::message(oop throwable) {
2092   return throwable->obj_field(_detailMessage_offset);
2093 }
2094 
2095 oop java_lang_Throwable::cause(oop throwable) {
2096   return throwable->obj_field(_cause_offset);
2097 }
2098 
2099 // Return Symbol for detailed_message or null
2100 Symbol* java_lang_Throwable::detail_message(oop throwable) {
2101   PreserveExceptionMark pm(Thread::current());
2102   oop detailed_message = java_lang_Throwable::message(throwable);
2103   if (detailed_message != nullptr) {
2104     return java_lang_String::as_symbol(detailed_message);
2105   }
2106   return nullptr;
2107 }
2108 
2109 void java_lang_Throwable::set_message(oop throwable, oop value) {
2110   throwable->obj_field_put(_detailMessage_offset, value);
2111 }
2112 
2113 
2114 void java_lang_Throwable::set_stacktrace(oop throwable, oop st_element_array) {
2115   throwable->obj_field_put(_stackTrace_offset, st_element_array);
2116 }
2117 
2118 void java_lang_Throwable::clear_stacktrace(oop throwable) {
2119   set_stacktrace(throwable, nullptr);
2120 }
2121 
2122 oop java_lang_Throwable::create_exception_instance(Symbol* class_name, TRAPS) {
2123   Klass* k = SystemDictionary::resolve_or_fail(class_name, true, CHECK_NULL);
2124   return InstanceKlass::cast(k)->allocate_instance(CHECK_NULL);
2125 }
2126 
2127 void java_lang_Throwable::print(oop throwable, outputStream* st) {
2128   ResourceMark rm;
2129   Klass* k = throwable->klass();
2130   assert(k != nullptr, "just checking");
2131   st->print("%s", k->external_name());
2132   oop msg = message(throwable);
2133   if (msg != nullptr) {
2134     st->print(": %s", java_lang_String::as_utf8_string(msg));
2135   }
2136 }
2137 
2138 // After this many redefines, the stack trace is unreliable.
2139 const int MAX_VERSION = USHRT_MAX;
2140 
2141 static inline bool version_matches(Method* method, int version) {
2142   assert(version < MAX_VERSION, "version is too big");
2143   return method != nullptr && (method->constants()->version() == version);
2144 }
2145 
2146 // This class provides a simple wrapper over the internal structure of
2147 // exception backtrace to insulate users of the backtrace from needing
2148 // to know what it looks like.
2149 // The code of this class is not GC safe. Allocations can only happen
2150 // in expand().
2151 class BacktraceBuilder: public StackObj {
2152  friend class BacktraceIterator;
2153  private:
2154   Handle          _backtrace;
2155   objArrayOop     _head;
2156   typeArrayOop    _methods;
2157   typeArrayOop    _bcis;
2158   objArrayOop     _mirrors;
2159   typeArrayOop    _names; // Needed to insulate method name against redefinition.
2160   // True if the top frame of the backtrace is omitted because it shall be hidden.
2161   bool            _has_hidden_top_frame;
2162   int             _index;
2163   NoSafepointVerifier _nsv;
2164 
2165   enum {
2166     trace_methods_offset = java_lang_Throwable::trace_methods_offset,
2167     trace_bcis_offset    = java_lang_Throwable::trace_bcis_offset,
2168     trace_mirrors_offset = java_lang_Throwable::trace_mirrors_offset,
2169     trace_names_offset   = java_lang_Throwable::trace_names_offset,
2170     trace_conts_offset   = java_lang_Throwable::trace_conts_offset,
2171     trace_next_offset    = java_lang_Throwable::trace_next_offset,
2172     trace_hidden_offset  = java_lang_Throwable::trace_hidden_offset,
2173     trace_size           = java_lang_Throwable::trace_size,
2174     trace_chunk_size     = java_lang_Throwable::trace_chunk_size
2175   };
2176 
2177   // get info out of chunks
2178   static typeArrayOop get_methods(objArrayHandle chunk) {
2179     typeArrayOop methods = typeArrayOop(chunk->obj_at(trace_methods_offset));
2180     assert(methods != nullptr, "method array should be initialized in backtrace");
2181     return methods;
2182   }
2183   static typeArrayOop get_bcis(objArrayHandle chunk) {
2184     typeArrayOop bcis = typeArrayOop(chunk->obj_at(trace_bcis_offset));
2185     assert(bcis != nullptr, "bci array should be initialized in backtrace");
2186     return bcis;
2187   }
2188   static objArrayOop get_mirrors(objArrayHandle chunk) {
2189     objArrayOop mirrors = objArrayOop(chunk->obj_at(trace_mirrors_offset));
2190     assert(mirrors != nullptr, "mirror array should be initialized in backtrace");
2191     return mirrors;
2192   }
2193   static typeArrayOop get_names(objArrayHandle chunk) {
2194     typeArrayOop names = typeArrayOop(chunk->obj_at(trace_names_offset));
2195     assert(names != nullptr, "names array should be initialized in backtrace");
2196     return names;
2197   }
2198   static bool has_hidden_top_frame(objArrayHandle chunk) {
2199     oop hidden = chunk->obj_at(trace_hidden_offset);
2200     return hidden != nullptr;
2201   }
2202 
2203  public:
2204 
2205   // constructor for new backtrace
2206   BacktraceBuilder(TRAPS): _head(nullptr), _methods(nullptr), _bcis(nullptr), _mirrors(nullptr), _names(nullptr), _has_hidden_top_frame(false) {
2207     expand(CHECK);
2208     _backtrace = Handle(THREAD, _head);
2209     _index = 0;
2210   }
2211 
2212   BacktraceBuilder(Thread* thread, objArrayHandle backtrace) {
2213     _methods = get_methods(backtrace);
2214     _bcis = get_bcis(backtrace);
2215     _mirrors = get_mirrors(backtrace);
2216     _names = get_names(backtrace);
2217     _has_hidden_top_frame = has_hidden_top_frame(backtrace);
2218     assert(_methods->length() == _bcis->length() &&
2219            _methods->length() == _mirrors->length() &&
2220            _mirrors->length() == _names->length(),
2221            "method and source information arrays should match");
2222 
2223     // head is the preallocated backtrace
2224     _head = backtrace();
2225     _backtrace = Handle(thread, _head);
2226     _index = 0;
2227   }
2228 
2229   void expand(TRAPS) {
2230     objArrayHandle old_head(THREAD, _head);
2231     PauseNoSafepointVerifier pnsv(&_nsv);
2232 
2233     objArrayOop head = oopFactory::new_objectArray(trace_size, CHECK);
2234     objArrayHandle new_head(THREAD, head);
2235 
2236     typeArrayOop methods = oopFactory::new_shortArray(trace_chunk_size, CHECK);
2237     typeArrayHandle new_methods(THREAD, methods);
2238 
2239     typeArrayOop bcis = oopFactory::new_intArray(trace_chunk_size, CHECK);
2240     typeArrayHandle new_bcis(THREAD, bcis);
2241 
2242     objArrayOop mirrors = oopFactory::new_objectArray(trace_chunk_size, CHECK);
2243     objArrayHandle new_mirrors(THREAD, mirrors);
2244 
2245     typeArrayOop names = oopFactory::new_symbolArray(trace_chunk_size, CHECK);
2246     typeArrayHandle new_names(THREAD, names);
2247 
2248     if (!old_head.is_null()) {
2249       old_head->obj_at_put(trace_next_offset, new_head());
2250     }
2251     new_head->obj_at_put(trace_methods_offset, new_methods());
2252     new_head->obj_at_put(trace_bcis_offset, new_bcis());
2253     new_head->obj_at_put(trace_mirrors_offset, new_mirrors());
2254     new_head->obj_at_put(trace_names_offset, new_names());
2255     new_head->obj_at_put(trace_hidden_offset, nullptr);
2256 
2257     _head    = new_head();
2258     _methods = new_methods();
2259     _bcis = new_bcis();
2260     _mirrors = new_mirrors();
2261     _names  = new_names();
2262     _index = 0;
2263   }
2264 
2265   oop backtrace() {
2266     return _backtrace();
2267   }
2268 
2269   inline void push(Method* method, int bci, TRAPS) {
2270     // Smear the -1 bci to 0 since the array only holds unsigned
2271     // shorts.  The later line number lookup would just smear the -1
2272     // to a 0 even if it could be recorded.
2273     if (bci == SynchronizationEntryBCI) bci = 0;
2274 
2275     if (_index >= trace_chunk_size) {
2276       methodHandle mhandle(THREAD, method);
2277       expand(CHECK);
2278       method = mhandle();
2279     }
2280 
2281     _methods->ushort_at_put(_index, method->orig_method_idnum());
2282     _bcis->int_at_put(_index, Backtrace::merge_bci_and_version(bci, method->constants()->version()));
2283 
2284     // Note:this doesn't leak symbols because the mirror in the backtrace keeps the
2285     // klass owning the symbols alive so their refcounts aren't decremented.
2286     Symbol* name = method->name();
2287     _names->symbol_at_put(_index, name);
2288 
2289     // We need to save the mirrors in the backtrace to keep the class
2290     // from being unloaded while we still have this stack trace.
2291     assert(method->method_holder()->java_mirror() != nullptr, "never push null for mirror");
2292     _mirrors->obj_at_put(_index, method->method_holder()->java_mirror());
2293 
2294     _index++;
2295   }
2296 
2297   void set_has_hidden_top_frame() {
2298     if (!_has_hidden_top_frame) {
2299       // It would be nice to add java/lang/Boolean::TRUE here
2300       // to indicate that this backtrace has a hidden top frame.
2301       // But this code is used before TRUE is allocated.
2302       // Therefore let's just use an arbitrary legal oop
2303       // available right here. _methods is a short[].
2304       assert(_methods != nullptr, "we need a legal oop");
2305       _has_hidden_top_frame = true;
2306       _head->obj_at_put(trace_hidden_offset, _methods);
2307     }
2308   }
2309 };
2310 
2311 struct BacktraceElement : public StackObj {
2312   int _method_id;
2313   int _bci;
2314   int _version;
2315   Symbol* _name;
2316   Handle _mirror;
2317   BacktraceElement(Handle mirror, int mid, int version, int bci, Symbol* name) :
2318                    _method_id(mid), _bci(bci), _version(version), _name(name), _mirror(mirror) {}
2319 };
2320 
2321 class BacktraceIterator : public StackObj {
2322   int _index;
2323   objArrayHandle  _result;
2324   objArrayHandle  _mirrors;
2325   typeArrayHandle _methods;
2326   typeArrayHandle _bcis;
2327   typeArrayHandle _names;
2328 
2329   void init(objArrayHandle result, Thread* thread) {
2330     // Get method id, bci, version and mirror from chunk
2331     _result = result;
2332     if (_result.not_null()) {
2333       _methods = typeArrayHandle(thread, BacktraceBuilder::get_methods(_result));
2334       _bcis = typeArrayHandle(thread, BacktraceBuilder::get_bcis(_result));
2335       _mirrors = objArrayHandle(thread, BacktraceBuilder::get_mirrors(_result));
2336       _names = typeArrayHandle(thread, BacktraceBuilder::get_names(_result));
2337       _index = 0;
2338     }
2339   }
2340  public:
2341   BacktraceIterator(objArrayHandle result, Thread* thread) {
2342     init(result, thread);
2343     assert(_methods.is_null() || _methods->length() == java_lang_Throwable::trace_chunk_size, "lengths don't match");
2344   }
2345 
2346   BacktraceElement next(Thread* thread) {
2347     BacktraceElement e (Handle(thread, _mirrors->obj_at(_index)),
2348                         _methods->ushort_at(_index),
2349                         Backtrace::version_at(_bcis->int_at(_index)),
2350                         Backtrace::bci_at(_bcis->int_at(_index)),
2351                         _names->symbol_at(_index));
2352     _index++;
2353 
2354     if (_index >= java_lang_Throwable::trace_chunk_size) {
2355       int next_offset = java_lang_Throwable::trace_next_offset;
2356       // Get next chunk
2357       objArrayHandle result (thread, objArrayOop(_result->obj_at(next_offset)));
2358       init(result, thread);
2359     }
2360     return e;
2361   }
2362 
2363   bool repeat() {
2364     return _result.not_null() && _mirrors->obj_at(_index) != nullptr;
2365   }
2366 };
2367 
2368 
2369 // Print stack trace element to resource allocated buffer
2370 static void print_stack_element_to_stream(outputStream* st, Handle mirror, int method_id,
2371                                           int version, int bci, Symbol* name) {
2372   ResourceMark rm;
2373 
2374   // Get strings and string lengths
2375   InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(mirror()));
2376   const char* klass_name  = holder->external_name();
2377   int buf_len = (int)strlen(klass_name);
2378 
2379   char* method_name = name->as_C_string();
2380   buf_len += (int)strlen(method_name);
2381 
2382   char* source_file_name = nullptr;
2383   Symbol* source = Backtrace::get_source_file_name(holder, version);
2384   if (source != nullptr) {
2385     source_file_name = source->as_C_string();
2386     buf_len += (int)strlen(source_file_name);
2387   }
2388 
2389   char *module_name = nullptr, *module_version = nullptr;
2390   ModuleEntry* module = holder->module();
2391   if (module->is_named()) {
2392     module_name = module->name()->as_C_string();
2393     buf_len += (int)strlen(module_name);
2394     if (module->version() != nullptr) {
2395       module_version = module->version()->as_C_string();
2396       buf_len += (int)strlen(module_version);
2397     }
2398   }
2399 
2400   // Allocate temporary buffer with extra space for formatting and line number
2401   const size_t buf_size = buf_len + 64;
2402   char* buf = NEW_RESOURCE_ARRAY(char, buf_size);
2403 
2404   // Print stack trace line in buffer
2405   size_t buf_off = os::snprintf_checked(buf, buf_size, "\tat %s.%s(", klass_name, method_name);
2406 
2407   // Print module information
2408   if (module_name != nullptr) {
2409     if (module_version != nullptr) {
2410       buf_off += os::snprintf_checked(buf + buf_off, buf_size - buf_off, "%s@%s/", module_name, module_version);
2411     } else {
2412       buf_off += os::snprintf_checked(buf + buf_off, buf_size - buf_off, "%s/", module_name);
2413     }
2414   }
2415 
2416   // The method can be null if the requested class version is gone
2417   Method* method = holder->method_with_orig_idnum(method_id, version);
2418   if (!version_matches(method, version)) {
2419     strcat(buf, "Redefined)");
2420   } else {
2421     int line_number = Backtrace::get_line_number(method, bci);
2422     if (line_number == -2) {
2423       strcat(buf, "Native Method)");
2424     } else {
2425       if (source_file_name != nullptr && (line_number != -1)) {
2426         // Sourcename and linenumber
2427         buf_off += os::snprintf_checked(buf + buf_off, buf_size - buf_off, "%s:%d)", source_file_name, line_number);
2428       } else if (source_file_name != nullptr) {
2429         // Just sourcename
2430         buf_off += os::snprintf_checked(buf + buf_off, buf_size - buf_off, "%s)", source_file_name);
2431       } else {
2432         // Neither sourcename nor linenumber
2433         buf_off += os::snprintf_checked(buf + buf_off, buf_size - buf_off, "Unknown Source)");
2434       }
2435       CompiledMethod* nm = method->code();
2436       if (WizardMode && nm != nullptr) {
2437         os::snprintf_checked(buf + buf_off, buf_size - buf_off, "(nmethod " INTPTR_FORMAT ")", (intptr_t)nm);
2438       }
2439     }
2440   }
2441 
2442   st->print_cr("%s", buf);
2443 }
2444 
2445 void java_lang_Throwable::print_stack_element(outputStream *st, Method* method, int bci) {
2446   Handle mirror (Thread::current(),  method->method_holder()->java_mirror());
2447   int method_id = method->orig_method_idnum();
2448   int version = method->constants()->version();
2449   print_stack_element_to_stream(st, mirror, method_id, version, bci, method->name());
2450 }
2451 
2452 /**
2453  * Print the throwable message and its stack trace plus all causes by walking the
2454  * cause chain.  The output looks the same as of Throwable.printStackTrace().
2455  */
2456 void java_lang_Throwable::print_stack_trace(Handle throwable, outputStream* st) {
2457   // First, print the message.
2458   print(throwable(), st);
2459   st->cr();
2460 
2461   // Now print the stack trace.
2462   JavaThread* THREAD = JavaThread::current(); // For exception macros.
2463   while (throwable.not_null()) {
2464     objArrayHandle result (THREAD, objArrayOop(backtrace(throwable())));
2465     if (result.is_null()) {
2466       st->print_raw_cr("\t<<no stack trace available>>");
2467       return;
2468     }
2469     BacktraceIterator iter(result, THREAD);
2470 
2471     while (iter.repeat()) {
2472       BacktraceElement bte = iter.next(THREAD);
2473       print_stack_element_to_stream(st, bte._mirror, bte._method_id, bte._version, bte._bci, bte._name);
2474     }
2475     if (THREAD->can_call_java()) {
2476       // Call getCause() which doesn't necessarily return the _cause field.
2477       ExceptionMark em(THREAD);
2478       JavaValue cause(T_OBJECT);
2479       JavaCalls::call_virtual(&cause,
2480                               throwable,
2481                               throwable->klass(),
2482                               vmSymbols::getCause_name(),
2483                               vmSymbols::void_throwable_signature(),
2484                               THREAD);
2485       // Ignore any exceptions. we are in the middle of exception handling. Same as classic VM.
2486       if (HAS_PENDING_EXCEPTION) {
2487         CLEAR_PENDING_EXCEPTION;
2488         throwable = Handle();
2489       } else {
2490         throwable = Handle(THREAD, cause.get_oop());
2491         if (throwable.not_null()) {
2492           st->print("Caused by: ");
2493           print(throwable(), st);
2494           st->cr();
2495         }
2496       }
2497     } else {
2498       st->print_raw_cr("<<cannot call Java to get cause>>");
2499       return;
2500     }
2501   }
2502 }
2503 
2504 /**
2505  * Print the throwable stack trace by calling the Java method java.lang.Throwable.printStackTrace().
2506  */
2507 void java_lang_Throwable::java_printStackTrace(Handle throwable, TRAPS) {
2508   assert(throwable->is_a(vmClasses::Throwable_klass()), "Throwable instance expected");
2509   JavaValue result(T_VOID);
2510   JavaCalls::call_virtual(&result,
2511                           throwable,
2512                           vmClasses::Throwable_klass(),
2513                           vmSymbols::printStackTrace_name(),
2514                           vmSymbols::void_method_signature(),
2515                           THREAD);
2516 }
2517 
2518 void java_lang_Throwable::fill_in_stack_trace(Handle throwable, const methodHandle& method, TRAPS) {
2519   if (!StackTraceInThrowable) return;
2520   ResourceMark rm(THREAD);
2521 
2522   // Start out by clearing the backtrace for this object, in case the VM
2523   // runs out of memory while allocating the stack trace
2524   set_backtrace(throwable(), nullptr);
2525   // Clear lazily constructed Java level stacktrace if refilling occurs
2526   // This is unnecessary in 1.7+ but harmless
2527   clear_stacktrace(throwable());
2528 
2529   int max_depth = MaxJavaStackTraceDepth;
2530   JavaThread* thread = THREAD;
2531 
2532   BacktraceBuilder bt(CHECK);
2533 
2534   // If there is no Java frame just return the method that was being called
2535   // with bci 0
2536   if (!thread->has_last_Java_frame()) {
2537     if (max_depth >= 1 && method() != nullptr) {
2538       bt.push(method(), 0, CHECK);
2539       log_info(stacktrace)("%s, %d", throwable->klass()->external_name(), 1);
2540       set_depth(throwable(), 1);
2541       set_backtrace(throwable(), bt.backtrace());
2542     }
2543     return;
2544   }
2545 
2546   // Instead of using vframe directly, this version of fill_in_stack_trace
2547   // basically handles everything by hand. This significantly improved the
2548   // speed of this method call up to 28.5% on Solaris sparc. 27.1% on Windows.
2549   // See bug 6333838 for  more details.
2550   // The "ASSERT" here is to verify this method generates the exactly same stack
2551   // trace as utilizing vframe.
2552 #ifdef ASSERT
2553   vframeStream st(thread, false /* stop_at_java_call_stub */, false /* process_frames */);
2554 #endif
2555   int total_count = 0;
2556   RegisterMap map(thread,
2557                   RegisterMap::UpdateMap::skip,
2558                   RegisterMap::ProcessFrames::skip,
2559                   RegisterMap::WalkContinuation::include);
2560   int decode_offset = 0;
2561   CompiledMethod* nm = nullptr;
2562   bool skip_fillInStackTrace_check = false;
2563   bool skip_throwableInit_check = false;
2564   bool skip_hidden = !ShowHiddenFrames;
2565   bool show_carrier = ShowCarrierFrames;
2566   ContinuationEntry* cont_entry = thread->last_continuation();
2567   for (frame fr = thread->last_frame(); max_depth == 0 || max_depth != total_count;) {
2568     Method* method = nullptr;
2569     int bci = 0;
2570 
2571     // Compiled java method case.
2572     if (decode_offset != 0) {
2573       DebugInfoReadStream stream(nm, decode_offset);
2574       decode_offset = stream.read_int();
2575       method = (Method*)nm->metadata_at(stream.read_int());
2576       bci = stream.read_bci();
2577     } else {
2578       if (fr.is_first_frame()) break;
2579 
2580       if (Continuation::is_continuation_enterSpecial(fr)) {
2581         assert(cont_entry == Continuation::get_continuation_entry_for_entry_frame(thread, fr), "");
2582         if (!show_carrier && cont_entry->is_virtual_thread()) {
2583           break;
2584         }
2585         cont_entry = cont_entry->parent();
2586       }
2587 
2588       address pc = fr.pc();
2589       if (fr.is_interpreted_frame()) {
2590         address bcp;
2591         if (!map.in_cont()) {
2592           bcp = fr.interpreter_frame_bcp();
2593           method = fr.interpreter_frame_method();
2594         } else {
2595           bcp = map.stack_chunk()->interpreter_frame_bcp(fr);
2596           method = map.stack_chunk()->interpreter_frame_method(fr);
2597         }
2598         bci =  method->bci_from(bcp);
2599         fr = fr.sender(&map);
2600       } else {
2601         CodeBlob* cb = fr.cb();
2602         // HMMM QQQ might be nice to have frame return nm as null if cb is non-null
2603         // but non nmethod
2604         fr = fr.sender(&map);
2605         if (cb == nullptr || !cb->is_compiled()) {
2606           continue;
2607         }
2608         nm = cb->as_compiled_method();
2609         assert(nm->method() != nullptr, "must be");
2610         if (nm->method()->is_native()) {
2611           method = nm->method();
2612           bci = 0;
2613         } else {
2614           PcDesc* pd = nm->pc_desc_at(pc);
2615           decode_offset = pd->scope_decode_offset();
2616           // if decode_offset is not equal to 0, it will execute the
2617           // "compiled java method case" at the beginning of the loop.
2618           continue;
2619         }
2620       }
2621     }
2622 #ifdef ASSERT
2623     if (!st.at_end()) { // TODO LOOM remove once we show only vthread trace
2624       assert(st.method() == method && st.bci() == bci, "Wrong stack trace");
2625       st.next();
2626     }
2627 #endif
2628 
2629     // the format of the stacktrace will be:
2630     // - 1 or more fillInStackTrace frames for the exception class (skipped)
2631     // - 0 or more <init> methods for the exception class (skipped)
2632     // - rest of the stack
2633 
2634     if (!skip_fillInStackTrace_check) {
2635       if (method->name() == vmSymbols::fillInStackTrace_name() &&
2636           throwable->is_a(method->method_holder())) {
2637         continue;
2638       }
2639       else {
2640         skip_fillInStackTrace_check = true; // gone past them all
2641       }
2642     }
2643     if (!skip_throwableInit_check) {
2644       assert(skip_fillInStackTrace_check, "logic error in backtrace filtering");
2645 
2646       // skip <init> methods of the exception class and superclasses
2647       // This is similar to classic VM.
2648       if (method->name() == vmSymbols::object_initializer_name() &&
2649           throwable->is_a(method->method_holder())) {
2650         continue;
2651       } else {
2652         // there are none or we've seen them all - either way stop checking
2653         skip_throwableInit_check = true;
2654       }
2655     }
2656     if (method->is_hidden() || method->is_continuation_enter_intrinsic()) {
2657       if (skip_hidden) {
2658         if (total_count == 0) {
2659           // The top frame will be hidden from the stack trace.
2660           bt.set_has_hidden_top_frame();
2661         }
2662         continue;
2663       }
2664     }
2665 
2666     bt.push(method, bci, CHECK);
2667     total_count++;
2668   }
2669 
2670   log_info(stacktrace)("%s, %d", throwable->klass()->external_name(), total_count);
2671 
2672   // Put completed stack trace into throwable object
2673   set_backtrace(throwable(), bt.backtrace());
2674   set_depth(throwable(), total_count);
2675 }
2676 
2677 void java_lang_Throwable::fill_in_stack_trace(Handle throwable, const methodHandle& method) {
2678   // No-op if stack trace is disabled
2679   if (!StackTraceInThrowable) {
2680     return;
2681   }
2682 
2683   // Disable stack traces for some preallocated out of memory errors
2684   if (!Universe::should_fill_in_stack_trace(throwable)) {
2685     return;
2686   }
2687 
2688   JavaThread* THREAD = JavaThread::current(); // For exception macros.
2689   PreserveExceptionMark pm(THREAD);
2690 
2691   fill_in_stack_trace(throwable, method, THREAD);
2692   // Ignore exceptions thrown during stack trace filling (OOM) and reinstall the
2693   // original exception via the PreserveExceptionMark destructor.
2694   CLEAR_PENDING_EXCEPTION;
2695 }
2696 
2697 void java_lang_Throwable::allocate_backtrace(Handle throwable, TRAPS) {
2698   // Allocate stack trace - backtrace is created but not filled in
2699 
2700   // No-op if stack trace is disabled
2701   if (!StackTraceInThrowable) return;
2702   BacktraceBuilder bt(CHECK);   // creates a backtrace
2703   set_backtrace(throwable(), bt.backtrace());
2704 }
2705 
2706 
2707 void java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(Handle throwable) {
2708   // Fill in stack trace into preallocated backtrace (no GC)
2709 
2710   // No-op if stack trace is disabled
2711   if (!StackTraceInThrowable) return;
2712 
2713   assert(throwable->is_a(vmClasses::Throwable_klass()), "sanity check");
2714 
2715   JavaThread* THREAD = JavaThread::current(); // For exception macros.
2716 
2717   objArrayHandle backtrace (THREAD, (objArrayOop)java_lang_Throwable::backtrace(throwable()));
2718   assert(backtrace.not_null(), "backtrace should have been preallocated");
2719 
2720   ResourceMark rm(THREAD);
2721   vframeStream st(THREAD, false /* stop_at_java_call_stub */, false /* process_frames */);
2722 
2723   BacktraceBuilder bt(THREAD, backtrace);
2724 
2725   // Unlike fill_in_stack_trace we do not skip fillInStackTrace or throwable init
2726   // methods as preallocated errors aren't created by "java" code.
2727 
2728   // fill in as much stack trace as possible
2729   int chunk_count = 0;
2730   for (;!st.at_end(); st.next()) {
2731     bt.push(st.method(), st.bci(), CHECK);
2732     chunk_count++;
2733 
2734     // Bail-out for deep stacks
2735     if (chunk_count >= trace_chunk_size) break;
2736   }
2737   set_depth(throwable(), chunk_count);
2738   log_info(stacktrace)("%s, %d", throwable->klass()->external_name(), chunk_count);
2739 
2740   // We support the Throwable immutability protocol defined for Java 7.
2741   java_lang_Throwable::set_stacktrace(throwable(), java_lang_Throwable::unassigned_stacktrace());
2742   assert(java_lang_Throwable::unassigned_stacktrace() != nullptr, "not initialized");
2743 }
2744 
2745 void java_lang_Throwable::get_stack_trace_elements(int depth, Handle backtrace,
2746                                                    objArrayHandle stack_trace_array_h, TRAPS) {
2747 
2748   if (backtrace.is_null() || stack_trace_array_h.is_null()) {
2749     THROW(vmSymbols::java_lang_NullPointerException());
2750   }
2751 
2752   assert(stack_trace_array_h->is_objArray(), "Stack trace array should be an array of StackTraceElenent");
2753 
2754   if (stack_trace_array_h->length() != depth) {
2755     THROW(vmSymbols::java_lang_IndexOutOfBoundsException());
2756   }
2757 
2758   objArrayHandle result(THREAD, objArrayOop(backtrace()));
2759   BacktraceIterator iter(result, THREAD);
2760 
2761   int index = 0;
2762   while (iter.repeat()) {
2763     BacktraceElement bte = iter.next(THREAD);
2764 
2765     Handle stack_trace_element(THREAD, stack_trace_array_h->obj_at(index++));
2766 
2767     if (stack_trace_element.is_null()) {
2768       THROW(vmSymbols::java_lang_NullPointerException());
2769     }
2770 
2771     InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(bte._mirror()));
2772     methodHandle method (THREAD, holder->method_with_orig_idnum(bte._method_id, bte._version));
2773 
2774     java_lang_StackTraceElement::fill_in(stack_trace_element, holder,
2775                                          method,
2776                                          bte._version,
2777                                          bte._bci,
2778                                          bte._name,
2779                                          CHECK);
2780   }
2781 }
2782 
2783 Handle java_lang_Throwable::create_initialization_error(JavaThread* current, Handle throwable) {
2784   // Creates an ExceptionInInitializerError to be recorded as the initialization error when class initialization
2785   // failed due to the passed in 'throwable'. We cannot save 'throwable' directly due to issues with keeping alive
2786   // all objects referenced via its stacktrace. So instead we save a new EIIE instance, with the same message and
2787   // symbolic stacktrace of 'throwable'.
2788   assert(throwable.not_null(), "shouldn't be");
2789 
2790   // Now create the message from the original exception and thread name.
2791   ResourceMark rm(current);
2792   const char *message = nullptr;
2793   oop detailed_message = java_lang_Throwable::message(throwable());
2794   if (detailed_message != nullptr) {
2795     message = java_lang_String::as_utf8_string(detailed_message);
2796   }
2797   stringStream st;
2798   st.print("Exception %s%s ", throwable()->klass()->name()->as_klass_external_name(),
2799              message == nullptr ? "" : ":");
2800   if (message == nullptr) {
2801     st.print("[in thread \"%s\"]", current->name());
2802   } else {
2803     st.print("%s [in thread \"%s\"]", message, current->name());
2804   }
2805 
2806   Symbol* exception_name = vmSymbols::java_lang_ExceptionInInitializerError();
2807   Handle init_error = Exceptions::new_exception(current, exception_name, st.as_string());
2808   // If new_exception returns a different exception while creating the exception,
2809   // abandon the attempt to save the initialization error and return null.
2810   if (init_error->klass()->name() != exception_name) {
2811     log_info(class, init)("Exception %s thrown while saving initialization exception",
2812                         init_error->klass()->external_name());
2813     return Handle();
2814   }
2815 
2816   // Call to java to fill in the stack trace and clear declaringClassObject to
2817   // not keep classes alive in the stack trace.
2818   // call this:  public StackTraceElement[] getStackTrace()
2819   JavaValue result(T_ARRAY);
2820   JavaCalls::call_virtual(&result, throwable,
2821                           vmClasses::Throwable_klass(),
2822                           vmSymbols::getStackTrace_name(),
2823                           vmSymbols::getStackTrace_signature(),
2824                           current);
2825   if (!current->has_pending_exception()){
2826     Handle stack_trace(current, result.get_oop());
2827     assert(stack_trace->is_objArray(), "Should be an array");
2828     java_lang_Throwable::set_stacktrace(init_error(), stack_trace());
2829     // Clear backtrace because the stacktrace should be used instead.
2830     set_backtrace(init_error(), nullptr);
2831   } else {
2832     log_info(class, init)("Exception thrown while getting stack trace for initialization exception %s",
2833                         init_error->klass()->external_name());
2834     current->clear_pending_exception();
2835   }
2836 
2837   return init_error;
2838 }
2839 
2840 bool java_lang_Throwable::get_top_method_and_bci(oop throwable, Method** method, int* bci) {
2841   JavaThread* current = JavaThread::current();
2842   objArrayHandle result(current, objArrayOop(backtrace(throwable)));
2843   BacktraceIterator iter(result, current);
2844   // No backtrace available.
2845   if (!iter.repeat()) return false;
2846 
2847   // If the exception happened in a frame that has been hidden, i.e.,
2848   // omitted from the back trace, we can not compute the message.
2849   oop hidden = ((objArrayOop)backtrace(throwable))->obj_at(trace_hidden_offset);
2850   if (hidden != nullptr) {
2851     return false;
2852   }
2853 
2854   // Get first backtrace element.
2855   BacktraceElement bte = iter.next(current);
2856 
2857   InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(bte._mirror()));
2858   assert(holder != nullptr, "first element should be non-null");
2859   Method* m = holder->method_with_orig_idnum(bte._method_id, bte._version);
2860 
2861   // Original version is no longer available.
2862   if (m == nullptr || !version_matches(m, bte._version)) {
2863     return false;
2864   }
2865 
2866   *method = m;
2867   *bci = bte._bci;
2868   return true;
2869 }
2870 
2871 oop java_lang_StackTraceElement::create(const methodHandle& method, int bci, TRAPS) {
2872   // Allocate java.lang.StackTraceElement instance
2873   InstanceKlass* k = vmClasses::StackTraceElement_klass();
2874   assert(k != nullptr, "must be loaded in 1.4+");
2875   if (k->should_be_initialized()) {
2876     k->initialize(CHECK_NULL);
2877   }
2878 
2879   Handle element = k->allocate_instance_handle(CHECK_NULL);
2880 
2881   int version = method->constants()->version();
2882   fill_in(element, method->method_holder(), method, version, bci, method->name(), CHECK_NULL);
2883   return element();
2884 }
2885 
2886 void java_lang_StackTraceElement::fill_in(Handle element,
2887                                           InstanceKlass* holder, const methodHandle& method,
2888                                           int version, int bci, Symbol* name, TRAPS) {
2889   assert(element->is_a(vmClasses::StackTraceElement_klass()), "sanity check");
2890 
2891   ResourceMark rm(THREAD);
2892   HandleMark hm(THREAD);
2893 
2894   // Fill in class name
2895   Handle java_class(THREAD, holder->java_mirror());
2896   oop classname = java_lang_Class::name(java_class, CHECK);
2897   java_lang_StackTraceElement::set_declaringClass(element(), classname);
2898   java_lang_StackTraceElement::set_declaringClassObject(element(), java_class());
2899 
2900   oop loader = holder->class_loader();
2901   if (loader != nullptr) {
2902     oop loader_name = java_lang_ClassLoader::name(loader);
2903     if (loader_name != nullptr)
2904       java_lang_StackTraceElement::set_classLoaderName(element(), loader_name);
2905   }
2906 
2907   // Fill in method name
2908   oop methodname = StringTable::intern(name, CHECK);
2909   java_lang_StackTraceElement::set_methodName(element(), methodname);
2910 
2911   // Fill in module name and version
2912   ModuleEntry* module = holder->module();
2913   if (module->is_named()) {
2914     oop module_name = StringTable::intern(module->name(), CHECK);
2915     java_lang_StackTraceElement::set_moduleName(element(), module_name);
2916     oop module_version;
2917     if (module->version() != nullptr) {
2918       module_version = StringTable::intern(module->version(), CHECK);
2919     } else {
2920       module_version = nullptr;
2921     }
2922     java_lang_StackTraceElement::set_moduleVersion(element(), module_version);
2923   }
2924 
2925   if (method() == nullptr || !version_matches(method(), version)) {
2926     // The method was redefined, accurate line number information isn't available
2927     java_lang_StackTraceElement::set_fileName(element(), nullptr);
2928     java_lang_StackTraceElement::set_lineNumber(element(), -1);
2929   } else {
2930     Symbol* source;
2931     oop source_file;
2932     int line_number;
2933     decode_file_and_line(java_class, holder, version, method, bci, source, source_file, line_number, CHECK);
2934 
2935     java_lang_StackTraceElement::set_fileName(element(), source_file);
2936     java_lang_StackTraceElement::set_lineNumber(element(), line_number);
2937   }
2938 }
2939 
2940 void java_lang_StackTraceElement::decode_file_and_line(Handle java_class,
2941                                                        InstanceKlass* holder,
2942                                                        int version,
2943                                                        const methodHandle& method,
2944                                                        int bci,
2945                                                        Symbol*& source,
2946                                                        oop& source_file,
2947                                                        int& line_number, TRAPS) {
2948   // Fill in source file name and line number.
2949   source = Backtrace::get_source_file_name(holder, version);
2950   source_file = java_lang_Class::source_file(java_class());
2951   if (source != nullptr) {
2952     // Class was not redefined. We can trust its cache if set,
2953     // else we have to initialize it.
2954     if (source_file == nullptr) {
2955       source_file = StringTable::intern(source, CHECK);
2956       java_lang_Class::set_source_file(java_class(), source_file);
2957     }
2958   } else {
2959     // Class was redefined. Dump the cache if it was set.
2960     if (source_file != nullptr) {
2961       source_file = nullptr;
2962       java_lang_Class::set_source_file(java_class(), source_file);
2963     }
2964   }
2965   line_number = Backtrace::get_line_number(method(), bci);
2966 }
2967 
2968 #if INCLUDE_JVMCI
2969 void java_lang_StackTraceElement::decode(const methodHandle& method, int bci,
2970                                          Symbol*& filename, int& line_number, TRAPS) {
2971   ResourceMark rm(THREAD);
2972   HandleMark hm(THREAD);
2973 
2974   filename = nullptr;
2975   line_number = -1;
2976 
2977   oop source_file;
2978   int version = method->constants()->version();
2979   InstanceKlass* holder = method->method_holder();
2980   Handle java_class(THREAD, holder->java_mirror());
2981   decode_file_and_line(java_class, holder, version, method, bci, filename, source_file, line_number, CHECK);
2982 }
2983 #endif // INCLUDE_JVMCI
2984 
2985 // java_lang_ClassFrameInfo
2986 
2987 int java_lang_ClassFrameInfo::_classOrMemberName_offset;
2988 int java_lang_ClassFrameInfo::_flags_offset;
2989 
2990 #define CLASSFRAMEINFO_FIELDS_DO(macro) \
2991   macro(_classOrMemberName_offset, k, "classOrMemberName", object_signature,  false); \
2992   macro(_flags_offset,             k, vmSymbols::flags_name(), int_signature, false)
2993 
2994 void java_lang_ClassFrameInfo::compute_offsets() {
2995   InstanceKlass* k = vmClasses::ClassFrameInfo_klass();
2996   CLASSFRAMEINFO_FIELDS_DO(FIELD_COMPUTE_OFFSET);
2997 }
2998 
2999 #if INCLUDE_CDS
3000 void java_lang_ClassFrameInfo::serialize_offsets(SerializeClosure* f) {
3001   CLASSFRAMEINFO_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3002 }
3003 #endif
3004 
3005 static int get_flags(const methodHandle& m) {
3006   int flags = (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS );
3007   if (m->is_initializer()) {
3008     flags |= java_lang_invoke_MemberName::MN_IS_CONSTRUCTOR;
3009   } else {
3010     flags |= java_lang_invoke_MemberName::MN_IS_METHOD;
3011   }
3012   if (m->caller_sensitive()) {
3013     flags |= java_lang_invoke_MemberName::MN_CALLER_SENSITIVE;
3014   }
3015   if (m->is_hidden()) {
3016     flags |= java_lang_invoke_MemberName::MN_HIDDEN_MEMBER;
3017   }
3018   assert((flags & 0xFF000000) == 0, "unexpected flags");
3019   return flags;
3020 }
3021 
3022 oop java_lang_ClassFrameInfo::classOrMemberName(oop obj) {
3023   return obj->obj_field(_classOrMemberName_offset);
3024 }
3025 
3026 int java_lang_ClassFrameInfo::flags(oop obj) {
3027   return obj->int_field(_flags_offset);
3028 }
3029 
3030 void java_lang_ClassFrameInfo::init_class(Handle stackFrame, const methodHandle& m) {
3031   stackFrame->obj_field_put(_classOrMemberName_offset, m->method_holder()->java_mirror());
3032   // flags is initialized when ClassFrameInfo object is constructed and retain the value
3033   int flags = java_lang_ClassFrameInfo::flags(stackFrame()) | get_flags(m);
3034   stackFrame->int_field_put(_flags_offset, flags);
3035 }
3036 
3037 void java_lang_ClassFrameInfo::init_method(Handle stackFrame, const methodHandle& m, TRAPS) {
3038   oop rmethod_name = java_lang_invoke_ResolvedMethodName::find_resolved_method(m, CHECK);
3039   stackFrame->obj_field_put(_classOrMemberName_offset, rmethod_name);
3040   // flags is initialized when ClassFrameInfo object is constructed and retain the value
3041   int flags = java_lang_ClassFrameInfo::flags(stackFrame()) | get_flags(m);
3042   stackFrame->int_field_put(_flags_offset, flags);
3043 }
3044 
3045 
3046 // java_lang_StackFrameInfo
3047 
3048 int java_lang_StackFrameInfo::_type_offset;
3049 int java_lang_StackFrameInfo::_name_offset;
3050 int java_lang_StackFrameInfo::_bci_offset;
3051 int java_lang_StackFrameInfo::_version_offset;
3052 int java_lang_StackFrameInfo::_contScope_offset;
3053 
3054 #define STACKFRAMEINFO_FIELDS_DO(macro) \
3055   macro(_type_offset,       k, "type",       object_signature,            false); \
3056   macro(_name_offset,       k, "name",       string_signature,            false); \
3057   macro(_bci_offset,        k, "bci",        int_signature,               false); \
3058   macro(_contScope_offset,  k, "contScope",  continuationscope_signature, false)
3059 
3060 void java_lang_StackFrameInfo::compute_offsets() {
3061   InstanceKlass* k = vmClasses::StackFrameInfo_klass();
3062   STACKFRAMEINFO_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3063   STACKFRAMEINFO_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
3064 }
3065 
3066 #if INCLUDE_CDS
3067 void java_lang_StackFrameInfo::serialize_offsets(SerializeClosure* f) {
3068   STACKFRAMEINFO_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3069   STACKFRAMEINFO_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
3070 }
3071 #endif
3072 
3073 Method* java_lang_StackFrameInfo::get_method(oop obj) {
3074   oop m = java_lang_ClassFrameInfo::classOrMemberName(obj);
3075   Method* method = java_lang_invoke_ResolvedMethodName::vmtarget(m);
3076   return method;
3077 }
3078 
3079 void java_lang_StackFrameInfo::set_method_and_bci(Handle stackFrame, const methodHandle& method, int bci, oop cont, TRAPS) {
3080   // set Method* or mid/cpref
3081   HandleMark hm(THREAD);
3082   Handle cont_h(THREAD, cont);
3083   java_lang_ClassFrameInfo::init_method(stackFrame, method, CHECK);
3084 
3085   // set bci
3086   java_lang_StackFrameInfo::set_bci(stackFrame(), bci);
3087   // method may be redefined; store the version
3088   int version = method->constants()->version();
3089   assert((jushort)version == version, "version should be short");
3090   java_lang_StackFrameInfo::set_version(stackFrame(), (short)version);
3091 
3092   oop contScope = cont_h() != nullptr ? jdk_internal_vm_Continuation::scope(cont_h()) : (oop)nullptr;
3093   java_lang_StackFrameInfo::set_contScope(stackFrame(), contScope);
3094 }
3095 
3096 void java_lang_StackFrameInfo::to_stack_trace_element(Handle stackFrame, Handle stack_trace_element, TRAPS) {
3097   ResourceMark rm(THREAD);
3098   HandleMark hm(THREAD);
3099 
3100   Method* method = java_lang_StackFrameInfo::get_method(stackFrame());
3101   InstanceKlass* holder = method->method_holder();
3102   short version = stackFrame->short_field(_version_offset);
3103   int bci = stackFrame->int_field(_bci_offset);
3104   Symbol* name = method->name();
3105   java_lang_StackTraceElement::fill_in(stack_trace_element, holder, methodHandle(THREAD, method), version, bci, name, CHECK);
3106 }
3107 
3108 oop java_lang_StackFrameInfo::type(oop obj) {
3109   return obj->obj_field(_type_offset);
3110 }
3111 
3112 void java_lang_StackFrameInfo::set_type(oop obj, oop value) {
3113   obj->obj_field_put(_type_offset, value);
3114 }
3115 
3116 oop java_lang_StackFrameInfo::name(oop obj) {
3117   return obj->obj_field(_name_offset);
3118 }
3119 
3120 void java_lang_StackFrameInfo::set_name(oop obj, oop value) {
3121   obj->obj_field_put(_name_offset, value);
3122 }
3123 
3124 void java_lang_StackFrameInfo::set_version(oop obj, short value) {
3125   obj->short_field_put(_version_offset, value);
3126 }
3127 
3128 void java_lang_StackFrameInfo::set_bci(oop obj, int value) {
3129   assert(value >= 0 && value < max_jushort, "must be a valid bci value");
3130   obj->int_field_put(_bci_offset, value);
3131 }
3132 
3133 void java_lang_StackFrameInfo::set_contScope(oop obj, oop value) {
3134   obj->obj_field_put(_contScope_offset, value);
3135 }
3136 
3137 int java_lang_LiveStackFrameInfo::_monitors_offset;
3138 int java_lang_LiveStackFrameInfo::_locals_offset;
3139 int java_lang_LiveStackFrameInfo::_operands_offset;
3140 int java_lang_LiveStackFrameInfo::_mode_offset;
3141 
3142 #define LIVESTACKFRAMEINFO_FIELDS_DO(macro) \
3143   macro(_monitors_offset,   k, "monitors",    object_array_signature, false); \
3144   macro(_locals_offset,     k, "locals",      object_array_signature, false); \
3145   macro(_operands_offset,   k, "operands",    object_array_signature, false); \
3146   macro(_mode_offset,       k, "mode",        int_signature,          false)
3147 
3148 void java_lang_LiveStackFrameInfo::compute_offsets() {
3149   InstanceKlass* k = vmClasses::LiveStackFrameInfo_klass();
3150   LIVESTACKFRAMEINFO_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3151 }
3152 
3153 #if INCLUDE_CDS
3154 void java_lang_LiveStackFrameInfo::serialize_offsets(SerializeClosure* f) {
3155   LIVESTACKFRAMEINFO_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3156 }
3157 #endif
3158 
3159 void java_lang_LiveStackFrameInfo::set_monitors(oop obj, oop value) {
3160   obj->obj_field_put(_monitors_offset, value);
3161 }
3162 
3163 void java_lang_LiveStackFrameInfo::set_locals(oop obj, oop value) {
3164   obj->obj_field_put(_locals_offset, value);
3165 }
3166 
3167 void java_lang_LiveStackFrameInfo::set_operands(oop obj, oop value) {
3168   obj->obj_field_put(_operands_offset, value);
3169 }
3170 
3171 void java_lang_LiveStackFrameInfo::set_mode(oop obj, int value) {
3172   obj->int_field_put(_mode_offset, value);
3173 }
3174 
3175 
3176 // java_lang_AccessibleObject
3177 
3178 int java_lang_reflect_AccessibleObject::_override_offset;
3179 
3180 #define ACCESSIBLEOBJECT_FIELDS_DO(macro) \
3181   macro(_override_offset, k, "override", bool_signature, false)
3182 
3183 void java_lang_reflect_AccessibleObject::compute_offsets() {
3184   InstanceKlass* k = vmClasses::reflect_AccessibleObject_klass();
3185   ACCESSIBLEOBJECT_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3186 }
3187 
3188 #if INCLUDE_CDS
3189 void java_lang_reflect_AccessibleObject::serialize_offsets(SerializeClosure* f) {
3190   ACCESSIBLEOBJECT_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3191 }
3192 #endif
3193 
3194 jboolean java_lang_reflect_AccessibleObject::override(oop reflect) {
3195   return (jboolean) reflect->bool_field(_override_offset);
3196 }
3197 
3198 void java_lang_reflect_AccessibleObject::set_override(oop reflect, jboolean value) {
3199   reflect->bool_field_put(_override_offset, (int) value);
3200 }
3201 
3202 // java_lang_reflect_Method
3203 
3204 int java_lang_reflect_Method::_clazz_offset;
3205 int java_lang_reflect_Method::_name_offset;
3206 int java_lang_reflect_Method::_returnType_offset;
3207 int java_lang_reflect_Method::_parameterTypes_offset;
3208 int java_lang_reflect_Method::_exceptionTypes_offset;
3209 int java_lang_reflect_Method::_slot_offset;
3210 int java_lang_reflect_Method::_modifiers_offset;
3211 int java_lang_reflect_Method::_signature_offset;
3212 int java_lang_reflect_Method::_annotations_offset;
3213 int java_lang_reflect_Method::_parameter_annotations_offset;
3214 int java_lang_reflect_Method::_annotation_default_offset;
3215 
3216 #define METHOD_FIELDS_DO(macro) \
3217   macro(_clazz_offset,          k, vmSymbols::clazz_name(),          class_signature,       false); \
3218   macro(_name_offset,           k, vmSymbols::name_name(),           string_signature,      false); \
3219   macro(_returnType_offset,     k, vmSymbols::returnType_name(),     class_signature,       false); \
3220   macro(_parameterTypes_offset, k, vmSymbols::parameterTypes_name(), class_array_signature, false); \
3221   macro(_exceptionTypes_offset, k, vmSymbols::exceptionTypes_name(), class_array_signature, false); \
3222   macro(_slot_offset,           k, vmSymbols::slot_name(),           int_signature,         false); \
3223   macro(_modifiers_offset,      k, vmSymbols::modifiers_name(),      int_signature,         false); \
3224   macro(_signature_offset,             k, vmSymbols::signature_name(),             string_signature,     false); \
3225   macro(_annotations_offset,           k, vmSymbols::annotations_name(),           byte_array_signature, false); \
3226   macro(_parameter_annotations_offset, k, vmSymbols::parameter_annotations_name(), byte_array_signature, false); \
3227   macro(_annotation_default_offset,    k, vmSymbols::annotation_default_name(),    byte_array_signature, false);
3228 
3229 void java_lang_reflect_Method::compute_offsets() {
3230   InstanceKlass* k = vmClasses::reflect_Method_klass();
3231   METHOD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3232 }
3233 
3234 #if INCLUDE_CDS
3235 void java_lang_reflect_Method::serialize_offsets(SerializeClosure* f) {
3236   METHOD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3237 }
3238 #endif
3239 
3240 Handle java_lang_reflect_Method::create(TRAPS) {
3241   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3242   Klass* klass = vmClasses::reflect_Method_klass();
3243   // This class is eagerly initialized during VM initialization, since we keep a reference
3244   // to one of the methods
3245   assert(InstanceKlass::cast(klass)->is_initialized(), "must be initialized");
3246   return InstanceKlass::cast(klass)->allocate_instance_handle(THREAD);
3247 }
3248 
3249 oop java_lang_reflect_Method::clazz(oop reflect) {
3250   return reflect->obj_field(_clazz_offset);
3251 }
3252 
3253 void java_lang_reflect_Method::set_clazz(oop reflect, oop value) {
3254    reflect->obj_field_put(_clazz_offset, value);
3255 }
3256 
3257 int java_lang_reflect_Method::slot(oop reflect) {
3258   return reflect->int_field(_slot_offset);
3259 }
3260 
3261 void java_lang_reflect_Method::set_slot(oop reflect, int value) {
3262   reflect->int_field_put(_slot_offset, value);
3263 }
3264 
3265 void java_lang_reflect_Method::set_name(oop method, oop value) {
3266   method->obj_field_put(_name_offset, value);
3267 }
3268 
3269 oop java_lang_reflect_Method::return_type(oop method) {
3270   return method->obj_field(_returnType_offset);
3271 }
3272 
3273 void java_lang_reflect_Method::set_return_type(oop method, oop value) {
3274   method->obj_field_put(_returnType_offset, value);
3275 }
3276 
3277 oop java_lang_reflect_Method::parameter_types(oop method) {
3278   return method->obj_field(_parameterTypes_offset);
3279 }
3280 
3281 void java_lang_reflect_Method::set_parameter_types(oop method, oop value) {
3282   method->obj_field_put(_parameterTypes_offset, value);
3283 }
3284 
3285 void java_lang_reflect_Method::set_exception_types(oop method, oop value) {
3286   method->obj_field_put(_exceptionTypes_offset, value);
3287 }
3288 
3289 void java_lang_reflect_Method::set_modifiers(oop method, int value) {
3290   method->int_field_put(_modifiers_offset, value);
3291 }
3292 
3293 void java_lang_reflect_Method::set_signature(oop method, oop value) {
3294   method->obj_field_put(_signature_offset, value);
3295 }
3296 
3297 void java_lang_reflect_Method::set_annotations(oop method, oop value) {
3298   method->obj_field_put(_annotations_offset, value);
3299 }
3300 
3301 void java_lang_reflect_Method::set_parameter_annotations(oop method, oop value) {
3302   method->obj_field_put(_parameter_annotations_offset, value);
3303 }
3304 
3305 void java_lang_reflect_Method::set_annotation_default(oop method, oop value) {
3306   method->obj_field_put(_annotation_default_offset, value);
3307 }
3308 
3309 int java_lang_reflect_Constructor::_clazz_offset;
3310 int java_lang_reflect_Constructor::_parameterTypes_offset;
3311 int java_lang_reflect_Constructor::_exceptionTypes_offset;
3312 int java_lang_reflect_Constructor::_slot_offset;
3313 int java_lang_reflect_Constructor::_modifiers_offset;
3314 int java_lang_reflect_Constructor::_signature_offset;
3315 int java_lang_reflect_Constructor::_annotations_offset;
3316 int java_lang_reflect_Constructor::_parameter_annotations_offset;
3317 
3318 #define CONSTRUCTOR_FIELDS_DO(macro) \
3319   macro(_clazz_offset,          k, vmSymbols::clazz_name(),          class_signature,       false); \
3320   macro(_parameterTypes_offset, k, vmSymbols::parameterTypes_name(), class_array_signature, false); \
3321   macro(_exceptionTypes_offset, k, vmSymbols::exceptionTypes_name(), class_array_signature, false); \
3322   macro(_slot_offset,           k, vmSymbols::slot_name(),           int_signature,         false); \
3323   macro(_modifiers_offset,      k, vmSymbols::modifiers_name(),      int_signature,         false); \
3324   macro(_signature_offset,             k, vmSymbols::signature_name(),             string_signature,     false); \
3325   macro(_annotations_offset,           k, vmSymbols::annotations_name(),           byte_array_signature, false); \
3326   macro(_parameter_annotations_offset, k, vmSymbols::parameter_annotations_name(), byte_array_signature, false);
3327 
3328 void java_lang_reflect_Constructor::compute_offsets() {
3329   InstanceKlass* k = vmClasses::reflect_Constructor_klass();
3330   CONSTRUCTOR_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3331 }
3332 
3333 #if INCLUDE_CDS
3334 void java_lang_reflect_Constructor::serialize_offsets(SerializeClosure* f) {
3335   CONSTRUCTOR_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3336 }
3337 #endif
3338 
3339 Handle java_lang_reflect_Constructor::create(TRAPS) {
3340   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3341   Symbol* name = vmSymbols::java_lang_reflect_Constructor();
3342   Klass* k = SystemDictionary::resolve_or_fail(name, true, CHECK_NH);
3343   InstanceKlass* ik = InstanceKlass::cast(k);
3344   // Ensure it is initialized
3345   ik->initialize(CHECK_NH);
3346   return ik->allocate_instance_handle(THREAD);
3347 }
3348 
3349 oop java_lang_reflect_Constructor::clazz(oop reflect) {
3350   return reflect->obj_field(_clazz_offset);
3351 }
3352 
3353 void java_lang_reflect_Constructor::set_clazz(oop reflect, oop value) {
3354    reflect->obj_field_put(_clazz_offset, value);
3355 }
3356 
3357 oop java_lang_reflect_Constructor::parameter_types(oop constructor) {
3358   return constructor->obj_field(_parameterTypes_offset);
3359 }
3360 
3361 void java_lang_reflect_Constructor::set_parameter_types(oop constructor, oop value) {
3362   constructor->obj_field_put(_parameterTypes_offset, value);
3363 }
3364 
3365 void java_lang_reflect_Constructor::set_exception_types(oop constructor, oop value) {
3366   constructor->obj_field_put(_exceptionTypes_offset, value);
3367 }
3368 
3369 int java_lang_reflect_Constructor::slot(oop reflect) {
3370   return reflect->int_field(_slot_offset);
3371 }
3372 
3373 void java_lang_reflect_Constructor::set_slot(oop reflect, int value) {
3374   reflect->int_field_put(_slot_offset, value);
3375 }
3376 
3377 void java_lang_reflect_Constructor::set_modifiers(oop constructor, int value) {
3378   constructor->int_field_put(_modifiers_offset, value);
3379 }
3380 
3381 void java_lang_reflect_Constructor::set_signature(oop constructor, oop value) {
3382   constructor->obj_field_put(_signature_offset, value);
3383 }
3384 
3385 void java_lang_reflect_Constructor::set_annotations(oop constructor, oop value) {
3386   constructor->obj_field_put(_annotations_offset, value);
3387 }
3388 
3389 void java_lang_reflect_Constructor::set_parameter_annotations(oop method, oop value) {
3390   method->obj_field_put(_parameter_annotations_offset, value);
3391 }
3392 
3393 int java_lang_reflect_Field::_clazz_offset;
3394 int java_lang_reflect_Field::_name_offset;
3395 int java_lang_reflect_Field::_type_offset;
3396 int java_lang_reflect_Field::_slot_offset;
3397 int java_lang_reflect_Field::_modifiers_offset;
3398 int java_lang_reflect_Field::_trusted_final_offset;
3399 int java_lang_reflect_Field::_signature_offset;
3400 int java_lang_reflect_Field::_annotations_offset;
3401 
3402 #define FIELD_FIELDS_DO(macro) \
3403   macro(_clazz_offset,     k, vmSymbols::clazz_name(),     class_signature,  false); \
3404   macro(_name_offset,      k, vmSymbols::name_name(),      string_signature, false); \
3405   macro(_type_offset,      k, vmSymbols::type_name(),      class_signature,  false); \
3406   macro(_slot_offset,      k, vmSymbols::slot_name(),      int_signature,    false); \
3407   macro(_modifiers_offset, k, vmSymbols::modifiers_name(), int_signature,    false); \
3408   macro(_trusted_final_offset,    k, vmSymbols::trusted_final_name(),    bool_signature,       false); \
3409   macro(_signature_offset,        k, vmSymbols::signature_name(),        string_signature,     false); \
3410   macro(_annotations_offset,      k, vmSymbols::annotations_name(),      byte_array_signature, false);
3411 
3412 void java_lang_reflect_Field::compute_offsets() {
3413   InstanceKlass* k = vmClasses::reflect_Field_klass();
3414   FIELD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3415 }
3416 
3417 #if INCLUDE_CDS
3418 void java_lang_reflect_Field::serialize_offsets(SerializeClosure* f) {
3419   FIELD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3420 }
3421 #endif
3422 
3423 Handle java_lang_reflect_Field::create(TRAPS) {
3424   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3425   Symbol* name = vmSymbols::java_lang_reflect_Field();
3426   Klass* k = SystemDictionary::resolve_or_fail(name, true, CHECK_NH);
3427   InstanceKlass* ik = InstanceKlass::cast(k);
3428   // Ensure it is initialized
3429   ik->initialize(CHECK_NH);
3430   return ik->allocate_instance_handle(THREAD);
3431 }
3432 
3433 oop java_lang_reflect_Field::clazz(oop reflect) {
3434   return reflect->obj_field(_clazz_offset);
3435 }
3436 
3437 void java_lang_reflect_Field::set_clazz(oop reflect, oop value) {
3438   reflect->obj_field_put(_clazz_offset, value);
3439 }
3440 
3441 oop java_lang_reflect_Field::name(oop field) {
3442   return field->obj_field(_name_offset);
3443 }
3444 
3445 void java_lang_reflect_Field::set_name(oop field, oop value) {
3446   field->obj_field_put(_name_offset, value);
3447 }
3448 
3449 oop java_lang_reflect_Field::type(oop field) {
3450   return field->obj_field(_type_offset);
3451 }
3452 
3453 void java_lang_reflect_Field::set_type(oop field, oop value) {
3454   field->obj_field_put(_type_offset, value);
3455 }
3456 
3457 int java_lang_reflect_Field::slot(oop reflect) {
3458   return reflect->int_field(_slot_offset);
3459 }
3460 
3461 void java_lang_reflect_Field::set_slot(oop reflect, int value) {
3462   reflect->int_field_put(_slot_offset, value);
3463 }
3464 
3465 int java_lang_reflect_Field::modifiers(oop field) {
3466   return field->int_field(_modifiers_offset);
3467 }
3468 
3469 void java_lang_reflect_Field::set_modifiers(oop field, int value) {
3470   field->int_field_put(_modifiers_offset, value);
3471 }
3472 
3473 void java_lang_reflect_Field::set_trusted_final(oop field) {
3474   field->bool_field_put(_trusted_final_offset, true);
3475 }
3476 
3477 void java_lang_reflect_Field::set_signature(oop field, oop value) {
3478   field->obj_field_put(_signature_offset, value);
3479 }
3480 
3481 void java_lang_reflect_Field::set_annotations(oop field, oop value) {
3482   field->obj_field_put(_annotations_offset, value);
3483 }
3484 
3485 oop java_lang_reflect_RecordComponent::create(InstanceKlass* holder, RecordComponent* component, TRAPS) {
3486   // Allocate java.lang.reflect.RecordComponent instance
3487   HandleMark hm(THREAD);
3488   InstanceKlass* ik = vmClasses::RecordComponent_klass();
3489   assert(ik != nullptr, "must be loaded");
3490   ik->initialize(CHECK_NULL);
3491 
3492   Handle element = ik->allocate_instance_handle(CHECK_NULL);
3493 
3494   Handle decl_class(THREAD, holder->java_mirror());
3495   java_lang_reflect_RecordComponent::set_clazz(element(), decl_class());
3496 
3497   Symbol* name = holder->constants()->symbol_at(component->name_index()); // name_index is a utf8
3498   oop component_name = StringTable::intern(name, CHECK_NULL);
3499   java_lang_reflect_RecordComponent::set_name(element(), component_name);
3500 
3501   Symbol* type = holder->constants()->symbol_at(component->descriptor_index());
3502   Handle component_type_h =
3503     SystemDictionary::find_java_mirror_for_type(type, holder, SignatureStream::NCDFError, CHECK_NULL);
3504   java_lang_reflect_RecordComponent::set_type(element(), component_type_h());
3505 
3506   Method* accessor_method = nullptr;
3507   {
3508     // Prepend "()" to type to create the full method signature.
3509     ResourceMark rm(THREAD);
3510     int sig_len = type->utf8_length() + 3; // "()" and null char
3511     char* sig = NEW_RESOURCE_ARRAY(char, sig_len);
3512     jio_snprintf(sig, sig_len, "%c%c%s", JVM_SIGNATURE_FUNC, JVM_SIGNATURE_ENDFUNC, type->as_C_string());
3513     TempNewSymbol full_sig = SymbolTable::new_symbol(sig);
3514     accessor_method = holder->find_instance_method(name, full_sig, Klass::PrivateLookupMode::find);
3515   }
3516 
3517   if (accessor_method != nullptr) {
3518     methodHandle method(THREAD, accessor_method);
3519     oop m = Reflection::new_method(method, false, CHECK_NULL);
3520     java_lang_reflect_RecordComponent::set_accessor(element(), m);
3521   } else {
3522     java_lang_reflect_RecordComponent::set_accessor(element(), nullptr);
3523   }
3524 
3525   int sig_index = component->generic_signature_index();
3526   if (sig_index > 0) {
3527     Symbol* sig = holder->constants()->symbol_at(sig_index); // sig_index is a utf8
3528     oop component_sig = StringTable::intern(sig, CHECK_NULL);
3529     java_lang_reflect_RecordComponent::set_signature(element(), component_sig);
3530   } else {
3531     java_lang_reflect_RecordComponent::set_signature(element(), nullptr);
3532   }
3533 
3534   typeArrayOop annotation_oop = Annotations::make_java_array(component->annotations(), CHECK_NULL);
3535   java_lang_reflect_RecordComponent::set_annotations(element(), annotation_oop);
3536 
3537   typeArrayOop type_annotation_oop = Annotations::make_java_array(component->type_annotations(), CHECK_NULL);
3538   java_lang_reflect_RecordComponent::set_typeAnnotations(element(), type_annotation_oop);
3539 
3540   return element();
3541 }
3542 
3543 int reflect_ConstantPool::_oop_offset;
3544 
3545 #define CONSTANTPOOL_FIELDS_DO(macro) \
3546   macro(_oop_offset, k, "constantPoolOop", object_signature, false)
3547 
3548 void reflect_ConstantPool::compute_offsets() {
3549   InstanceKlass* k = vmClasses::reflect_ConstantPool_klass();
3550   // The field is called ConstantPool* in the sun.reflect.ConstantPool class.
3551   CONSTANTPOOL_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3552 }
3553 
3554 #if INCLUDE_CDS
3555 void reflect_ConstantPool::serialize_offsets(SerializeClosure* f) {
3556   CONSTANTPOOL_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3557 }
3558 #endif
3559 
3560 int java_lang_reflect_Parameter::_name_offset;
3561 int java_lang_reflect_Parameter::_modifiers_offset;
3562 int java_lang_reflect_Parameter::_index_offset;
3563 int java_lang_reflect_Parameter::_executable_offset;
3564 
3565 #define PARAMETER_FIELDS_DO(macro) \
3566   macro(_name_offset,        k, vmSymbols::name_name(),        string_signature, false); \
3567   macro(_modifiers_offset,   k, vmSymbols::modifiers_name(),   int_signature,    false); \
3568   macro(_index_offset,       k, vmSymbols::index_name(),       int_signature,    false); \
3569   macro(_executable_offset,  k, vmSymbols::executable_name(),  executable_signature, false)
3570 
3571 void java_lang_reflect_Parameter::compute_offsets() {
3572   InstanceKlass* k = vmClasses::reflect_Parameter_klass();
3573   PARAMETER_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3574 }
3575 
3576 #if INCLUDE_CDS
3577 void java_lang_reflect_Parameter::serialize_offsets(SerializeClosure* f) {
3578   PARAMETER_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3579 }
3580 #endif
3581 
3582 Handle java_lang_reflect_Parameter::create(TRAPS) {
3583   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3584   Symbol* name = vmSymbols::java_lang_reflect_Parameter();
3585   Klass* k = SystemDictionary::resolve_or_fail(name, true, CHECK_NH);
3586   InstanceKlass* ik = InstanceKlass::cast(k);
3587   // Ensure it is initialized
3588   ik->initialize(CHECK_NH);
3589   return ik->allocate_instance_handle(THREAD);
3590 }
3591 
3592 oop java_lang_reflect_Parameter::name(oop param) {
3593   return param->obj_field(_name_offset);
3594 }
3595 
3596 void java_lang_reflect_Parameter::set_name(oop param, oop value) {
3597   param->obj_field_put(_name_offset, value);
3598 }
3599 
3600 int java_lang_reflect_Parameter::modifiers(oop param) {
3601   return param->int_field(_modifiers_offset);
3602 }
3603 
3604 void java_lang_reflect_Parameter::set_modifiers(oop param, int value) {
3605   param->int_field_put(_modifiers_offset, value);
3606 }
3607 
3608 int java_lang_reflect_Parameter::index(oop param) {
3609   return param->int_field(_index_offset);
3610 }
3611 
3612 void java_lang_reflect_Parameter::set_index(oop param, int value) {
3613   param->int_field_put(_index_offset, value);
3614 }
3615 
3616 oop java_lang_reflect_Parameter::executable(oop param) {
3617   return param->obj_field(_executable_offset);
3618 }
3619 
3620 void java_lang_reflect_Parameter::set_executable(oop param, oop value) {
3621   param->obj_field_put(_executable_offset, value);
3622 }
3623 
3624 // java_lang_Module
3625 
3626 int java_lang_Module::_loader_offset;
3627 int java_lang_Module::_name_offset;
3628 int java_lang_Module::_module_entry_offset;
3629 
3630 Handle java_lang_Module::create(Handle loader, Handle module_name, TRAPS) {
3631   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3632   return JavaCalls::construct_new_instance(vmClasses::Module_klass(),
3633                           vmSymbols::java_lang_module_init_signature(),
3634                           loader, module_name, CHECK_NH);
3635 }
3636 
3637 #define MODULE_FIELDS_DO(macro) \
3638   macro(_loader_offset,  k, vmSymbols::loader_name(),  classloader_signature, false); \
3639   macro(_name_offset,    k, vmSymbols::name_name(),    string_signature,      false)
3640 
3641 void java_lang_Module::compute_offsets() {
3642   InstanceKlass* k = vmClasses::Module_klass();
3643   MODULE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3644   MODULE_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
3645 }
3646 
3647 #if INCLUDE_CDS
3648 void java_lang_Module::serialize_offsets(SerializeClosure* f) {
3649   MODULE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3650   MODULE_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
3651 }
3652 #endif
3653 
3654 oop java_lang_Module::loader(oop module) {
3655   return module->obj_field(_loader_offset);
3656 }
3657 
3658 void java_lang_Module::set_loader(oop module, oop value) {
3659   module->obj_field_put(_loader_offset, value);
3660 }
3661 
3662 oop java_lang_Module::name(oop module) {
3663   return module->obj_field(_name_offset);
3664 }
3665 
3666 void java_lang_Module::set_name(oop module, oop value) {
3667   module->obj_field_put(_name_offset, value);
3668 }
3669 
3670 ModuleEntry* java_lang_Module::module_entry_raw(oop module) {
3671   assert(_module_entry_offset != 0, "Uninitialized module_entry_offset");
3672   assert(module != nullptr, "module can't be null");
3673   assert(oopDesc::is_oop(module), "module must be oop");
3674 
3675   ModuleEntry* module_entry = (ModuleEntry*)module->address_field(_module_entry_offset);
3676   return module_entry;
3677 }
3678 
3679 ModuleEntry* java_lang_Module::module_entry(oop module) {
3680   ModuleEntry* module_entry = module_entry_raw(module);
3681   if (module_entry == nullptr) {
3682     // If the inject field containing the ModuleEntry* is null then return the
3683     // class loader's unnamed module.
3684     oop loader = java_lang_Module::loader(module);
3685     Handle h_loader = Handle(Thread::current(), loader);
3686     ClassLoaderData* loader_cld = SystemDictionary::register_loader(h_loader);
3687     return loader_cld->unnamed_module();
3688   }
3689   return module_entry;
3690 }
3691 
3692 void java_lang_Module::set_module_entry(oop module, ModuleEntry* module_entry) {
3693   assert(_module_entry_offset != 0, "Uninitialized module_entry_offset");
3694   assert(module != nullptr, "module can't be null");
3695   assert(oopDesc::is_oop(module), "module must be oop");
3696   module->address_field_put(_module_entry_offset, (address)module_entry);
3697 }
3698 
3699 Handle reflect_ConstantPool::create(TRAPS) {
3700   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3701   InstanceKlass* k = vmClasses::reflect_ConstantPool_klass();
3702   // Ensure it is initialized
3703   k->initialize(CHECK_NH);
3704   return k->allocate_instance_handle(THREAD);
3705 }
3706 
3707 
3708 void reflect_ConstantPool::set_cp(oop reflect, ConstantPool* value) {
3709   oop mirror = value->pool_holder()->java_mirror();
3710   // Save the mirror to get back the constant pool.
3711   reflect->obj_field_put(_oop_offset, mirror);
3712 }
3713 
3714 ConstantPool* reflect_ConstantPool::get_cp(oop reflect) {
3715 
3716   oop mirror = reflect->obj_field(_oop_offset);
3717   Klass* k = java_lang_Class::as_Klass(mirror);
3718   assert(k->is_instance_klass(), "Must be");
3719 
3720   // Get the constant pool back from the klass.  Since class redefinition
3721   // merges the new constant pool into the old, this is essentially the
3722   // same constant pool as the original.  If constant pool merging is
3723   // no longer done in the future, this will have to change to save
3724   // the original.
3725   return InstanceKlass::cast(k)->constants();
3726 }
3727 
3728 
3729 // Support for java_lang_ref_Reference
3730 
3731 bool java_lang_ref_Reference::_offsets_initialized;
3732 
3733 int java_lang_ref_Reference::_referent_offset;
3734 int java_lang_ref_Reference::_queue_offset;
3735 int java_lang_ref_Reference::_next_offset;
3736 int java_lang_ref_Reference::_discovered_offset;
3737 
3738 #define REFERENCE_FIELDS_DO(macro) \
3739   macro(_referent_offset,   k, "referent", object_signature, false); \
3740   macro(_queue_offset,      k, "queue", referencequeue_signature, false); \
3741   macro(_next_offset,       k, "next", reference_signature, false); \
3742   macro(_discovered_offset, k, "discovered", reference_signature, false);
3743 
3744 void java_lang_ref_Reference::compute_offsets() {
3745   if (_offsets_initialized) {
3746     return;
3747   }
3748   _offsets_initialized = true;
3749   InstanceKlass* k = vmClasses::Reference_klass();
3750   REFERENCE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3751 }
3752 
3753 #if INCLUDE_CDS
3754 void java_lang_ref_Reference::serialize_offsets(SerializeClosure* f) {
3755   f->do_bool(&_offsets_initialized);
3756   REFERENCE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3757 }
3758 #endif
3759 
3760 bool java_lang_ref_Reference::is_referent_field(oop obj, ptrdiff_t offset) {
3761   assert(obj != nullptr, "sanity");
3762   if (offset != _referent_offset) {
3763     return false;
3764   }
3765 
3766   Klass* k = obj->klass();
3767   if (!k->is_instance_klass()) {
3768     return false;
3769   }
3770 
3771   InstanceKlass* ik = InstanceKlass::cast(obj->klass());
3772   bool is_reference = ik->reference_type() != REF_NONE;
3773   assert(!is_reference || ik->is_subclass_of(vmClasses::Reference_klass()), "sanity");
3774   return is_reference;
3775 }
3776 
3777 int java_lang_boxing_object::_value_offset;
3778 int java_lang_boxing_object::_long_value_offset;
3779 
3780 #define BOXING_FIELDS_DO(macro) \
3781   macro(_value_offset,      integerKlass, "value", int_signature, false); \
3782   macro(_long_value_offset, longKlass, "value", long_signature, false);
3783 
3784 void java_lang_boxing_object::compute_offsets() {
3785   InstanceKlass* integerKlass = vmClasses::Integer_klass();
3786   InstanceKlass* longKlass = vmClasses::Long_klass();
3787   BOXING_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3788 }
3789 
3790 #if INCLUDE_CDS
3791 void java_lang_boxing_object::serialize_offsets(SerializeClosure* f) {
3792   BOXING_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3793 }
3794 #endif
3795 
3796 oop java_lang_boxing_object::initialize_and_allocate(BasicType type, TRAPS) {
3797   Klass* k = vmClasses::box_klass(type);
3798   if (k == nullptr)  return nullptr;
3799   InstanceKlass* ik = InstanceKlass::cast(k);
3800   if (!ik->is_initialized()) {
3801     ik->initialize(CHECK_NULL);
3802   }
3803   return ik->allocate_instance(THREAD);
3804 }
3805 
3806 
3807 oop java_lang_boxing_object::create(BasicType type, jvalue* value, TRAPS) {
3808   oop box = initialize_and_allocate(type, CHECK_NULL);
3809   if (box == nullptr)  return nullptr;
3810   switch (type) {
3811     case T_BOOLEAN:
3812       box->bool_field_put(_value_offset, value->z);
3813       break;
3814     case T_CHAR:
3815       box->char_field_put(_value_offset, value->c);
3816       break;
3817     case T_FLOAT:
3818       box->float_field_put(_value_offset, value->f);
3819       break;
3820     case T_DOUBLE:
3821       box->double_field_put(_long_value_offset, value->d);
3822       break;
3823     case T_BYTE:
3824       box->byte_field_put(_value_offset, value->b);
3825       break;
3826     case T_SHORT:
3827       box->short_field_put(_value_offset, value->s);
3828       break;
3829     case T_INT:
3830       box->int_field_put(_value_offset, value->i);
3831       break;
3832     case T_LONG:
3833       box->long_field_put(_long_value_offset, value->j);
3834       break;
3835     default:
3836       return nullptr;
3837   }
3838   return box;
3839 }
3840 
3841 
3842 BasicType java_lang_boxing_object::basic_type(oop box) {
3843   if (box == nullptr)  return T_ILLEGAL;
3844   BasicType type = vmClasses::box_klass_type(box->klass());
3845   if (type == T_OBJECT)         // 'unknown' value returned by SD::bkt
3846     return T_ILLEGAL;
3847   return type;
3848 }
3849 
3850 
3851 BasicType java_lang_boxing_object::get_value(oop box, jvalue* value) {
3852   BasicType type = vmClasses::box_klass_type(box->klass());
3853   switch (type) {
3854   case T_BOOLEAN:
3855     value->z = box->bool_field(_value_offset);
3856     break;
3857   case T_CHAR:
3858     value->c = box->char_field(_value_offset);
3859     break;
3860   case T_FLOAT:
3861     value->f = box->float_field(_value_offset);
3862     break;
3863   case T_DOUBLE:
3864     value->d = box->double_field(_long_value_offset);
3865     break;
3866   case T_BYTE:
3867     value->b = box->byte_field(_value_offset);
3868     break;
3869   case T_SHORT:
3870     value->s = box->short_field(_value_offset);
3871     break;
3872   case T_INT:
3873     value->i = box->int_field(_value_offset);
3874     break;
3875   case T_LONG:
3876     value->j = box->long_field(_long_value_offset);
3877     break;
3878   default:
3879     return T_ILLEGAL;
3880   } // end switch
3881   return type;
3882 }
3883 
3884 
3885 BasicType java_lang_boxing_object::set_value(oop box, jvalue* value) {
3886   BasicType type = vmClasses::box_klass_type(box->klass());
3887   switch (type) {
3888   case T_BOOLEAN:
3889     box->bool_field_put(_value_offset, value->z);
3890     break;
3891   case T_CHAR:
3892     box->char_field_put(_value_offset, value->c);
3893     break;
3894   case T_FLOAT:
3895     box->float_field_put(_value_offset, value->f);
3896     break;
3897   case T_DOUBLE:
3898     box->double_field_put(_long_value_offset, value->d);
3899     break;
3900   case T_BYTE:
3901     box->byte_field_put(_value_offset, value->b);
3902     break;
3903   case T_SHORT:
3904     box->short_field_put(_value_offset, value->s);
3905     break;
3906   case T_INT:
3907     box->int_field_put(_value_offset, value->i);
3908     break;
3909   case T_LONG:
3910     box->long_field_put(_long_value_offset, value->j);
3911     break;
3912   default:
3913     return T_ILLEGAL;
3914   } // end switch
3915   return type;
3916 }
3917 
3918 
3919 void java_lang_boxing_object::print(BasicType type, jvalue* value, outputStream* st) {
3920   switch (type) {
3921   case T_BOOLEAN:   st->print("%s", value->z ? "true" : "false");   break;
3922   case T_CHAR:      st->print("%d", value->c);                      break;
3923   case T_BYTE:      st->print("%d", value->b);                      break;
3924   case T_SHORT:     st->print("%d", value->s);                      break;
3925   case T_INT:       st->print("%d", value->i);                      break;
3926   case T_LONG:      st->print(JLONG_FORMAT, value->j);              break;
3927   case T_FLOAT:     st->print("%f", value->f);                      break;
3928   case T_DOUBLE:    st->print("%lf", value->d);                     break;
3929   default:          st->print("type %d?", type);                    break;
3930   }
3931 }
3932 
3933 
3934 // Support for java_lang_ref_SoftReference
3935 //
3936 
3937 int java_lang_ref_SoftReference::_timestamp_offset;
3938 int java_lang_ref_SoftReference::_static_clock_offset;
3939 
3940 #define SOFTREFERENCE_FIELDS_DO(macro) \
3941   macro(_timestamp_offset,    k, "timestamp", long_signature, false); \
3942   macro(_static_clock_offset, k, "clock",     long_signature, true)
3943 
3944 void java_lang_ref_SoftReference::compute_offsets() {
3945   InstanceKlass* k = vmClasses::SoftReference_klass();
3946   SOFTREFERENCE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3947 }
3948 
3949 #if INCLUDE_CDS
3950 void java_lang_ref_SoftReference::serialize_offsets(SerializeClosure* f) {
3951   SOFTREFERENCE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3952 }
3953 #endif
3954 
3955 jlong java_lang_ref_SoftReference::timestamp(oop ref) {
3956   return ref->long_field(_timestamp_offset);
3957 }
3958 
3959 jlong java_lang_ref_SoftReference::clock() {
3960   InstanceKlass* ik = vmClasses::SoftReference_klass();
3961   oop base = ik->static_field_base_raw();
3962   return base->long_field(_static_clock_offset);
3963 }
3964 
3965 void java_lang_ref_SoftReference::set_clock(jlong value) {
3966   InstanceKlass* ik = vmClasses::SoftReference_klass();
3967   oop base = ik->static_field_base_raw();
3968   base->long_field_put(_static_clock_offset, value);
3969 }
3970 
3971 // Support for java_lang_invoke_DirectMethodHandle
3972 
3973 int java_lang_invoke_DirectMethodHandle::_member_offset;
3974 
3975 oop java_lang_invoke_DirectMethodHandle::member(oop dmh) {
3976   oop member_name = nullptr;
3977   assert(oopDesc::is_oop(dmh) && java_lang_invoke_DirectMethodHandle::is_instance(dmh),
3978          "a DirectMethodHandle oop is expected");
3979   return dmh->obj_field(_member_offset);
3980 }
3981 
3982 #define DIRECTMETHODHANDLE_FIELDS_DO(macro) \
3983   macro(_member_offset, k, "member", java_lang_invoke_MemberName_signature, false)
3984 
3985 void java_lang_invoke_DirectMethodHandle::compute_offsets() {
3986   InstanceKlass* k = vmClasses::DirectMethodHandle_klass();
3987   DIRECTMETHODHANDLE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3988 }
3989 
3990 #if INCLUDE_CDS
3991 void java_lang_invoke_DirectMethodHandle::serialize_offsets(SerializeClosure* f) {
3992   DIRECTMETHODHANDLE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3993 }
3994 #endif
3995 
3996 // Support for java_lang_invoke_MethodHandle
3997 
3998 int java_lang_invoke_MethodHandle::_type_offset;
3999 int java_lang_invoke_MethodHandle::_form_offset;
4000 
4001 int java_lang_invoke_MemberName::_clazz_offset;
4002 int java_lang_invoke_MemberName::_name_offset;
4003 int java_lang_invoke_MemberName::_type_offset;
4004 int java_lang_invoke_MemberName::_flags_offset;
4005 int java_lang_invoke_MemberName::_method_offset;
4006 int java_lang_invoke_MemberName::_vmindex_offset;
4007 
4008 int java_lang_invoke_ResolvedMethodName::_vmtarget_offset;
4009 int java_lang_invoke_ResolvedMethodName::_vmholder_offset;
4010 
4011 int java_lang_invoke_LambdaForm::_vmentry_offset;
4012 
4013 #define METHODHANDLE_FIELDS_DO(macro) \
4014   macro(_type_offset, k, vmSymbols::type_name(), java_lang_invoke_MethodType_signature, false); \
4015   macro(_form_offset, k, "form",                 java_lang_invoke_LambdaForm_signature, false)
4016 
4017 void java_lang_invoke_MethodHandle::compute_offsets() {
4018   InstanceKlass* k = vmClasses::MethodHandle_klass();
4019   METHODHANDLE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4020 }
4021 
4022 #if INCLUDE_CDS
4023 void java_lang_invoke_MethodHandle::serialize_offsets(SerializeClosure* f) {
4024   METHODHANDLE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4025 }
4026 #endif
4027 
4028 #define MEMBERNAME_FIELDS_DO(macro) \
4029   macro(_clazz_offset,   k, vmSymbols::clazz_name(),   class_signature,  false); \
4030   macro(_name_offset,    k, vmSymbols::name_name(),    string_signature, false); \
4031   macro(_type_offset,    k, vmSymbols::type_name(),    object_signature, false); \
4032   macro(_flags_offset,   k, vmSymbols::flags_name(),   int_signature,    false); \
4033   macro(_method_offset,  k, vmSymbols::method_name(),  java_lang_invoke_ResolvedMethodName_signature, false)
4034 
4035 void java_lang_invoke_MemberName::compute_offsets() {
4036   InstanceKlass* k = vmClasses::MemberName_klass();
4037   MEMBERNAME_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4038   MEMBERNAME_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
4039 }
4040 
4041 #if INCLUDE_CDS
4042 void java_lang_invoke_MemberName::serialize_offsets(SerializeClosure* f) {
4043   MEMBERNAME_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4044   MEMBERNAME_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
4045 }
4046 #endif
4047 
4048 #define RESOLVEDMETHOD_FIELDS_DO(macro) \
4049   macro(_vmholder_offset, k, "vmholder", class_signature, false)
4050 
4051 void java_lang_invoke_ResolvedMethodName::compute_offsets() {
4052   InstanceKlass* k = vmClasses::ResolvedMethodName_klass();
4053   assert(k != nullptr, "jdk mismatch");
4054   RESOLVEDMETHOD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4055   RESOLVEDMETHOD_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
4056 }
4057 
4058 #if INCLUDE_CDS
4059 void java_lang_invoke_ResolvedMethodName::serialize_offsets(SerializeClosure* f) {
4060   RESOLVEDMETHOD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4061   RESOLVEDMETHOD_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
4062 }
4063 #endif
4064 
4065 #define LAMBDAFORM_FIELDS_DO(macro) \
4066   macro(_vmentry_offset, k, "vmentry", java_lang_invoke_MemberName_signature, false)
4067 
4068 void java_lang_invoke_LambdaForm::compute_offsets() {
4069   InstanceKlass* k = vmClasses::LambdaForm_klass();
4070   assert (k != nullptr, "jdk mismatch");
4071   LAMBDAFORM_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4072 }
4073 
4074 #if INCLUDE_CDS
4075 void java_lang_invoke_LambdaForm::serialize_offsets(SerializeClosure* f) {
4076   LAMBDAFORM_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4077 }
4078 #endif
4079 
4080 bool java_lang_invoke_LambdaForm::is_instance(oop obj) {
4081   return obj != nullptr && is_subclass(obj->klass());
4082 }
4083 
4084 int jdk_internal_foreign_abi_NativeEntryPoint::_method_type_offset;
4085 int jdk_internal_foreign_abi_NativeEntryPoint::_downcall_stub_address_offset;
4086 
4087 #define NEP_FIELDS_DO(macro) \
4088   macro(_method_type_offset,           k, "methodType",          java_lang_invoke_MethodType_signature, false); \
4089   macro(_downcall_stub_address_offset, k, "downcallStubAddress", long_signature, false);
4090 
4091 bool jdk_internal_foreign_abi_NativeEntryPoint::is_instance(oop obj) {
4092   return obj != nullptr && is_subclass(obj->klass());
4093 }
4094 
4095 void jdk_internal_foreign_abi_NativeEntryPoint::compute_offsets() {
4096   InstanceKlass* k = vmClasses::NativeEntryPoint_klass();
4097   NEP_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4098 }
4099 
4100 #if INCLUDE_CDS
4101 void jdk_internal_foreign_abi_NativeEntryPoint::serialize_offsets(SerializeClosure* f) {
4102   NEP_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4103 }
4104 #endif
4105 
4106 oop jdk_internal_foreign_abi_NativeEntryPoint::method_type(oop entry) {
4107   return entry->obj_field(_method_type_offset);
4108 }
4109 
4110 jlong jdk_internal_foreign_abi_NativeEntryPoint::downcall_stub_address(oop entry) {
4111   return entry->long_field(_downcall_stub_address_offset);
4112 }
4113 
4114 int jdk_internal_foreign_abi_ABIDescriptor::_inputStorage_offset;
4115 int jdk_internal_foreign_abi_ABIDescriptor::_outputStorage_offset;
4116 int jdk_internal_foreign_abi_ABIDescriptor::_volatileStorage_offset;
4117 int jdk_internal_foreign_abi_ABIDescriptor::_stackAlignment_offset;
4118 int jdk_internal_foreign_abi_ABIDescriptor::_shadowSpace_offset;
4119 int jdk_internal_foreign_abi_ABIDescriptor::_scratch1_offset;
4120 int jdk_internal_foreign_abi_ABIDescriptor::_scratch2_offset;
4121 
4122 #define ABIDescriptor_FIELDS_DO(macro) \
4123   macro(_inputStorage_offset,    k, "inputStorage",    jdk_internal_foreign_abi_VMStorage_array_array_signature, false); \
4124   macro(_outputStorage_offset,   k, "outputStorage",   jdk_internal_foreign_abi_VMStorage_array_array_signature, false); \
4125   macro(_volatileStorage_offset, k, "volatileStorage", jdk_internal_foreign_abi_VMStorage_array_array_signature, false); \
4126   macro(_stackAlignment_offset,  k, "stackAlignment",  int_signature, false); \
4127   macro(_shadowSpace_offset,     k, "shadowSpace",     int_signature, false); \
4128   macro(_scratch1_offset,        k, "scratch1",        jdk_internal_foreign_abi_VMStorage_signature, false); \
4129   macro(_scratch2_offset,        k, "scratch2",        jdk_internal_foreign_abi_VMStorage_signature, false);
4130 
4131 bool jdk_internal_foreign_abi_ABIDescriptor::is_instance(oop obj) {
4132   return obj != nullptr && is_subclass(obj->klass());
4133 }
4134 
4135 void jdk_internal_foreign_abi_ABIDescriptor::compute_offsets() {
4136   InstanceKlass* k = vmClasses::ABIDescriptor_klass();
4137   ABIDescriptor_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4138 }
4139 
4140 #if INCLUDE_CDS
4141 void jdk_internal_foreign_abi_ABIDescriptor::serialize_offsets(SerializeClosure* f) {
4142   ABIDescriptor_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4143 }
4144 #endif
4145 
4146 objArrayOop jdk_internal_foreign_abi_ABIDescriptor::inputStorage(oop entry) {
4147   return oop_cast<objArrayOop>(entry->obj_field(_inputStorage_offset));
4148 }
4149 
4150 objArrayOop jdk_internal_foreign_abi_ABIDescriptor::outputStorage(oop entry) {
4151   return oop_cast<objArrayOop>(entry->obj_field(_outputStorage_offset));
4152 }
4153 
4154 objArrayOop jdk_internal_foreign_abi_ABIDescriptor::volatileStorage(oop entry) {
4155   return oop_cast<objArrayOop>(entry->obj_field(_volatileStorage_offset));
4156 }
4157 
4158 jint jdk_internal_foreign_abi_ABIDescriptor::stackAlignment(oop entry) {
4159   return entry->int_field(_stackAlignment_offset);
4160 }
4161 
4162 jint jdk_internal_foreign_abi_ABIDescriptor::shadowSpace(oop entry) {
4163   return entry->int_field(_shadowSpace_offset);
4164 }
4165 
4166 oop jdk_internal_foreign_abi_ABIDescriptor::scratch1(oop entry) {
4167   return entry->obj_field(_scratch1_offset);
4168 }
4169 
4170 oop jdk_internal_foreign_abi_ABIDescriptor::scratch2(oop entry) {
4171   return entry->obj_field(_scratch2_offset);
4172 }
4173 
4174 int jdk_internal_foreign_abi_VMStorage::_type_offset;
4175 int jdk_internal_foreign_abi_VMStorage::_indexOrOffset_offset;
4176 int jdk_internal_foreign_abi_VMStorage::_segmentMaskOrSize_offset;
4177 int jdk_internal_foreign_abi_VMStorage::_debugName_offset;
4178 
4179 #define VMStorage_FIELDS_DO(macro) \
4180   macro(_type_offset,              k, "type",              byte_signature, false); \
4181   macro(_indexOrOffset_offset,     k, "indexOrOffset",     int_signature, false); \
4182   macro(_segmentMaskOrSize_offset, k, "segmentMaskOrSize", short_signature, false); \
4183   macro(_debugName_offset,         k, "debugName",         string_signature, false); \
4184 
4185 bool jdk_internal_foreign_abi_VMStorage::is_instance(oop obj) {
4186   return obj != nullptr && is_subclass(obj->klass());
4187 }
4188 
4189 void jdk_internal_foreign_abi_VMStorage::compute_offsets() {
4190   InstanceKlass* k = vmClasses::VMStorage_klass();
4191   VMStorage_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4192 }
4193 
4194 #if INCLUDE_CDS
4195 void jdk_internal_foreign_abi_VMStorage::serialize_offsets(SerializeClosure* f) {
4196   VMStorage_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4197 }
4198 #endif
4199 
4200 jbyte jdk_internal_foreign_abi_VMStorage::type(oop entry) {
4201   return entry->byte_field(_type_offset);
4202 }
4203 
4204 jint jdk_internal_foreign_abi_VMStorage::index_or_offset(oop entry) {
4205   return entry->int_field(_indexOrOffset_offset);
4206 }
4207 
4208 jshort jdk_internal_foreign_abi_VMStorage::segment_mask_or_size(oop entry) {
4209   return entry->short_field(_segmentMaskOrSize_offset);
4210 }
4211 
4212 oop jdk_internal_foreign_abi_VMStorage::debugName(oop entry) {
4213   return entry->obj_field(_debugName_offset);
4214 }
4215 
4216 int jdk_internal_foreign_abi_CallConv::_argRegs_offset;
4217 int jdk_internal_foreign_abi_CallConv::_retRegs_offset;
4218 
4219 #define CallConv_FIELDS_DO(macro) \
4220   macro(_argRegs_offset, k, "argRegs", jdk_internal_foreign_abi_VMStorage_array_signature, false); \
4221   macro(_retRegs_offset, k, "retRegs", jdk_internal_foreign_abi_VMStorage_array_signature, false); \
4222 
4223 bool jdk_internal_foreign_abi_CallConv::is_instance(oop obj) {
4224   return obj != nullptr && is_subclass(obj->klass());
4225 }
4226 
4227 void jdk_internal_foreign_abi_CallConv::compute_offsets() {
4228   InstanceKlass* k = vmClasses::CallConv_klass();
4229   CallConv_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4230 }
4231 
4232 #if INCLUDE_CDS
4233 void jdk_internal_foreign_abi_CallConv::serialize_offsets(SerializeClosure* f) {
4234   CallConv_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4235 }
4236 #endif
4237 
4238 objArrayOop jdk_internal_foreign_abi_CallConv::argRegs(oop entry) {
4239   return oop_cast<objArrayOop>(entry->obj_field(_argRegs_offset));
4240 }
4241 
4242 objArrayOop jdk_internal_foreign_abi_CallConv::retRegs(oop entry) {
4243   return oop_cast<objArrayOop>(entry->obj_field(_retRegs_offset));
4244 }
4245 
4246 oop java_lang_invoke_MethodHandle::type(oop mh) {
4247   return mh->obj_field(_type_offset);
4248 }
4249 
4250 void java_lang_invoke_MethodHandle::set_type(oop mh, oop mtype) {
4251   mh->obj_field_put(_type_offset, mtype);
4252 }
4253 
4254 oop java_lang_invoke_MethodHandle::form(oop mh) {
4255   assert(_form_offset != 0, "");
4256   return mh->obj_field(_form_offset);
4257 }
4258 
4259 void java_lang_invoke_MethodHandle::set_form(oop mh, oop lform) {
4260   assert(_form_offset != 0, "");
4261   mh->obj_field_put(_form_offset, lform);
4262 }
4263 
4264 /// MemberName accessors
4265 
4266 oop java_lang_invoke_MemberName::clazz(oop mname) {
4267   assert(is_instance(mname), "wrong type");
4268   return mname->obj_field(_clazz_offset);
4269 }
4270 
4271 void java_lang_invoke_MemberName::set_clazz(oop mname, oop clazz) {
4272   assert(is_instance(mname), "wrong type");
4273   mname->obj_field_put(_clazz_offset, clazz);
4274 }
4275 
4276 oop java_lang_invoke_MemberName::name(oop mname) {
4277   assert(is_instance(mname), "wrong type");
4278   return mname->obj_field(_name_offset);
4279 }
4280 
4281 void java_lang_invoke_MemberName::set_name(oop mname, oop name) {
4282   assert(is_instance(mname), "wrong type");
4283   mname->obj_field_put(_name_offset, name);
4284 }
4285 
4286 oop java_lang_invoke_MemberName::type(oop mname) {
4287   assert(is_instance(mname), "wrong type");
4288   return mname->obj_field(_type_offset);
4289 }
4290 
4291 void java_lang_invoke_MemberName::set_type(oop mname, oop type) {
4292   assert(is_instance(mname), "wrong type");
4293   mname->obj_field_put(_type_offset, type);
4294 }
4295 
4296 int java_lang_invoke_MemberName::flags(oop mname) {
4297   assert(is_instance(mname), "wrong type");
4298   return mname->int_field(_flags_offset);
4299 }
4300 
4301 void java_lang_invoke_MemberName::set_flags(oop mname, int flags) {
4302   assert(is_instance(mname), "wrong type");
4303   mname->int_field_put(_flags_offset, flags);
4304 }
4305 
4306 
4307 // Return vmtarget from ResolvedMethodName method field through indirection
4308 Method* java_lang_invoke_MemberName::vmtarget(oop mname) {
4309   assert(is_instance(mname), "wrong type");
4310   oop method = mname->obj_field(_method_offset);
4311   return method == nullptr ? nullptr : java_lang_invoke_ResolvedMethodName::vmtarget(method);
4312 }
4313 
4314 bool java_lang_invoke_MemberName::is_method(oop mname) {
4315   assert(is_instance(mname), "must be MemberName");
4316   return (flags(mname) & (MN_IS_METHOD | MN_IS_CONSTRUCTOR)) > 0;
4317 }
4318 
4319 void java_lang_invoke_MemberName::set_method(oop mname, oop resolved_method) {
4320   assert(is_instance(mname), "wrong type");
4321   mname->obj_field_put(_method_offset, resolved_method);
4322 }
4323 
4324 intptr_t java_lang_invoke_MemberName::vmindex(oop mname) {
4325   assert(is_instance(mname), "wrong type");
4326   return (intptr_t) mname->address_field(_vmindex_offset);
4327 }
4328 
4329 void java_lang_invoke_MemberName::set_vmindex(oop mname, intptr_t index) {
4330   assert(is_instance(mname), "wrong type");
4331   mname->address_field_put(_vmindex_offset, (address) index);
4332 }
4333 
4334 
4335 Method* java_lang_invoke_ResolvedMethodName::vmtarget(oop resolved_method) {
4336   assert(is_instance(resolved_method), "wrong type");
4337   Method* m = (Method*)resolved_method->address_field(_vmtarget_offset);
4338   assert(m->is_method(), "must be");
4339   return m;
4340 }
4341 
4342 // Used by redefinition to change Method* to new Method* with same hash (name, signature)
4343 void java_lang_invoke_ResolvedMethodName::set_vmtarget(oop resolved_method, Method* m) {
4344   assert(is_instance(resolved_method), "wrong type");
4345   resolved_method->address_field_put(_vmtarget_offset, (address)m);
4346 }
4347 
4348 void java_lang_invoke_ResolvedMethodName::set_vmholder(oop resolved_method, oop holder) {
4349   assert(is_instance(resolved_method), "wrong type");
4350   resolved_method->obj_field_put(_vmholder_offset, holder);
4351 }
4352 
4353 oop java_lang_invoke_ResolvedMethodName::find_resolved_method(const methodHandle& m, TRAPS) {
4354   const Method* method = m();
4355 
4356   // lookup ResolvedMethod oop in the table, or create a new one and intern it
4357   oop resolved_method = ResolvedMethodTable::find_method(method);
4358   if (resolved_method != nullptr) {
4359     return resolved_method;
4360   }
4361 
4362   InstanceKlass* k = vmClasses::ResolvedMethodName_klass();
4363   if (!k->is_initialized()) {
4364     k->initialize(CHECK_NULL);
4365   }
4366 
4367   oop new_resolved_method = k->allocate_instance(CHECK_NULL);
4368 
4369   NoSafepointVerifier nsv;
4370 
4371   if (method->is_old()) {
4372     method = (method->is_deleted()) ? Universe::throw_no_such_method_error() :
4373                                       method->get_new_method();
4374   }
4375 
4376   InstanceKlass* holder = method->method_holder();
4377 
4378   set_vmtarget(new_resolved_method, const_cast<Method*>(method));
4379   // Add a reference to the loader (actually mirror because hidden classes may not have
4380   // distinct loaders) to ensure the metadata is kept alive.
4381   // This mirror may be different than the one in clazz field.
4382   set_vmholder(new_resolved_method, holder->java_mirror());
4383 
4384   // Set flag in class to indicate this InstanceKlass has entries in the table
4385   // to avoid walking table during redefinition if none of the redefined classes
4386   // have any membernames in the table.
4387   holder->set_has_resolved_methods();
4388 
4389   return ResolvedMethodTable::add_method(method, Handle(THREAD, new_resolved_method));
4390 }
4391 
4392 oop java_lang_invoke_LambdaForm::vmentry(oop lform) {
4393   assert(is_instance(lform), "wrong type");
4394   return lform->obj_field(_vmentry_offset);
4395 }
4396 
4397 
4398 // Support for java_lang_invoke_MethodType
4399 
4400 int java_lang_invoke_MethodType::_rtype_offset;
4401 int java_lang_invoke_MethodType::_ptypes_offset;
4402 
4403 #define METHODTYPE_FIELDS_DO(macro) \
4404   macro(_rtype_offset,  k, "rtype",  class_signature,       false); \
4405   macro(_ptypes_offset, k, "ptypes", class_array_signature, false)
4406 
4407 void java_lang_invoke_MethodType::compute_offsets() {
4408   InstanceKlass* k = vmClasses::MethodType_klass();
4409   METHODTYPE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4410 }
4411 
4412 #if INCLUDE_CDS
4413 void java_lang_invoke_MethodType::serialize_offsets(SerializeClosure* f) {
4414   METHODTYPE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4415 }
4416 #endif
4417 
4418 void java_lang_invoke_MethodType::print_signature(oop mt, outputStream* st) {
4419   st->print("(");
4420   objArrayOop pts = ptypes(mt);
4421   if (pts != nullptr) {
4422     for (int i = 0, limit = pts->length(); i < limit; i++) {
4423       java_lang_Class::print_signature(pts->obj_at(i), st);
4424     }
4425   } else {
4426     st->print("null");
4427   }
4428   st->print(")");
4429   oop rt = rtype(mt);
4430   if (rt != nullptr) {
4431     java_lang_Class::print_signature(rt, st);
4432   } else {
4433     st->print("null");
4434   }
4435 }
4436 
4437 Symbol* java_lang_invoke_MethodType::as_signature(oop mt, bool intern_if_not_found) {
4438   ResourceMark rm;
4439   stringStream buffer(128);
4440   print_signature(mt, &buffer);
4441   const char* sigstr =       buffer.base();
4442   int         siglen = (int) buffer.size();
4443   Symbol *name;
4444   if (!intern_if_not_found) {
4445     name = SymbolTable::probe(sigstr, siglen);
4446   } else {
4447     name = SymbolTable::new_symbol(sigstr, siglen);
4448   }
4449   return name;
4450 }
4451 
4452 bool java_lang_invoke_MethodType::equals(oop mt1, oop mt2) {
4453   if (mt1 == mt2)
4454     return true;
4455   if (rtype(mt1) != rtype(mt2))
4456     return false;
4457   if (ptype_count(mt1) != ptype_count(mt2))
4458     return false;
4459   for (int i = ptype_count(mt1) - 1; i >= 0; i--) {
4460     if (ptype(mt1, i) != ptype(mt2, i))
4461       return false;
4462   }
4463   return true;
4464 }
4465 
4466 oop java_lang_invoke_MethodType::rtype(oop mt) {
4467   assert(is_instance(mt), "must be a MethodType");
4468   return mt->obj_field(_rtype_offset);
4469 }
4470 
4471 objArrayOop java_lang_invoke_MethodType::ptypes(oop mt) {
4472   assert(is_instance(mt), "must be a MethodType");
4473   return (objArrayOop) mt->obj_field(_ptypes_offset);
4474 }
4475 
4476 oop java_lang_invoke_MethodType::ptype(oop mt, int idx) {
4477   return ptypes(mt)->obj_at(idx);
4478 }
4479 
4480 int java_lang_invoke_MethodType::ptype_count(oop mt) {
4481   return ptypes(mt)->length();
4482 }
4483 
4484 int java_lang_invoke_MethodType::ptype_slot_count(oop mt) {
4485   objArrayOop pts = ptypes(mt);
4486   int count = pts->length();
4487   int slots = 0;
4488   for (int i = 0; i < count; i++) {
4489     BasicType bt = java_lang_Class::as_BasicType(pts->obj_at(i));
4490     slots += type2size[bt];
4491   }
4492   return slots;
4493 }
4494 
4495 int java_lang_invoke_MethodType::rtype_slot_count(oop mt) {
4496   BasicType bt = java_lang_Class::as_BasicType(rtype(mt));
4497   return type2size[bt];
4498 }
4499 
4500 
4501 // Support for java_lang_invoke_CallSite
4502 
4503 int java_lang_invoke_CallSite::_target_offset;
4504 int java_lang_invoke_CallSite::_context_offset;
4505 
4506 #define CALLSITE_FIELDS_DO(macro) \
4507   macro(_target_offset,  k, "target", java_lang_invoke_MethodHandle_signature, false); \
4508   macro(_context_offset, k, "context", java_lang_invoke_MethodHandleNatives_CallSiteContext_signature, false)
4509 
4510 void java_lang_invoke_CallSite::compute_offsets() {
4511   InstanceKlass* k = vmClasses::CallSite_klass();
4512   CALLSITE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4513 }
4514 
4515 #if INCLUDE_CDS
4516 void java_lang_invoke_CallSite::serialize_offsets(SerializeClosure* f) {
4517   CALLSITE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4518 }
4519 #endif
4520 
4521 oop java_lang_invoke_CallSite::context_no_keepalive(oop call_site) {
4522   assert(java_lang_invoke_CallSite::is_instance(call_site), "");
4523 
4524   oop dep_oop = call_site->obj_field_access<AS_NO_KEEPALIVE>(_context_offset);
4525   return dep_oop;
4526 }
4527 
4528 // Support for java_lang_invoke_ConstantCallSite
4529 
4530 int java_lang_invoke_ConstantCallSite::_is_frozen_offset;
4531 
4532 #define CONSTANTCALLSITE_FIELDS_DO(macro) \
4533   macro(_is_frozen_offset, k, "isFrozen", bool_signature, false)
4534 
4535 void java_lang_invoke_ConstantCallSite::compute_offsets() {
4536   InstanceKlass* k = vmClasses::ConstantCallSite_klass();
4537   CONSTANTCALLSITE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4538 }
4539 
4540 #if INCLUDE_CDS
4541 void java_lang_invoke_ConstantCallSite::serialize_offsets(SerializeClosure* f) {
4542   CONSTANTCALLSITE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4543 }
4544 #endif
4545 
4546 // Support for java_lang_invoke_MethodHandleNatives_CallSiteContext
4547 
4548 int java_lang_invoke_MethodHandleNatives_CallSiteContext::_vmdependencies_offset;
4549 int java_lang_invoke_MethodHandleNatives_CallSiteContext::_last_cleanup_offset;
4550 
4551 void java_lang_invoke_MethodHandleNatives_CallSiteContext::compute_offsets() {
4552   InstanceKlass* k = vmClasses::Context_klass();
4553   CALLSITECONTEXT_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
4554 }
4555 
4556 #if INCLUDE_CDS
4557 void java_lang_invoke_MethodHandleNatives_CallSiteContext::serialize_offsets(SerializeClosure* f) {
4558   CALLSITECONTEXT_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
4559 }
4560 #endif
4561 
4562 DependencyContext java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(oop call_site) {
4563   assert(java_lang_invoke_MethodHandleNatives_CallSiteContext::is_instance(call_site), "");
4564   nmethodBucket* volatile* vmdeps_addr = call_site->field_addr<nmethodBucket* volatile>(_vmdependencies_offset);
4565   volatile uint64_t* last_cleanup_addr = call_site->field_addr<volatile uint64_t>(_last_cleanup_offset);
4566   DependencyContext dep_ctx(vmdeps_addr, last_cleanup_addr);
4567   return dep_ctx;
4568 }
4569 
4570 // Support for java_security_AccessControlContext
4571 
4572 int java_security_AccessControlContext::_context_offset;
4573 int java_security_AccessControlContext::_privilegedContext_offset;
4574 int java_security_AccessControlContext::_isPrivileged_offset;
4575 int java_security_AccessControlContext::_isAuthorized_offset;
4576 
4577 #define ACCESSCONTROLCONTEXT_FIELDS_DO(macro) \
4578   macro(_context_offset,           k, "context",      protectiondomain_signature, false); \
4579   macro(_privilegedContext_offset, k, "privilegedContext", accesscontrolcontext_signature, false); \
4580   macro(_isPrivileged_offset,      k, "isPrivileged", bool_signature, false); \
4581   macro(_isAuthorized_offset,      k, "isAuthorized", bool_signature, false)
4582 
4583 void java_security_AccessControlContext::compute_offsets() {
4584   assert(_isPrivileged_offset == 0, "offsets should be initialized only once");
4585   InstanceKlass* k = vmClasses::AccessControlContext_klass();
4586   ACCESSCONTROLCONTEXT_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4587 }
4588 
4589 #if INCLUDE_CDS
4590 void java_security_AccessControlContext::serialize_offsets(SerializeClosure* f) {
4591   ACCESSCONTROLCONTEXT_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4592 }
4593 #endif
4594 
4595 oop java_security_AccessControlContext::create(objArrayHandle context, bool isPrivileged, Handle privileged_context, TRAPS) {
4596   assert(_isPrivileged_offset != 0, "offsets should have been initialized");
4597   assert(_isAuthorized_offset != 0, "offsets should have been initialized");
4598   // Ensure klass is initialized
4599   vmClasses::AccessControlContext_klass()->initialize(CHECK_NULL);
4600   // Allocate result
4601   oop result = vmClasses::AccessControlContext_klass()->allocate_instance(CHECK_NULL);
4602   // Fill in values
4603   result->obj_field_put(_context_offset, context());
4604   result->obj_field_put(_privilegedContext_offset, privileged_context());
4605   result->bool_field_put(_isPrivileged_offset, isPrivileged);
4606   result->bool_field_put(_isAuthorized_offset, true);
4607   return result;
4608 }
4609 
4610 
4611 // Support for java_lang_ClassLoader
4612 
4613 int  java_lang_ClassLoader::_loader_data_offset;
4614 int  java_lang_ClassLoader::_parallelCapable_offset;
4615 int  java_lang_ClassLoader::_name_offset;
4616 int  java_lang_ClassLoader::_nameAndId_offset;
4617 int  java_lang_ClassLoader::_unnamedModule_offset;
4618 int  java_lang_ClassLoader::_parent_offset;
4619 
4620 ClassLoaderData* java_lang_ClassLoader::loader_data_acquire(oop loader) {
4621   assert(loader != nullptr, "loader must not be null");
4622   assert(oopDesc::is_oop(loader), "loader must be oop");
4623   return Atomic::load_acquire(loader->field_addr<ClassLoaderData*>(_loader_data_offset));
4624 }
4625 
4626 ClassLoaderData* java_lang_ClassLoader::loader_data(oop loader) {
4627   assert(loader != nullptr, "loader must not be null");
4628   assert(oopDesc::is_oop(loader), "loader must be oop");
4629   return *loader->field_addr<ClassLoaderData*>(_loader_data_offset);
4630 }
4631 
4632 void java_lang_ClassLoader::release_set_loader_data(oop loader, ClassLoaderData* new_data) {
4633   assert(loader != nullptr, "loader must not be null");
4634   assert(oopDesc::is_oop(loader), "loader must be oop");
4635   Atomic::release_store(loader->field_addr<ClassLoaderData*>(_loader_data_offset), new_data);
4636 }
4637 
4638 #define CLASSLOADER_FIELDS_DO(macro) \
4639   macro(_parallelCapable_offset, k1, "parallelLockMap",      concurrenthashmap_signature, false); \
4640   macro(_name_offset,            k1, vmSymbols::name_name(), string_signature, false); \
4641   macro(_nameAndId_offset,       k1, "nameAndId",            string_signature, false); \
4642   macro(_unnamedModule_offset,   k1, "unnamedModule",        module_signature, false); \
4643   macro(_parent_offset,          k1, "parent",               classloader_signature, false)
4644 
4645 void java_lang_ClassLoader::compute_offsets() {
4646   InstanceKlass* k1 = vmClasses::ClassLoader_klass();
4647   CLASSLOADER_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4648 
4649   CLASSLOADER_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
4650 }
4651 
4652 #if INCLUDE_CDS
4653 void java_lang_ClassLoader::serialize_offsets(SerializeClosure* f) {
4654   CLASSLOADER_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4655   CLASSLOADER_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
4656 }
4657 #endif
4658 
4659 oop java_lang_ClassLoader::parent(oop loader) {
4660   assert(is_instance(loader), "loader must be oop");
4661   return loader->obj_field(_parent_offset);
4662 }
4663 
4664 oop java_lang_ClassLoader::parent_no_keepalive(oop loader) {
4665   assert(is_instance(loader), "loader must be oop");
4666   return loader->obj_field_access<AS_NO_KEEPALIVE>(_parent_offset);
4667 }
4668 
4669 // Returns the name field of this class loader.  If the name field has not
4670 // been set, null will be returned.
4671 oop java_lang_ClassLoader::name(oop loader) {
4672   assert(is_instance(loader), "loader must be oop");
4673   return loader->obj_field(_name_offset);
4674 }
4675 
4676 // Returns the nameAndId field of this class loader. The format is
4677 // as follows:
4678 //   If the defining loader has a name explicitly set then '<loader-name>' @<id>
4679 //   If the defining loader has no name then <qualified-class-name> @<id>
4680 //   If built-in loader, then omit '@<id>' as there is only one instance.
4681 // Use ClassLoader::loader_name_id() to obtain this String as a char*.
4682 oop java_lang_ClassLoader::nameAndId(oop loader) {
4683   assert(is_instance(loader), "loader must be oop");
4684   return loader->obj_field(_nameAndId_offset);
4685 }
4686 
4687 bool java_lang_ClassLoader::isAncestor(oop loader, oop cl) {
4688   assert(is_instance(loader), "loader must be oop");
4689   assert(cl == nullptr || is_instance(cl), "cl argument must be oop");
4690   oop acl = loader;
4691   debug_only(jint loop_count = 0);
4692   // This loop taken verbatim from ClassLoader.java:
4693   do {
4694     acl = parent(acl);
4695     if (cl == acl) {
4696       return true;
4697     }
4698     assert(++loop_count > 0, "loop_count overflow");
4699   } while (acl != nullptr);
4700   return false;
4701 }
4702 
4703 bool java_lang_ClassLoader::is_instance(oop obj) {
4704   return obj != nullptr && is_subclass(obj->klass());
4705 }
4706 
4707 
4708 // For class loader classes, parallelCapable defined
4709 // based on non-null field
4710 // Written to by java.lang.ClassLoader, vm only reads this field, doesn't set it
4711 bool java_lang_ClassLoader::parallelCapable(oop class_loader) {
4712   assert(_parallelCapable_offset != 0, "offsets should have been initialized");
4713   return (class_loader->obj_field(_parallelCapable_offset) != nullptr);
4714 }
4715 
4716 bool java_lang_ClassLoader::is_trusted_loader(oop loader) {
4717   // Fix for 4474172; see evaluation for more details
4718   loader = non_reflection_class_loader(loader);
4719 
4720   oop cl = SystemDictionary::java_system_loader();
4721   while(cl != nullptr) {
4722     if (cl == loader) return true;
4723     cl = parent(cl);
4724   }
4725   return false;
4726 }
4727 
4728 // Return true if this is one of the class loaders associated with
4729 // the generated bytecodes for serialization constructor returned
4730 // by sun.reflect.ReflectionFactory::newConstructorForSerialization
4731 bool java_lang_ClassLoader::is_reflection_class_loader(oop loader) {
4732   if (loader != nullptr) {
4733     Klass* delegating_cl_class = vmClasses::reflect_DelegatingClassLoader_klass();
4734     // This might be null in non-1.4 JDKs
4735     return (delegating_cl_class != nullptr && loader->is_a(delegating_cl_class));
4736   }
4737   return false;
4738 }
4739 
4740 oop java_lang_ClassLoader::non_reflection_class_loader(oop loader) {
4741   // See whether this is one of the class loaders associated with
4742   // the generated bytecodes for reflection, and if so, "magically"
4743   // delegate to its parent to prevent class loading from occurring
4744   // in places where applications using reflection didn't expect it.
4745   if (is_reflection_class_loader(loader)) {
4746     return parent(loader);
4747   }
4748   return loader;
4749 }
4750 
4751 oop java_lang_ClassLoader::unnamedModule(oop loader) {
4752   assert(is_instance(loader), "loader must be oop");
4753   return loader->obj_field(_unnamedModule_offset);
4754 }
4755 
4756 // Support for java_lang_System
4757 //
4758 
4759 int java_lang_System::_static_in_offset;
4760 int java_lang_System::_static_out_offset;
4761 int java_lang_System::_static_err_offset;
4762 int java_lang_System::_static_security_offset;
4763 int java_lang_System::_static_allow_security_offset;
4764 int java_lang_System::_static_never_offset;
4765 
4766 #define SYSTEM_FIELDS_DO(macro) \
4767   macro(_static_in_offset,  k, "in",  input_stream_signature, true); \
4768   macro(_static_out_offset, k, "out", print_stream_signature, true); \
4769   macro(_static_err_offset, k, "err", print_stream_signature, true); \
4770   macro(_static_security_offset, k, "security", security_manager_signature, true); \
4771   macro(_static_allow_security_offset, k, "allowSecurityManager", int_signature, true); \
4772   macro(_static_never_offset, k, "NEVER", int_signature, true)
4773 
4774 void java_lang_System::compute_offsets() {
4775   InstanceKlass* k = vmClasses::System_klass();
4776   SYSTEM_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4777 }
4778 
4779 // This field tells us that a security manager can never be installed so we
4780 // can completely skip populating the ProtectionDomainCacheTable.
4781 bool java_lang_System::allow_security_manager() {
4782   static int initialized = false;
4783   static bool allowed = true; // default
4784   if (!initialized) {
4785     oop base = vmClasses::System_klass()->static_field_base_raw();
4786     int never = base->int_field(_static_never_offset);
4787     allowed = (base->int_field(_static_allow_security_offset) != never);
4788     initialized = true;
4789   }
4790   return allowed;
4791 }
4792 
4793 // This field tells us that a security manager is installed.
4794 bool java_lang_System::has_security_manager() {
4795   oop base = vmClasses::System_klass()->static_field_base_raw();
4796   return base->obj_field(_static_security_offset) != nullptr;
4797 }
4798 
4799 #if INCLUDE_CDS
4800 void java_lang_System::serialize_offsets(SerializeClosure* f) {
4801    SYSTEM_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4802 }
4803 #endif
4804 
4805 // Support for jdk_internal_misc_UnsafeConstants
4806 //
4807 class UnsafeConstantsFixup : public FieldClosure {
4808 private:
4809   int _address_size;
4810   int _page_size;
4811   bool _big_endian;
4812   bool _use_unaligned_access;
4813   int _data_cache_line_flush_size;
4814 public:
4815   UnsafeConstantsFixup() {
4816     // round up values for all static final fields
4817     _address_size = sizeof(void*);
4818     _page_size = AIX_ONLY(sysconf(_SC_PAGESIZE)) NOT_AIX((int)os::vm_page_size());
4819     _big_endian = LITTLE_ENDIAN_ONLY(false) BIG_ENDIAN_ONLY(true);
4820     _use_unaligned_access = UseUnalignedAccesses;
4821     _data_cache_line_flush_size = (int)VM_Version::data_cache_line_flush_size();
4822   }
4823 
4824   void do_field(fieldDescriptor* fd) {
4825     oop mirror = fd->field_holder()->java_mirror();
4826     assert(mirror != nullptr, "UnsafeConstants must have mirror already");
4827     assert(fd->field_holder() == vmClasses::UnsafeConstants_klass(), "Should be UnsafeConstants");
4828     assert(fd->is_final(), "fields of UnsafeConstants must be final");
4829     assert(fd->is_static(), "fields of UnsafeConstants must be static");
4830     if (fd->name() == vmSymbols::address_size_name()) {
4831       mirror->int_field_put(fd->offset(), _address_size);
4832     } else if (fd->name() == vmSymbols::page_size_name()) {
4833       mirror->int_field_put(fd->offset(), _page_size);
4834     } else if (fd->name() == vmSymbols::big_endian_name()) {
4835       mirror->bool_field_put(fd->offset(), _big_endian);
4836     } else if (fd->name() == vmSymbols::use_unaligned_access_name()) {
4837       mirror->bool_field_put(fd->offset(), _use_unaligned_access);
4838     } else if (fd->name() == vmSymbols::data_cache_line_flush_size_name()) {
4839       mirror->int_field_put(fd->offset(), _data_cache_line_flush_size);
4840     } else {
4841       assert(false, "unexpected UnsafeConstants field");
4842     }
4843   }
4844 };
4845 
4846 void jdk_internal_misc_UnsafeConstants::set_unsafe_constants() {
4847   UnsafeConstantsFixup fixup;
4848   vmClasses::UnsafeConstants_klass()->do_local_static_fields(&fixup);
4849 }
4850 
4851 
4852 // java_lang_StackTraceElement
4853 
4854 int java_lang_StackTraceElement::_methodName_offset;
4855 int java_lang_StackTraceElement::_fileName_offset;
4856 int java_lang_StackTraceElement::_lineNumber_offset;
4857 int java_lang_StackTraceElement::_moduleName_offset;
4858 int java_lang_StackTraceElement::_moduleVersion_offset;
4859 int java_lang_StackTraceElement::_classLoaderName_offset;
4860 int java_lang_StackTraceElement::_declaringClass_offset;
4861 int java_lang_StackTraceElement::_declaringClassObject_offset;
4862 
4863 #define STACKTRACEELEMENT_FIELDS_DO(macro) \
4864   macro(_declaringClassObject_offset,  k, "declaringClassObject", class_signature, false); \
4865   macro(_classLoaderName_offset, k, "classLoaderName", string_signature, false); \
4866   macro(_moduleName_offset,      k, "moduleName",      string_signature, false); \
4867   macro(_moduleVersion_offset,   k, "moduleVersion",   string_signature, false); \
4868   macro(_declaringClass_offset,  k, "declaringClass",  string_signature, false); \
4869   macro(_methodName_offset,      k, "methodName",      string_signature, false); \
4870   macro(_fileName_offset,        k, "fileName",        string_signature, false); \
4871   macro(_lineNumber_offset,      k, "lineNumber",      int_signature,    false)
4872 
4873 // Support for java_lang_StackTraceElement
4874 void java_lang_StackTraceElement::compute_offsets() {
4875   InstanceKlass* k = vmClasses::StackTraceElement_klass();
4876   STACKTRACEELEMENT_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4877 }
4878 
4879 #if INCLUDE_CDS
4880 void java_lang_StackTraceElement::serialize_offsets(SerializeClosure* f) {
4881   STACKTRACEELEMENT_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4882 }
4883 #endif
4884 
4885 void java_lang_StackTraceElement::set_fileName(oop element, oop value) {
4886   element->obj_field_put(_fileName_offset, value);
4887 }
4888 
4889 void java_lang_StackTraceElement::set_declaringClass(oop element, oop value) {
4890   element->obj_field_put(_declaringClass_offset, value);
4891 }
4892 
4893 void java_lang_StackTraceElement::set_methodName(oop element, oop value) {
4894   element->obj_field_put(_methodName_offset, value);
4895 }
4896 
4897 void java_lang_StackTraceElement::set_lineNumber(oop element, int value) {
4898   element->int_field_put(_lineNumber_offset, value);
4899 }
4900 
4901 void java_lang_StackTraceElement::set_moduleName(oop element, oop value) {
4902   element->obj_field_put(_moduleName_offset, value);
4903 }
4904 
4905 void java_lang_StackTraceElement::set_moduleVersion(oop element, oop value) {
4906   element->obj_field_put(_moduleVersion_offset, value);
4907 }
4908 
4909 void java_lang_StackTraceElement::set_classLoaderName(oop element, oop value) {
4910   element->obj_field_put(_classLoaderName_offset, value);
4911 }
4912 
4913 void java_lang_StackTraceElement::set_declaringClassObject(oop element, oop value) {
4914   element->obj_field_put(_declaringClassObject_offset, value);
4915 }
4916 
4917 
4918 // java_lang_AssertionStatusDirectives
4919 
4920 int java_lang_AssertionStatusDirectives::_classes_offset;
4921 int java_lang_AssertionStatusDirectives::_classEnabled_offset;
4922 int java_lang_AssertionStatusDirectives::_packages_offset;
4923 int java_lang_AssertionStatusDirectives::_packageEnabled_offset;
4924 int java_lang_AssertionStatusDirectives::_deflt_offset;
4925 
4926 // Support for java Assertions - java_lang_AssertionStatusDirectives.
4927 #define ASSERTIONSTATUSDIRECTIVES_FIELDS_DO(macro) \
4928   macro(_classes_offset,        k, "classes",        string_array_signature, false); \
4929   macro(_classEnabled_offset,   k, "classEnabled",   bool_array_signature, false); \
4930   macro(_packages_offset,       k, "packages",       string_array_signature, false); \
4931   macro(_packageEnabled_offset, k, "packageEnabled", bool_array_signature,   false); \
4932   macro(_deflt_offset,          k, "deflt",          bool_signature,         false)
4933 
4934 void java_lang_AssertionStatusDirectives::compute_offsets() {
4935   InstanceKlass* k = vmClasses::AssertionStatusDirectives_klass();
4936   ASSERTIONSTATUSDIRECTIVES_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4937 }
4938 
4939 #if INCLUDE_CDS
4940 void java_lang_AssertionStatusDirectives::serialize_offsets(SerializeClosure* f) {
4941   ASSERTIONSTATUSDIRECTIVES_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4942 }
4943 #endif
4944 
4945 void java_lang_AssertionStatusDirectives::set_classes(oop o, oop val) {
4946   o->obj_field_put(_classes_offset, val);
4947 }
4948 
4949 void java_lang_AssertionStatusDirectives::set_classEnabled(oop o, oop val) {
4950   o->obj_field_put(_classEnabled_offset, val);
4951 }
4952 
4953 void java_lang_AssertionStatusDirectives::set_packages(oop o, oop val) {
4954   o->obj_field_put(_packages_offset, val);
4955 }
4956 
4957 void java_lang_AssertionStatusDirectives::set_packageEnabled(oop o, oop val) {
4958   o->obj_field_put(_packageEnabled_offset, val);
4959 }
4960 
4961 void java_lang_AssertionStatusDirectives::set_deflt(oop o, bool val) {
4962   o->bool_field_put(_deflt_offset, val);
4963 }
4964 
4965 int java_util_concurrent_locks_AbstractOwnableSynchronizer::_owner_offset;
4966 
4967 #define AOS_FIELDS_DO(macro) \
4968   macro(_owner_offset, k, "exclusiveOwnerThread", thread_signature, false)
4969 
4970 void java_util_concurrent_locks_AbstractOwnableSynchronizer::compute_offsets() {
4971   InstanceKlass* k = vmClasses::java_util_concurrent_locks_AbstractOwnableSynchronizer_klass();
4972   AOS_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4973 }
4974 
4975 oop java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(oop obj) {
4976   assert(_owner_offset != 0, "Must be initialized");
4977   return obj->obj_field(_owner_offset);
4978 }
4979 
4980 #if INCLUDE_CDS
4981 void java_util_concurrent_locks_AbstractOwnableSynchronizer::serialize_offsets(SerializeClosure* f) {
4982   AOS_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4983 }
4984 #endif
4985 
4986 int vector_VectorPayload::_payload_offset;
4987 
4988 #define VECTORPAYLOAD_FIELDS_DO(macro) \
4989   macro(_payload_offset, k, "payload", object_signature, false)
4990 
4991 void vector_VectorPayload::compute_offsets() {
4992   InstanceKlass* k = vmClasses::vector_VectorPayload_klass();
4993   VECTORPAYLOAD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4994 }
4995 
4996 #if INCLUDE_CDS
4997 void vector_VectorPayload::serialize_offsets(SerializeClosure* f) {
4998   VECTORPAYLOAD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4999 }
5000 #endif
5001 
5002 void vector_VectorPayload::set_payload(oop o, oop val) {
5003   o->obj_field_put(_payload_offset, val);
5004 }
5005 
5006 bool vector_VectorPayload::is_instance(oop obj) {
5007   return obj != nullptr && is_subclass(obj->klass());
5008 }
5009 
5010 int java_lang_Integer_IntegerCache::_static_cache_offset;
5011 int java_lang_Long_LongCache::_static_cache_offset;
5012 int java_lang_Character_CharacterCache::_static_cache_offset;
5013 int java_lang_Short_ShortCache::_static_cache_offset;
5014 int java_lang_Byte_ByteCache::_static_cache_offset;
5015 
5016 #define INTEGER_CACHE_FIELDS_DO(macro) \
5017   macro(_static_cache_offset, k, "cache", java_lang_Integer_array_signature, true)
5018 
5019 void java_lang_Integer_IntegerCache::compute_offsets(InstanceKlass *k) {
5020   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5021   INTEGER_CACHE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5022 }
5023 
5024 objArrayOop java_lang_Integer_IntegerCache::cache(InstanceKlass *ik) {
5025   oop base = ik->static_field_base_raw();
5026   return objArrayOop(base->obj_field(_static_cache_offset));
5027 }
5028 
5029 Symbol* java_lang_Integer_IntegerCache::symbol() {
5030   return vmSymbols::java_lang_Integer_IntegerCache();
5031 }
5032 
5033 #if INCLUDE_CDS
5034 void java_lang_Integer_IntegerCache::serialize_offsets(SerializeClosure* f) {
5035   INTEGER_CACHE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5036 }
5037 #endif
5038 #undef INTEGER_CACHE_FIELDS_DO
5039 
5040 jint java_lang_Integer::value(oop obj) {
5041    jvalue v;
5042    java_lang_boxing_object::get_value(obj, &v);
5043    return v.i;
5044 }
5045 
5046 #define LONG_CACHE_FIELDS_DO(macro) \
5047   macro(_static_cache_offset, k, "cache", java_lang_Long_array_signature, true)
5048 
5049 void java_lang_Long_LongCache::compute_offsets(InstanceKlass *k) {
5050   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5051   LONG_CACHE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5052 }
5053 
5054 objArrayOop java_lang_Long_LongCache::cache(InstanceKlass *ik) {
5055   oop base = ik->static_field_base_raw();
5056   return objArrayOop(base->obj_field(_static_cache_offset));
5057 }
5058 
5059 Symbol* java_lang_Long_LongCache::symbol() {
5060   return vmSymbols::java_lang_Long_LongCache();
5061 }
5062 
5063 #if INCLUDE_CDS
5064 void java_lang_Long_LongCache::serialize_offsets(SerializeClosure* f) {
5065   LONG_CACHE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5066 }
5067 #endif
5068 #undef LONG_CACHE_FIELDS_DO
5069 
5070 jlong java_lang_Long::value(oop obj) {
5071    jvalue v;
5072    java_lang_boxing_object::get_value(obj, &v);
5073    return v.j;
5074 }
5075 
5076 #define CHARACTER_CACHE_FIELDS_DO(macro) \
5077   macro(_static_cache_offset, k, "cache", java_lang_Character_array_signature, true)
5078 
5079 void java_lang_Character_CharacterCache::compute_offsets(InstanceKlass *k) {
5080   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5081   CHARACTER_CACHE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5082 }
5083 
5084 objArrayOop java_lang_Character_CharacterCache::cache(InstanceKlass *ik) {
5085   oop base = ik->static_field_base_raw();
5086   return objArrayOop(base->obj_field(_static_cache_offset));
5087 }
5088 
5089 Symbol* java_lang_Character_CharacterCache::symbol() {
5090   return vmSymbols::java_lang_Character_CharacterCache();
5091 }
5092 
5093 #if INCLUDE_CDS
5094 void java_lang_Character_CharacterCache::serialize_offsets(SerializeClosure* f) {
5095   CHARACTER_CACHE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5096 }
5097 #endif
5098 #undef CHARACTER_CACHE_FIELDS_DO
5099 
5100 jchar java_lang_Character::value(oop obj) {
5101    jvalue v;
5102    java_lang_boxing_object::get_value(obj, &v);
5103    return v.c;
5104 }
5105 
5106 #define SHORT_CACHE_FIELDS_DO(macro) \
5107   macro(_static_cache_offset, k, "cache", java_lang_Short_array_signature, true)
5108 
5109 void java_lang_Short_ShortCache::compute_offsets(InstanceKlass *k) {
5110   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5111   SHORT_CACHE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5112 }
5113 
5114 objArrayOop java_lang_Short_ShortCache::cache(InstanceKlass *ik) {
5115   oop base = ik->static_field_base_raw();
5116   return objArrayOop(base->obj_field(_static_cache_offset));
5117 }
5118 
5119 Symbol* java_lang_Short_ShortCache::symbol() {
5120   return vmSymbols::java_lang_Short_ShortCache();
5121 }
5122 
5123 #if INCLUDE_CDS
5124 void java_lang_Short_ShortCache::serialize_offsets(SerializeClosure* f) {
5125   SHORT_CACHE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5126 }
5127 #endif
5128 #undef SHORT_CACHE_FIELDS_DO
5129 
5130 jshort java_lang_Short::value(oop obj) {
5131    jvalue v;
5132    java_lang_boxing_object::get_value(obj, &v);
5133    return v.s;
5134 }
5135 
5136 #define BYTE_CACHE_FIELDS_DO(macro) \
5137   macro(_static_cache_offset, k, "cache", java_lang_Byte_array_signature, true)
5138 
5139 void java_lang_Byte_ByteCache::compute_offsets(InstanceKlass *k) {
5140   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5141   BYTE_CACHE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5142 }
5143 
5144 objArrayOop java_lang_Byte_ByteCache::cache(InstanceKlass *ik) {
5145   oop base = ik->static_field_base_raw();
5146   return objArrayOop(base->obj_field(_static_cache_offset));
5147 }
5148 
5149 Symbol* java_lang_Byte_ByteCache::symbol() {
5150   return vmSymbols::java_lang_Byte_ByteCache();
5151 }
5152 
5153 #if INCLUDE_CDS
5154 void java_lang_Byte_ByteCache::serialize_offsets(SerializeClosure* f) {
5155   BYTE_CACHE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5156 }
5157 #endif
5158 #undef BYTE_CACHE_FIELDS_DO
5159 
5160 jbyte java_lang_Byte::value(oop obj) {
5161    jvalue v;
5162    java_lang_boxing_object::get_value(obj, &v);
5163    return v.b;
5164 }
5165 
5166 int java_lang_Boolean::_static_TRUE_offset;
5167 int java_lang_Boolean::_static_FALSE_offset;
5168 
5169 #define BOOLEAN_FIELDS_DO(macro) \
5170   macro(_static_TRUE_offset, k, "TRUE", java_lang_Boolean_signature, true); \
5171   macro(_static_FALSE_offset, k, "FALSE", java_lang_Boolean_signature, true)
5172 
5173 
5174 void java_lang_Boolean::compute_offsets(InstanceKlass *k) {
5175   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5176   BOOLEAN_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5177 }
5178 
5179 oop java_lang_Boolean::get_TRUE(InstanceKlass *ik) {
5180   oop base = ik->static_field_base_raw();
5181   return base->obj_field(_static_TRUE_offset);
5182 }
5183 
5184 oop java_lang_Boolean::get_FALSE(InstanceKlass *ik) {
5185   oop base = ik->static_field_base_raw();
5186   return base->obj_field(_static_FALSE_offset);
5187 }
5188 
5189 Symbol* java_lang_Boolean::symbol() {
5190   return vmSymbols::java_lang_Boolean();
5191 }
5192 
5193 #if INCLUDE_CDS
5194 void java_lang_Boolean::serialize_offsets(SerializeClosure* f) {
5195   BOOLEAN_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5196 }
5197 #endif
5198 #undef BOOLEAN_CACHE_FIELDS_DO
5199 
5200 jboolean java_lang_Boolean::value(oop obj) {
5201    jvalue v;
5202    java_lang_boxing_object::get_value(obj, &v);
5203    return v.z;
5204 }
5205 
5206 // java_lang_reflect_RecordComponent
5207 
5208 int java_lang_reflect_RecordComponent::_clazz_offset;
5209 int java_lang_reflect_RecordComponent::_name_offset;
5210 int java_lang_reflect_RecordComponent::_type_offset;
5211 int java_lang_reflect_RecordComponent::_accessor_offset;
5212 int java_lang_reflect_RecordComponent::_signature_offset;
5213 int java_lang_reflect_RecordComponent::_annotations_offset;
5214 int java_lang_reflect_RecordComponent::_typeAnnotations_offset;
5215 
5216 #define RECORDCOMPONENT_FIELDS_DO(macro) \
5217   macro(_clazz_offset,       k, "clazz",       class_signature,  false); \
5218   macro(_name_offset,        k, "name",        string_signature, false); \
5219   macro(_type_offset,        k, "type",        class_signature,  false); \
5220   macro(_accessor_offset,    k, "accessor",    reflect_method_signature, false); \
5221   macro(_signature_offset,   k, "signature",   string_signature, false); \
5222   macro(_annotations_offset, k, "annotations", byte_array_signature,     false); \
5223   macro(_typeAnnotations_offset, k, "typeAnnotations", byte_array_signature, false);
5224 
5225 // Support for java_lang_reflect_RecordComponent
5226 void java_lang_reflect_RecordComponent::compute_offsets() {
5227   InstanceKlass* k = vmClasses::RecordComponent_klass();
5228   RECORDCOMPONENT_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5229 }
5230 
5231 #if INCLUDE_CDS
5232 void java_lang_reflect_RecordComponent::serialize_offsets(SerializeClosure* f) {
5233   RECORDCOMPONENT_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5234 }
5235 #endif
5236 
5237 void java_lang_reflect_RecordComponent::set_clazz(oop element, oop value) {
5238   element->obj_field_put(_clazz_offset, value);
5239 }
5240 
5241 void java_lang_reflect_RecordComponent::set_name(oop element, oop value) {
5242   element->obj_field_put(_name_offset, value);
5243 }
5244 
5245 void java_lang_reflect_RecordComponent::set_type(oop element, oop value) {
5246   element->obj_field_put(_type_offset, value);
5247 }
5248 
5249 void java_lang_reflect_RecordComponent::set_accessor(oop element, oop value) {
5250   element->obj_field_put(_accessor_offset, value);
5251 }
5252 
5253 void java_lang_reflect_RecordComponent::set_signature(oop element, oop value) {
5254   element->obj_field_put(_signature_offset, value);
5255 }
5256 
5257 void java_lang_reflect_RecordComponent::set_annotations(oop element, oop value) {
5258   element->obj_field_put(_annotations_offset, value);
5259 }
5260 
5261 void java_lang_reflect_RecordComponent::set_typeAnnotations(oop element, oop value) {
5262   element->obj_field_put(_typeAnnotations_offset, value);
5263 }
5264 
5265 // java_lang_InternalError
5266 int java_lang_InternalError::_during_unsafe_access_offset;
5267 
5268 void java_lang_InternalError::set_during_unsafe_access(oop internal_error) {
5269   internal_error->bool_field_put(_during_unsafe_access_offset, true);
5270 }
5271 
5272 jboolean java_lang_InternalError::during_unsafe_access(oop internal_error) {
5273   return internal_error->bool_field(_during_unsafe_access_offset);
5274 }
5275 
5276 void java_lang_InternalError::compute_offsets() {
5277   INTERNALERROR_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
5278 }
5279 
5280 #if INCLUDE_CDS
5281 void java_lang_InternalError::serialize_offsets(SerializeClosure* f) {
5282   INTERNALERROR_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
5283 }
5284 #endif
5285 
5286 #define BASIC_JAVA_CLASSES_DO_PART1(f) \
5287   f(java_lang_Class) \
5288   f(java_lang_String) \
5289   f(java_lang_ref_Reference) \
5290   //end
5291 
5292 #define BASIC_JAVA_CLASSES_DO_PART2(f) \
5293   f(java_lang_System) \
5294   f(java_lang_ClassLoader) \
5295   f(java_lang_Throwable) \
5296   f(java_lang_Thread) \
5297   f(java_lang_Thread_FieldHolder) \
5298   f(java_lang_Thread_Constants) \
5299   f(java_lang_ThreadGroup) \
5300   f(java_lang_VirtualThread) \
5301   f(java_lang_InternalError) \
5302   f(java_lang_AssertionStatusDirectives) \
5303   f(java_lang_ref_SoftReference) \
5304   f(java_lang_invoke_MethodHandle) \
5305   f(java_lang_invoke_DirectMethodHandle) \
5306   f(java_lang_invoke_MemberName) \
5307   f(java_lang_invoke_ResolvedMethodName) \
5308   f(java_lang_invoke_LambdaForm) \
5309   f(java_lang_invoke_MethodType) \
5310   f(java_lang_invoke_CallSite) \
5311   f(java_lang_invoke_ConstantCallSite) \
5312   f(java_lang_invoke_MethodHandleNatives_CallSiteContext) \
5313   f(java_security_AccessControlContext) \
5314   f(java_lang_reflect_AccessibleObject) \
5315   f(java_lang_reflect_Method) \
5316   f(java_lang_reflect_Constructor) \
5317   f(java_lang_reflect_Field) \
5318   f(java_lang_reflect_RecordComponent) \
5319   f(reflect_ConstantPool) \
5320   f(java_lang_reflect_Parameter) \
5321   f(java_lang_Module) \
5322   f(java_lang_StackTraceElement) \
5323   f(java_lang_ClassFrameInfo) \
5324   f(java_lang_StackFrameInfo) \
5325   f(java_lang_LiveStackFrameInfo) \
5326   f(jdk_internal_vm_ContinuationScope) \
5327   f(jdk_internal_vm_Continuation) \
5328   f(jdk_internal_vm_StackChunk) \
5329   f(java_util_concurrent_locks_AbstractOwnableSynchronizer) \
5330   f(jdk_internal_foreign_abi_NativeEntryPoint) \
5331   f(jdk_internal_foreign_abi_ABIDescriptor) \
5332   f(jdk_internal_foreign_abi_VMStorage) \
5333   f(jdk_internal_foreign_abi_CallConv) \
5334   f(jdk_internal_misc_UnsafeConstants) \
5335   f(java_lang_boxing_object) \
5336   f(vector_VectorPayload) \
5337   //end
5338 
5339 #define BASIC_JAVA_CLASSES_DO(f) \
5340         BASIC_JAVA_CLASSES_DO_PART1(f) \
5341         BASIC_JAVA_CLASSES_DO_PART2(f)
5342 
5343 #define DO_COMPUTE_OFFSETS(k) k::compute_offsets();
5344 
5345 // Compute field offsets of all the classes in this file
5346 void JavaClasses::compute_offsets() {
5347   if (UseSharedSpaces) {
5348     JVMTI_ONLY(assert(JvmtiExport::is_early_phase() && !(JvmtiExport::should_post_class_file_load_hook() &&
5349                                                          JvmtiExport::has_early_class_hook_env()),
5350                       "JavaClasses::compute_offsets() must be called in early JVMTI phase."));
5351     // None of the classes used by the rest of this function can be replaced by
5352     // JVMTI ClassFileLoadHook.
5353     // We are safe to use the archived offsets, which have already been restored
5354     // by JavaClasses::serialize_offsets, without computing the offsets again.
5355     return;
5356   }
5357 
5358   // We have already called the compute_offsets() of the
5359   // BASIC_JAVA_CLASSES_DO_PART1 classes (java_lang_String, java_lang_Class and
5360   // java_lang_ref_Reference) earlier inside vmClasses::resolve_all()
5361   BASIC_JAVA_CLASSES_DO_PART2(DO_COMPUTE_OFFSETS);
5362 }
5363 
5364 #if INCLUDE_CDS
5365 #define DO_SERIALIZE_OFFSETS(k) k::serialize_offsets(soc);
5366 
5367 void JavaClasses::serialize_offsets(SerializeClosure* soc) {
5368   BASIC_JAVA_CLASSES_DO(DO_SERIALIZE_OFFSETS);
5369 }
5370 #endif
5371 
5372 #if INCLUDE_CDS_JAVA_HEAP
5373 bool JavaClasses::is_supported_for_archiving(oop obj) {
5374   Klass* klass = obj->klass();
5375 
5376   if (klass == vmClasses::ClassLoader_klass() ||  // ClassLoader::loader_data is malloc'ed.
5377 #if 0
5378       // The next 3 classes are used to implement java.lang.invoke, and are not used directly in
5379       // regular Java code. The implementation of java.lang.invoke uses generated hidden classes
5380       // (e.g., as referenced by ResolvedMethodName::vmholder) that are not yet supported by CDS.
5381       // So for now we cannot not support these classes for archiving.
5382       //
5383       // These objects typically are not referenced by static fields, but rather by resolved
5384       // constant pool entries, so excluding them shouldn't affect the archiving of static fields.
5385       klass == vmClasses::ResolvedMethodName_klass() ||
5386       klass == vmClasses::MemberName_klass() ||
5387       klass == vmClasses::Context_klass() ||
5388 #endif
5389       // It's problematic to archive Reference objects. One of the reasons is that
5390       // Reference::discovered may pull in unwanted objects (see JDK-8284336)
5391       klass->is_subclass_of(vmClasses::Reference_klass())) {
5392     return false;
5393   }
5394 
5395   return true;
5396 }
5397 #endif
5398 
5399 #ifndef PRODUCT
5400 
5401 // These functions exist to assert the validity of de-serialized offsets in boxing object as a sanity check.
5402 
5403 bool JavaClasses::check_offset(const char *klass_name, int deserialized_offset, const char *field_name,
5404                                const char* field_sig) {
5405   EXCEPTION_MARK;
5406   fieldDescriptor fd;
5407   TempNewSymbol klass_sym = SymbolTable::new_symbol(klass_name);
5408   Klass* k = SystemDictionary::resolve_or_fail(klass_sym, true, CATCH);
5409   InstanceKlass* ik = InstanceKlass::cast(k);
5410   TempNewSymbol f_name = SymbolTable::new_symbol(field_name);
5411   TempNewSymbol f_sig  = SymbolTable::new_symbol(field_sig);
5412   if (!ik->find_local_field(f_name, f_sig, &fd)) {
5413     tty->print_cr("Nonstatic field %s.%s not found", klass_name, field_name);
5414     return false;
5415   }
5416   if (fd.is_static()) {
5417     tty->print_cr("Nonstatic field %s.%s appears to be static", klass_name, field_name);
5418     return false;
5419   }
5420   if (fd.offset() == deserialized_offset ) {
5421     return true;
5422   } else {
5423     tty->print_cr("Offset of nonstatic field %s.%s is deserialized as %d but should really be %d.",
5424                   klass_name, field_name, deserialized_offset, fd.offset());
5425     return false;
5426   }
5427 }
5428 
5429 void JavaClasses::check_offsets() {
5430   bool valid = true;
5431 
5432 #define CHECK_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
5433   valid &= check_offset(klass_name, cpp_klass_name :: _##field_name ## _offset, #field_name, field_sig)
5434 
5435 #define CHECK_LONG_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
5436   valid &= check_offset(klass_name, cpp_klass_name :: _##long_ ## field_name ## _offset, #field_name, field_sig)
5437 
5438   // Boxed primitive objects (java_lang_boxing_object)
5439 
5440   CHECK_OFFSET("java/lang/Boolean",   java_lang_boxing_object, value, "Z");
5441   CHECK_OFFSET("java/lang/Character", java_lang_boxing_object, value, "C");
5442   CHECK_OFFSET("java/lang/Float",     java_lang_boxing_object, value, "F");
5443   CHECK_LONG_OFFSET("java/lang/Double", java_lang_boxing_object, value, "D");
5444   CHECK_OFFSET("java/lang/Byte",      java_lang_boxing_object, value, "B");
5445   CHECK_OFFSET("java/lang/Short",     java_lang_boxing_object, value, "S");
5446   CHECK_OFFSET("java/lang/Integer",   java_lang_boxing_object, value, "I");
5447   CHECK_LONG_OFFSET("java/lang/Long", java_lang_boxing_object, value, "J");
5448 
5449   if (!valid) vm_exit_during_initialization("Field offset verification failed");
5450 }
5451 
5452 #endif // PRODUCT
5453 
5454 int InjectedField::compute_offset() {
5455   InstanceKlass* ik = InstanceKlass::cast(klass());
5456   for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
5457     if (!may_be_java && !fs.field_flags().is_injected()) {
5458       // Only look at injected fields
5459       continue;
5460     }
5461     if (fs.name() == name() && fs.signature() == signature()) {
5462       return fs.offset();
5463     }
5464   }
5465   ResourceMark rm;
5466   tty->print_cr("Invalid layout of %s at %s/%s%s", ik->external_name(), name()->as_C_string(), signature()->as_C_string(), may_be_java ? " (may_be_java)" : "");
5467 #ifndef PRODUCT
5468   ik->print();
5469   tty->print_cr("all fields:");
5470   for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
5471     tty->print_cr("  name: %s, sig: %s, flags: %08x", fs.name()->as_C_string(), fs.signature()->as_C_string(), fs.access_flags().as_int());
5472   }
5473 #endif //PRODUCT
5474   vm_exit_during_initialization("Invalid layout of well-known class: use -Xlog:class+load=info to see the origin of the problem class");
5475   return -1;
5476 }
5477 
5478 void javaClasses_init() {
5479   JavaClasses::compute_offsets();
5480   JavaClasses::check_offsets();
5481   FilteredFieldsMap::initialize();  // must be done after computing offsets.
5482 }