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