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