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