1 /*
   2  * Copyright (c) 1997, 2024, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "cds/archiveBuilder.hpp"
  27 #include "cds/archiveHeapLoader.hpp"
  28 #include "cds/cdsConfig.hpp"
  29 #include "cds/heapShared.hpp"
  30 #include "cds/metaspaceShared.hpp"
  31 #include "classfile/altHashing.hpp"
  32 #include "classfile/classLoaderData.inline.hpp"
  33 #include "classfile/javaClasses.inline.hpp"
  34 #include "classfile/javaClassesImpl.hpp"
  35 #include "classfile/javaThreadStatus.hpp"
  36 #include "classfile/moduleEntry.hpp"
  37 #include "classfile/stringTable.hpp"
  38 #include "classfile/symbolTable.hpp"
  39 #include "classfile/systemDictionary.hpp"
  40 #include "classfile/vmClasses.hpp"
  41 #include "classfile/vmSymbols.hpp"
  42 #include "code/debugInfo.hpp"
  43 #include "code/dependencyContext.hpp"
  44 #include "code/pcDesc.hpp"
  45 #include "gc/shared/collectedHeap.inline.hpp"
  46 #include "interpreter/interpreter.hpp"
  47 #include "interpreter/linkResolver.hpp"
  48 #include "jvm.h"
  49 #include "logging/log.hpp"
  50 #include "logging/logStream.hpp"
  51 #include "memory/oopFactory.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "memory/universe.hpp"
  54 #include "oops/fieldInfo.hpp"
  55 #include "oops/fieldStreams.inline.hpp"


  56 #include "oops/instanceKlass.inline.hpp"
  57 #include "oops/instanceMirrorKlass.hpp"
  58 #include "oops/klass.hpp"
  59 #include "oops/klass.inline.hpp"
  60 #include "oops/method.inline.hpp"
  61 #include "oops/objArrayKlass.hpp"
  62 #include "oops/objArrayOop.inline.hpp"
  63 #include "oops/oopCast.inline.hpp"
  64 #include "oops/oop.inline.hpp"
  65 #include "oops/symbol.hpp"
  66 #include "oops/recordComponent.hpp"
  67 #include "oops/typeArrayOop.inline.hpp"
  68 #include "prims/jvmtiExport.hpp"
  69 #include "prims/methodHandles.hpp"
  70 #include "prims/resolvedMethodTable.hpp"
  71 #include "runtime/continuationEntry.inline.hpp"
  72 #include "runtime/continuationJavaClasses.inline.hpp"
  73 #include "runtime/fieldDescriptor.inline.hpp"
  74 #include "runtime/frame.inline.hpp"
  75 #include "runtime/handles.inline.hpp"
  76 #include "runtime/handshake.hpp"
  77 #include "runtime/init.hpp"
  78 #include "runtime/interfaceSupport.inline.hpp"
  79 #include "runtime/java.hpp"
  80 #include "runtime/javaCalls.hpp"
  81 #include "runtime/javaThread.hpp"
  82 #include "runtime/jniHandles.inline.hpp"
  83 #include "runtime/reflectionUtils.hpp"
  84 #include "runtime/safepoint.hpp"
  85 #include "runtime/safepointVerifiers.hpp"
  86 #include "runtime/threadSMR.hpp"
  87 #include "runtime/vframe.inline.hpp"
  88 #include "runtime/vm_version.hpp"
  89 #include "utilities/align.hpp"
  90 #include "utilities/globalDefinitions.hpp"
  91 #include "utilities/growableArray.hpp"
  92 #include "utilities/preserveException.hpp"
  93 #include "utilities/utf8.hpp"
  94 #if INCLUDE_JVMCI
  95 #include "jvmci/jvmciJavaClasses.hpp"
  96 #endif
  97 
  98 #define DECLARE_INJECTED_FIELD(klass, name, signature, may_be_java)           \
  99   { VM_CLASS_ID(klass), VM_SYMBOL_ENUM_NAME(name##_name), VM_SYMBOL_ENUM_NAME(signature), may_be_java },
 100 
 101 InjectedField JavaClasses::_injected_fields[] = {
 102   ALL_INJECTED_FIELDS(DECLARE_INJECTED_FIELD)
 103 };
 104 
 105 // Register native methods of Object
 106 void java_lang_Object::register_natives(TRAPS) {
 107   InstanceKlass* obj = vmClasses::Object_klass();
 108   Method::register_native(obj, vmSymbols::hashCode_name(),
 109                           vmSymbols::void_int_signature(), (address) &JVM_IHashCode, CHECK);
 110   Method::register_native(obj, vmSymbols::wait_name(),
 111                           vmSymbols::long_void_signature(), (address) &JVM_MonitorWait, CHECK);
 112   Method::register_native(obj, vmSymbols::notify_name(),
 113                           vmSymbols::void_method_signature(), (address) &JVM_MonitorNotify, CHECK);
 114   Method::register_native(obj, vmSymbols::notifyAll_name(),
 115                           vmSymbols::void_method_signature(), (address) &JVM_MonitorNotifyAll, CHECK);
 116   Method::register_native(obj, vmSymbols::clone_name(),
 117                           vmSymbols::void_object_signature(), (address) &JVM_Clone, THREAD);
 118 }
 119 
 120 int JavaClasses::compute_injected_offset(InjectedFieldID id) {
 121   return _injected_fields[(int)id].compute_offset();
 122 }
 123 
 124 InjectedField* JavaClasses::get_injected(Symbol* class_name, int* field_count) {
 125   *field_count = 0;
 126 
 127   vmSymbolID sid = vmSymbols::find_sid(class_name);
 128   if (sid == vmSymbolID::NO_SID) {
 129     // Only well known classes can inject fields
 130     return nullptr;
 131   }
 132 
 133   int count = 0;
 134   int start = -1;
 135 
 136 #define LOOKUP_INJECTED_FIELD(klass, name, signature, may_be_java) \
 137   if (sid == VM_SYMBOL_ENUM_NAME(klass)) {                         \
 138     count++;                                                       \
 139     if (start == -1) {                                             \
 140       start = (int)InjectedFieldID::klass##_##name##_enum;         \
 141     }                                                              \
 142   }
 143   ALL_INJECTED_FIELDS(LOOKUP_INJECTED_FIELD);
 144 #undef LOOKUP_INJECTED_FIELD
 145 
 146   if (start != -1) {
 147     *field_count = count;
 148     return _injected_fields + start;
 149   }
 150   return nullptr;
 151 }
 152 
 153 
 154 // Helpful routine for computing field offsets at run time rather than hardcoding them
 155 // Finds local fields only, including static fields.  Static field offsets are from the
 156 // beginning of the mirror.
 157 void JavaClasses::compute_offset(int &dest_offset,
 158                                  InstanceKlass* ik, Symbol* name_symbol, Symbol* signature_symbol,
 159                                  bool is_static) {
 160   fieldDescriptor fd;
 161   if (ik == nullptr) {
 162     ResourceMark rm;
 163     log_error(class)("Mismatch JDK version for field: %s type: %s", name_symbol->as_C_string(), signature_symbol->as_C_string());
 164     vm_exit_during_initialization("Invalid layout of well-known class");
 165   }
 166 
 167   if (!ik->find_local_field(name_symbol, signature_symbol, &fd) || fd.is_static() != is_static) {
 168     ResourceMark rm;
 169     log_error(class)("Invalid layout of %s field: %s type: %s", ik->external_name(),
 170                      name_symbol->as_C_string(), signature_symbol->as_C_string());
 171 #ifndef PRODUCT
 172     // Prints all fields and offsets
 173     Log(class) lt;
 174     LogStream ls(lt.error());
 175     ik->print_on(&ls);
 176 #endif //PRODUCT
 177     vm_exit_during_initialization("Invalid layout of well-known class: use -Xlog:class+load=info to see the origin of the problem class");
 178   }
 179   dest_offset = fd.offset();
 180 }
 181 
 182 // Overloading to pass name as a string.
 183 void JavaClasses::compute_offset(int& dest_offset, InstanceKlass* ik,
 184                                  const char* name_string, Symbol* signature_symbol,
 185                                  bool is_static) {
 186   TempNewSymbol name = SymbolTable::probe(name_string, (int)strlen(name_string));
 187   if (name == nullptr) {
 188     ResourceMark rm;
 189     log_error(class)("Name %s should be in the SymbolTable since its class is loaded", name_string);
 190     vm_exit_during_initialization("Invalid layout of well-known class", ik->external_name());
 191   }
 192   compute_offset(dest_offset, ik, name, signature_symbol, is_static);
 193 }
 194 
 195 // java_lang_String
 196 
 197 int java_lang_String::_value_offset;
 198 int java_lang_String::_hash_offset;
 199 int java_lang_String::_hashIsZero_offset;
 200 int java_lang_String::_coder_offset;
 201 int java_lang_String::_flags_offset;
 202 
 203 bool java_lang_String::_initialized;
 204 
 205 
 206 bool java_lang_String::test_and_set_flag(oop java_string, uint8_t flag_mask) {
 207   uint8_t* addr = flags_addr(java_string);
 208   uint8_t value = Atomic::load(addr);
 209   while ((value & flag_mask) == 0) {
 210     uint8_t old_value = value;
 211     value |= flag_mask;
 212     value = Atomic::cmpxchg(addr, old_value, value);
 213     if (value == old_value) return false; // Flag bit changed from 0 to 1.
 214   }
 215   return true;                  // Flag bit is already 1.
 216 }
 217 
 218 #define STRING_FIELDS_DO(macro) \
 219   macro(_value_offset, k, vmSymbols::value_name(), byte_array_signature, false); \
 220   macro(_hash_offset,  k, "hash",                  int_signature,        false); \
 221   macro(_hashIsZero_offset, k, "hashIsZero",       bool_signature,       false); \
 222   macro(_coder_offset, k, "coder",                 byte_signature,       false);
 223 
 224 void java_lang_String::compute_offsets() {
 225   if (_initialized) {
 226     return;
 227   }
 228 
 229   InstanceKlass* k = vmClasses::String_klass();
 230   STRING_FIELDS_DO(FIELD_COMPUTE_OFFSET);
 231   STRING_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
 232 
 233   _initialized = true;
 234 }
 235 
 236 #if INCLUDE_CDS
 237 void java_lang_String::serialize_offsets(SerializeClosure* f) {
 238   STRING_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
 239   STRING_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
 240   f->do_bool(&_initialized);
 241 }
 242 #endif
 243 
 244 class CompactStringsFixup : public FieldClosure {
 245 private:
 246   bool _value;
 247 
 248 public:
 249   CompactStringsFixup(bool value) : _value(value) {}
 250 
 251   void do_field(fieldDescriptor* fd) {
 252     if (fd->name() == vmSymbols::compact_strings_name()) {
 253       oop mirror = fd->field_holder()->java_mirror();
 254       assert(fd->field_holder() == vmClasses::String_klass(), "Should be String");
 255       assert(mirror != nullptr, "String must have mirror already");
 256       mirror->bool_field_put(fd->offset(), _value);
 257     }
 258   }
 259 };
 260 
 261 void java_lang_String::set_compact_strings(bool value) {
 262   CompactStringsFixup fix(value);
 263   vmClasses::String_klass()->do_local_static_fields(&fix);
 264 }
 265 
 266 Handle java_lang_String::basic_create(int length, bool is_latin1, TRAPS) {
 267   assert(_initialized, "Must be initialized");
 268   assert(CompactStrings || !is_latin1, "Must be UTF16 without CompactStrings");
 269 
 270   // Create the String object first, so there's a chance that the String
 271   // and the char array it points to end up in the same cache line.
 272   oop obj;
 273   obj = vmClasses::String_klass()->allocate_instance(CHECK_NH);
 274 
 275   // Create the char array.  The String object must be handlized here
 276   // because GC can happen as a result of the allocation attempt.
 277   Handle h_obj(THREAD, obj);
 278   int arr_length = is_latin1 ? length : length << 1; // 2 bytes per UTF16.
 279   typeArrayOop buffer = oopFactory::new_byteArray(arr_length, CHECK_NH);;
 280 
 281   // Point the String at the char array
 282   obj = h_obj();
 283   set_value(obj, buffer);
 284   // No need to zero the offset, allocation zero'ed the entire String object
 285   set_coder(obj, is_latin1 ? CODER_LATIN1 : CODER_UTF16);
 286   return h_obj;
 287 }
 288 
 289 Handle java_lang_String::create_from_unicode(const jchar* unicode, int length, TRAPS) {
 290   bool is_latin1 = CompactStrings && UNICODE::is_latin1(unicode, length);
 291   Handle h_obj = basic_create(length, is_latin1, CHECK_NH);
 292   typeArrayOop buffer = value(h_obj());
 293   assert(TypeArrayKlass::cast(buffer->klass())->element_type() == T_BYTE, "only byte[]");
 294   if (is_latin1) {
 295     for (int index = 0; index < length; index++) {
 296       buffer->byte_at_put(index, (jbyte)unicode[index]);
 297     }
 298   } else {
 299     for (int index = 0; index < length; index++) {
 300       buffer->char_at_put(index, unicode[index]);
 301     }
 302   }
 303 
 304 #ifdef ASSERT
 305   {
 306     ResourceMark rm;
 307     char* expected = UNICODE::as_utf8(unicode, length);
 308     char* actual = as_utf8_string(h_obj());
 309     if (strcmp(expected, actual) != 0) {
 310       fatal("Unicode conversion failure: %s --> %s", expected, actual);
 311     }
 312   }
 313 #endif
 314 
 315   return h_obj;
 316 }
 317 
 318 oop java_lang_String::create_oop_from_unicode(const jchar* unicode, int length, TRAPS) {
 319   Handle h_obj = create_from_unicode(unicode, length, CHECK_NULL);
 320   return h_obj();
 321 }
 322 
 323 Handle java_lang_String::create_from_str(const char* utf8_str, TRAPS) {
 324   if (utf8_str == nullptr) {
 325     return Handle();
 326   }
 327   bool has_multibyte, is_latin1;
 328   int length = UTF8::unicode_length(utf8_str, is_latin1, has_multibyte);
 329   if (!CompactStrings) {
 330     has_multibyte = true;
 331     is_latin1 = false;
 332   }
 333 
 334   Handle h_obj = basic_create(length, is_latin1, CHECK_NH);
 335   if (length > 0) {
 336     if (!has_multibyte) {
 337       const jbyte* src = reinterpret_cast<const jbyte*>(utf8_str);
 338       ArrayAccess<>::arraycopy_from_native(src, value(h_obj()), typeArrayOopDesc::element_offset<jbyte>(0), length);
 339     } else if (is_latin1) {
 340       UTF8::convert_to_unicode(utf8_str, value(h_obj())->byte_at_addr(0), length);
 341     } else {
 342       UTF8::convert_to_unicode(utf8_str, value(h_obj())->char_at_addr(0), length);
 343     }
 344   }
 345 
 346 #ifdef ASSERT
 347   // This check is too strict when the input string is not a valid UTF8.
 348   // For example, it may be created with arbitrary content via jni_NewStringUTF.
 349   if (UTF8::is_legal_utf8((const unsigned char*)utf8_str, (int)strlen(utf8_str), false)) {
 350     ResourceMark rm;
 351     const char* expected = utf8_str;
 352     char* actual = as_utf8_string(h_obj());
 353     if (strcmp(expected, actual) != 0) {
 354       fatal("String conversion failure: %s --> %s", expected, actual);
 355     }
 356   }
 357 #endif
 358 
 359   return h_obj;
 360 }
 361 
 362 oop java_lang_String::create_oop_from_str(const char* utf8_str, TRAPS) {
 363   Handle h_obj = create_from_str(utf8_str, CHECK_NULL);
 364   return h_obj();
 365 }
 366 
 367 Handle java_lang_String::create_from_symbol(Symbol* symbol, TRAPS) {
 368   const char* utf8_str = (char*)symbol->bytes();
 369   int utf8_len = symbol->utf8_length();
 370 
 371   bool has_multibyte, is_latin1;
 372   int length = UTF8::unicode_length(utf8_str, utf8_len, is_latin1, has_multibyte);
 373   if (!CompactStrings) {
 374     has_multibyte = true;
 375     is_latin1 = false;
 376   }
 377 
 378   Handle h_obj = basic_create(length, is_latin1, CHECK_NH);
 379   if (length > 0) {
 380     if (!has_multibyte) {
 381       const jbyte* src = reinterpret_cast<const jbyte*>(utf8_str);
 382       ArrayAccess<>::arraycopy_from_native(src, value(h_obj()), typeArrayOopDesc::element_offset<jbyte>(0), length);
 383     } else if (is_latin1) {
 384       UTF8::convert_to_unicode(utf8_str, value(h_obj())->byte_at_addr(0), length);
 385     } else {
 386       UTF8::convert_to_unicode(utf8_str, value(h_obj())->char_at_addr(0), length);
 387     }
 388   }
 389 
 390 #ifdef ASSERT
 391   {
 392     ResourceMark rm;
 393     const char* expected = symbol->as_utf8();
 394     char* actual = as_utf8_string(h_obj());
 395     if (strncmp(expected, actual, utf8_len) != 0) {
 396       fatal("Symbol conversion failure: %s --> %s", expected, actual);
 397     }
 398   }
 399 #endif
 400 
 401   return h_obj;
 402 }
 403 
 404 // Converts a C string to a Java String based on current encoding
 405 Handle java_lang_String::create_from_platform_dependent_str(const char* str, TRAPS) {
 406   assert(str != nullptr, "bad arguments");
 407 
 408   typedef jstring (JNICALL *to_java_string_fn_t)(JNIEnv*, const char *);
 409   static to_java_string_fn_t _to_java_string_fn = nullptr;
 410 
 411   if (_to_java_string_fn == nullptr) {
 412     void *lib_handle = os::native_java_library();
 413     _to_java_string_fn = CAST_TO_FN_PTR(to_java_string_fn_t, os::dll_lookup(lib_handle, "JNU_NewStringPlatform"));
 414 #if defined(_WIN32) && !defined(_WIN64)
 415     if (_to_java_string_fn == nullptr) {
 416       // On 32 bit Windows, also try __stdcall decorated name
 417       _to_java_string_fn = CAST_TO_FN_PTR(to_java_string_fn_t, os::dll_lookup(lib_handle, "_JNU_NewStringPlatform@8"));
 418     }
 419 #endif
 420     if (_to_java_string_fn == nullptr) {
 421       fatal("JNU_NewStringPlatform missing");
 422     }
 423   }
 424 
 425   jstring js = nullptr;
 426   {
 427     JavaThread* thread = THREAD;
 428     HandleMark hm(thread);
 429     ThreadToNativeFromVM ttn(thread);
 430     js = (_to_java_string_fn)(thread->jni_environment(), str);
 431   }
 432 
 433   Handle native_platform_string(THREAD, JNIHandles::resolve(js));
 434   JNIHandles::destroy_local(js);  // destroy local JNIHandle.
 435   return native_platform_string;
 436 }
 437 
 438 // Converts a Java String to a native C string that can be used for
 439 // native OS calls.
 440 char* java_lang_String::as_platform_dependent_str(Handle java_string, TRAPS) {
 441   typedef char* (*to_platform_string_fn_t)(JNIEnv*, jstring, bool*);
 442   static to_platform_string_fn_t _to_platform_string_fn = nullptr;
 443 
 444   if (_to_platform_string_fn == nullptr) {
 445     void *lib_handle = os::native_java_library();
 446     _to_platform_string_fn = CAST_TO_FN_PTR(to_platform_string_fn_t, os::dll_lookup(lib_handle, "GetStringPlatformChars"));
 447     if (_to_platform_string_fn == nullptr) {
 448       fatal("GetStringPlatformChars missing");
 449     }
 450   }
 451 
 452   char *native_platform_string;
 453   jstring js;
 454   { JavaThread* thread = THREAD;
 455     js = (jstring) JNIHandles::make_local(thread, java_string());
 456     HandleMark hm(thread);
 457     ThreadToNativeFromVM ttn(thread);
 458     JNIEnv *env = thread->jni_environment();
 459     bool is_copy;
 460     native_platform_string = (_to_platform_string_fn)(env, js, &is_copy);
 461     assert(is_copy == JNI_TRUE, "is_copy value changed");
 462   }
 463 
 464   // Uses a store barrier and therefore needs to be in vm state
 465   JNIHandles::destroy_local(js);
 466 
 467   return native_platform_string;
 468 }
 469 
 470 Handle java_lang_String::externalize_classname(Symbol* java_name, TRAPS) {
 471   ResourceMark rm(THREAD);
 472   return create_from_str(java_name->as_klass_external_name(), THREAD);
 473 }
 474 
 475 jchar* java_lang_String::as_unicode_string(oop java_string, int& length, TRAPS) {
 476   jchar* result = as_unicode_string_or_null(java_string, length);
 477   if (result == nullptr) {
 478     THROW_MSG_0(vmSymbols::java_lang_OutOfMemoryError(), "could not allocate Unicode string");
 479   }
 480   return result;
 481 }
 482 
 483 jchar* java_lang_String::as_unicode_string_or_null(oop java_string, int& length) {
 484   typeArrayOop value  = java_lang_String::value(java_string);
 485                length = java_lang_String::length(java_string, value);
 486   bool      is_latin1 = java_lang_String::is_latin1(java_string);
 487 
 488   jchar* result = NEW_RESOURCE_ARRAY_RETURN_NULL(jchar, length);
 489   if (result != nullptr) {
 490     if (!is_latin1) {
 491       for (int index = 0; index < length; index++) {
 492         result[index] = value->char_at(index);
 493       }
 494     } else {
 495       for (int index = 0; index < length; index++) {
 496         result[index] = ((jchar) value->byte_at(index)) & 0xff;
 497       }
 498     }
 499   }
 500   return result;
 501 }
 502 
 503 inline unsigned int java_lang_String::hash_code_impl(oop java_string, bool update) {
 504   // The hash and hashIsZero fields are subject to a benign data race,
 505   // making it crucial to ensure that any observable result of the
 506   // calculation in this method stays correct under any possible read of
 507   // these fields. Necessary restrictions to allow this to be correct
 508   // without explicit memory fences or similar concurrency primitives is
 509   // that we can ever only write to one of these two fields for a given
 510   // String instance, and that the computation is idempotent and derived
 511   // from immutable state
 512   assert(_initialized && (_hash_offset > 0) && (_hashIsZero_offset > 0), "Must be initialized");
 513   if (java_lang_String::hash_is_set(java_string)) {
 514     return java_string->int_field(_hash_offset);
 515   }
 516 
 517   typeArrayOop value = java_lang_String::value(java_string);
 518   int         length = java_lang_String::length(java_string, value);
 519   bool     is_latin1 = java_lang_String::is_latin1(java_string);
 520 
 521   unsigned int hash = 0;
 522   if (length > 0) {
 523     if (is_latin1) {
 524       hash = java_lang_String::hash_code(value->byte_at_addr(0), length);
 525     } else {
 526       hash = java_lang_String::hash_code(value->char_at_addr(0), length);
 527     }
 528   }
 529 
 530   if (update) {
 531     if (hash != 0) {
 532       java_string->int_field_put(_hash_offset, hash);
 533     } else {
 534       java_string->bool_field_put(_hashIsZero_offset, true);
 535     }
 536   }
 537   return hash;
 538 }
 539 
 540 unsigned int java_lang_String::hash_code(oop java_string) {
 541   return hash_code_impl(java_string, /*update=*/true);
 542 }
 543 
 544 unsigned int java_lang_String::hash_code_noupdate(oop java_string) {
 545   return hash_code_impl(java_string, /*update=*/false);
 546 }
 547 
 548 
 549 char* java_lang_String::as_quoted_ascii(oop java_string) {
 550   typeArrayOop value  = java_lang_String::value(java_string);
 551   int          length = java_lang_String::length(java_string, value);
 552   bool      is_latin1 = java_lang_String::is_latin1(java_string);
 553 
 554   if (length == 0) return nullptr;
 555 
 556   char* result;
 557   int result_length;
 558   if (!is_latin1) {
 559     jchar* base = value->char_at_addr(0);
 560     result_length = UNICODE::quoted_ascii_length(base, length) + 1;
 561     result = NEW_RESOURCE_ARRAY(char, result_length);
 562     UNICODE::as_quoted_ascii(base, length, result, result_length);
 563   } else {
 564     jbyte* base = value->byte_at_addr(0);
 565     result_length = UNICODE::quoted_ascii_length(base, length) + 1;
 566     result = NEW_RESOURCE_ARRAY(char, result_length);
 567     UNICODE::as_quoted_ascii(base, length, result, result_length);
 568   }
 569   assert(result_length >= length + 1, "must not be shorter");
 570   assert(result_length == (int)strlen(result) + 1, "must match");
 571   return result;
 572 }
 573 
 574 Symbol* java_lang_String::as_symbol(oop java_string) {
 575   typeArrayOop value  = java_lang_String::value(java_string);
 576   int          length = java_lang_String::length(java_string, value);
 577   bool      is_latin1 = java_lang_String::is_latin1(java_string);
 578   if (!is_latin1) {
 579     jchar* base = (length == 0) ? nullptr : value->char_at_addr(0);
 580     Symbol* sym = SymbolTable::new_symbol(base, length);
 581     return sym;
 582   } else {
 583     ResourceMark rm;
 584     jbyte* position = (length == 0) ? nullptr : value->byte_at_addr(0);
 585     const char* base = UNICODE::as_utf8(position, length);
 586     Symbol* sym = SymbolTable::new_symbol(base, length);
 587     return sym;
 588   }
 589 }
 590 
 591 Symbol* java_lang_String::as_symbol_or_null(oop java_string) {
 592   typeArrayOop value  = java_lang_String::value(java_string);
 593   int          length = java_lang_String::length(java_string, value);
 594   bool      is_latin1 = java_lang_String::is_latin1(java_string);
 595   if (!is_latin1) {
 596     jchar* base = (length == 0) ? nullptr : value->char_at_addr(0);
 597     return SymbolTable::probe_unicode(base, length);
 598   } else {
 599     ResourceMark rm;
 600     jbyte* position = (length == 0) ? nullptr : value->byte_at_addr(0);
 601     const char* base = UNICODE::as_utf8(position, length);
 602     return SymbolTable::probe(base, length);
 603   }
 604 }
 605 
 606 int java_lang_String::utf8_length(oop java_string, typeArrayOop value) {
 607   assert(value_equals(value, java_lang_String::value(java_string)),
 608          "value must be same as java_lang_String::value(java_string)");
 609   int length = java_lang_String::length(java_string, value);
 610   if (length == 0) {
 611     return 0;
 612   }
 613   if (!java_lang_String::is_latin1(java_string)) {
 614     return UNICODE::utf8_length(value->char_at_addr(0), length);
 615   } else {
 616     return UNICODE::utf8_length(value->byte_at_addr(0), length);
 617   }
 618 }
 619 
 620 int java_lang_String::utf8_length(oop java_string) {
 621   typeArrayOop value = java_lang_String::value(java_string);
 622   return utf8_length(java_string, value);
 623 }
 624 
 625 char* java_lang_String::as_utf8_string(oop java_string) {
 626   int length;
 627   return as_utf8_string(java_string, length);
 628 }
 629 
 630 char* java_lang_String::as_utf8_string(oop java_string, int& length) {
 631   typeArrayOop value = java_lang_String::value(java_string);
 632   length             = java_lang_String::length(java_string, value);
 633   bool     is_latin1 = java_lang_String::is_latin1(java_string);
 634   if (!is_latin1) {
 635     jchar* position = (length == 0) ? nullptr : value->char_at_addr(0);
 636     return UNICODE::as_utf8(position, length);
 637   } else {
 638     jbyte* position = (length == 0) ? nullptr : value->byte_at_addr(0);
 639     return UNICODE::as_utf8(position, length);
 640   }
 641 }
 642 
 643 // Uses a provided buffer if it's sufficiently large, otherwise allocates
 644 // a resource array to fit
 645 char* java_lang_String::as_utf8_string_full(oop java_string, char* buf, int buflen, int& utf8_len) {
 646   typeArrayOop value = java_lang_String::value(java_string);
 647   int            len = java_lang_String::length(java_string, value);
 648   bool     is_latin1 = java_lang_String::is_latin1(java_string);
 649   if (!is_latin1) {
 650     jchar *position = (len == 0) ? nullptr : value->char_at_addr(0);
 651     utf8_len = UNICODE::utf8_length(position, len);
 652     if (utf8_len >= buflen) {
 653       buf = NEW_RESOURCE_ARRAY(char, utf8_len + 1);
 654     }
 655     return UNICODE::as_utf8(position, len, buf, utf8_len + 1);
 656   } else {
 657     jbyte *position = (len == 0) ? nullptr : value->byte_at_addr(0);
 658     utf8_len = UNICODE::utf8_length(position, len);
 659     if (utf8_len >= buflen) {
 660       buf = NEW_RESOURCE_ARRAY(char, utf8_len + 1);
 661     }
 662     return UNICODE::as_utf8(position, len, buf, utf8_len + 1);
 663   }
 664 }
 665 
 666 char* java_lang_String::as_utf8_string(oop java_string, typeArrayOop value, char* buf, int buflen) {
 667   assert(value_equals(value, java_lang_String::value(java_string)),
 668          "value must be same as java_lang_String::value(java_string)");
 669   int     length = java_lang_String::length(java_string, value);
 670   bool is_latin1 = java_lang_String::is_latin1(java_string);
 671   if (!is_latin1) {
 672     jchar* position = (length == 0) ? nullptr : value->char_at_addr(0);
 673     return UNICODE::as_utf8(position, length, buf, buflen);
 674   } else {
 675     jbyte* position = (length == 0) ? nullptr : value->byte_at_addr(0);
 676     return UNICODE::as_utf8(position, length, buf, buflen);
 677   }
 678 }
 679 
 680 char* java_lang_String::as_utf8_string(oop java_string, char* buf, int buflen) {
 681   typeArrayOop value = java_lang_String::value(java_string);
 682   return as_utf8_string(java_string, value, buf, buflen);
 683 }
 684 
 685 char* java_lang_String::as_utf8_string(oop java_string, int start, int len) {
 686   typeArrayOop value  = java_lang_String::value(java_string);
 687   bool      is_latin1 = java_lang_String::is_latin1(java_string);
 688   assert(start + len <= java_lang_String::length(java_string), "just checking");
 689   if (!is_latin1) {
 690     jchar* position = value->char_at_addr(start);
 691     return UNICODE::as_utf8(position, len);
 692   } else {
 693     jbyte* position = value->byte_at_addr(start);
 694     return UNICODE::as_utf8(position, len);
 695   }
 696 }
 697 
 698 char* java_lang_String::as_utf8_string(oop java_string, typeArrayOop value, int start, int len, char* buf, int buflen) {
 699   assert(value_equals(value, java_lang_String::value(java_string)),
 700          "value must be same as java_lang_String::value(java_string)");
 701   assert(start + len <= java_lang_String::length(java_string), "just checking");
 702   bool is_latin1 = java_lang_String::is_latin1(java_string);
 703   if (!is_latin1) {
 704     jchar* position = value->char_at_addr(start);
 705     return UNICODE::as_utf8(position, len, buf, buflen);
 706   } else {
 707     jbyte* position = value->byte_at_addr(start);
 708     return UNICODE::as_utf8(position, len, buf, buflen);
 709   }
 710 }
 711 
 712 bool java_lang_String::equals(oop java_string, const jchar* chars, int len) {
 713   assert(java_string->klass() == vmClasses::String_klass(),
 714          "must be java_string");
 715   typeArrayOop value = java_lang_String::value_no_keepalive(java_string);
 716   int length = java_lang_String::length(java_string, value);
 717   if (length != len) {
 718     return false;
 719   }
 720   bool is_latin1 = java_lang_String::is_latin1(java_string);
 721   if (!is_latin1) {
 722     for (int i = 0; i < len; i++) {
 723       if (value->char_at(i) != chars[i]) {
 724         return false;
 725       }
 726     }
 727   } else {
 728     for (int i = 0; i < len; i++) {
 729       if ((((jchar) value->byte_at(i)) & 0xff) != chars[i]) {
 730         return false;
 731       }
 732     }
 733   }
 734   return true;
 735 }
 736 
 737 bool java_lang_String::equals(oop str1, oop str2) {
 738   assert(str1->klass() == vmClasses::String_klass(),
 739          "must be java String");
 740   assert(str2->klass() == vmClasses::String_klass(),
 741          "must be java String");
 742   typeArrayOop value1    = java_lang_String::value_no_keepalive(str1);
 743   bool         is_latin1 = java_lang_String::is_latin1(str1);
 744   typeArrayOop value2    = java_lang_String::value_no_keepalive(str2);
 745   bool         is_latin2 = java_lang_String::is_latin1(str2);
 746 
 747   if (is_latin1 != is_latin2) {
 748     // Strings with different coders are never equal.
 749     return false;
 750   }
 751   return value_equals(value1, value2);
 752 }
 753 
 754 void java_lang_String::print(oop java_string, outputStream* st) {
 755   assert(java_string->klass() == vmClasses::String_klass(), "must be java_string");
 756   typeArrayOop value  = java_lang_String::value_no_keepalive(java_string);
 757 
 758   if (value == nullptr) {
 759     // This can happen if, e.g., printing a String
 760     // object before its initializer has been called
 761     st->print("nullptr");
 762     return;
 763   }
 764 
 765   int length = java_lang_String::length(java_string, value);
 766   bool is_latin1 = java_lang_String::is_latin1(java_string);
 767 
 768   st->print("\"");
 769   for (int index = 0; index < length; index++) {
 770     jchar c = (!is_latin1) ?  value->char_at(index) :
 771                              ((jchar) value->byte_at(index)) & 0xff;
 772     if (c < ' ') {
 773       st->print("\\x%02X", c); // print control characters e.g. \x0A
 774     } else {
 775       st->print("%c", c);
 776     }
 777   }
 778   st->print("\"");
 779 }
 780 
 781 // java_lang_Class
 782 
 783 int java_lang_Class::_klass_offset;
 784 int java_lang_Class::_array_klass_offset;
 785 int java_lang_Class::_oop_size_offset;
 786 int java_lang_Class::_static_oop_field_count_offset;
 787 int java_lang_Class::_class_loader_offset;
 788 int java_lang_Class::_module_offset;
 789 int java_lang_Class::_protection_domain_offset;
 790 int java_lang_Class::_component_mirror_offset;

 791 int java_lang_Class::_signers_offset;
 792 int java_lang_Class::_name_offset;
 793 int java_lang_Class::_source_file_offset;
 794 int java_lang_Class::_classData_offset;
 795 int java_lang_Class::_classRedefinedCount_offset;
 796 
 797 bool java_lang_Class::_offsets_computed = false;
 798 GrowableArray<Klass*>* java_lang_Class::_fixup_mirror_list = nullptr;
 799 GrowableArray<Klass*>* java_lang_Class::_fixup_module_field_list = nullptr;
 800 
 801 #ifdef ASSERT
 802 inline static void assert_valid_static_string_field(fieldDescriptor* fd) {
 803   assert(fd->has_initial_value(), "caller should have checked this");
 804   assert(fd->field_type() == T_OBJECT, "caller should have checked this");
 805   assert(fd->signature() == vmSymbols::string_signature(), "just checking");
 806 }
 807 #endif
 808 
 809 static void initialize_static_string_field(fieldDescriptor* fd, Handle mirror, TRAPS) {
 810   DEBUG_ONLY(assert_valid_static_string_field(fd);)
 811   oop string = fd->string_initial_value(CHECK);
 812   mirror()->obj_field_put(fd->offset(), string);
 813 }
 814 
 815 static void initialize_static_primitive_field(fieldDescriptor* fd, Handle mirror) {
 816   assert(fd->has_initial_value(), "caller should have checked this");
 817   BasicType t = fd->field_type();
 818   switch (t) {
 819   case T_BYTE:
 820     mirror()->byte_field_put(fd->offset(), (jbyte)(fd->int_initial_value()));
 821     break;
 822   case T_BOOLEAN:
 823     mirror()->bool_field_put(fd->offset(), (jboolean)(fd->int_initial_value()));
 824     break;
 825   case T_CHAR:
 826     mirror()->char_field_put(fd->offset(), (jchar)(fd->int_initial_value()));
 827     break;
 828   case T_SHORT:
 829     mirror()->short_field_put(fd->offset(), (jshort)(fd->int_initial_value()));
 830     break;
 831   case T_INT:
 832     mirror()->int_field_put(fd->offset(), fd->int_initial_value());
 833     break;
 834   case T_FLOAT:
 835     mirror()->float_field_put(fd->offset(), fd->float_initial_value());
 836     break;
 837   case T_DOUBLE:
 838     mirror()->double_field_put(fd->offset(), fd->double_initial_value());
 839     break;
 840   case T_LONG:
 841     mirror()->long_field_put(fd->offset(), fd->long_initial_value());
 842     break;
 843   default:
 844     // Illegal ConstantValue attribute in class file should have been
 845     // caught during classfile parsing.
 846     ShouldNotReachHere();
 847   }
 848 }
 849 
 850 static void initialize_static_field(fieldDescriptor* fd, Handle mirror, TRAPS) {
 851   assert(mirror.not_null() && fd->is_static(), "just checking");
 852   if (fd->has_initial_value()) {
 853     if (fd->field_type() != T_OBJECT) {
 854       initialize_static_primitive_field(fd, mirror);
 855     } else {
 856       initialize_static_string_field(fd, mirror, CHECK);
 857     }
 858   }
 859 }
 860 
 861 void java_lang_Class::fixup_mirror(Klass* k, TRAPS) {
 862   assert(InstanceMirrorKlass::offset_of_static_fields() != 0, "must have been computed already");
 863 
 864   // If the offset was read from the shared archive, it was fixed up already
 865   if (!k->is_shared()) {
 866     if (k->is_instance_klass()) {
 867       // During bootstrap, java.lang.Class wasn't loaded so static field
 868       // offsets were computed without the size added it.  Go back and
 869       // update all the static field offsets to included the size.
 870 
 871       // Unfortunately, the FieldInfo stream is encoded with UNSIGNED5 which doesn't allow
 872       // content updates. So the FieldInfo stream has to be decompressed into a temporary array,
 873       // static fields offsets are updated in this array before reencoding everything into
 874       // a new UNSIGNED5 stream, and substitute it to the old FieldInfo stream.
 875 
 876       int java_fields;
 877       int injected_fields;
 878       InstanceKlass* ik = InstanceKlass::cast(k);
 879       GrowableArray<FieldInfo>* fields =
 880         FieldInfoStream::create_FieldInfoArray(ik->fieldinfo_stream(),
 881                                                &java_fields, &injected_fields);
 882       for (int i = 0; i < fields->length(); i++) {
 883         FieldInfo* fi = fields->adr_at(i);
 884         if (fi->access_flags().is_static()) {
 885           fi->set_offset(fi->offset() + InstanceMirrorKlass::offset_of_static_fields());
 886         }
 887       }
 888       Array<u1>* old_stream = ik->fieldinfo_stream();
 889       assert(fields->length() == (java_fields + injected_fields), "Must be");
 890       Array<u1>* new_fis = FieldInfoStream::create_FieldInfoStream(fields, java_fields, injected_fields, k->class_loader_data(), CHECK);
 891       ik->set_fieldinfo_stream(new_fis);
 892       MetadataFactory::free_array<u1>(k->class_loader_data(), old_stream);
 893     }
 894   }
 895 
 896   if (k->is_shared() && k->has_archived_mirror_index()) {
 897     if (ArchiveHeapLoader::is_in_use()) {
 898       bool present = restore_archived_mirror(k, Handle(), Handle(), Handle(), CHECK);
 899       assert(present, "Missing archived mirror for %s", k->external_name());
 900       return;
 901     } else {
 902       k->clear_java_mirror_handle();
 903       k->clear_archived_mirror_index();
 904     }
 905   }
 906   create_mirror(k, Handle(), Handle(), Handle(), Handle(), CHECK);
 907 }
 908 
 909 void java_lang_Class::initialize_mirror_fields(Klass* k,
 910                                                Handle mirror,
 911                                                Handle protection_domain,
 912                                                Handle classData,
 913                                                TRAPS) {
 914   // Set protection domain also
 915   set_protection_domain(mirror(), protection_domain());
 916 
 917   // Initialize static fields
 918   InstanceKlass::cast(k)->do_local_static_fields(&initialize_static_field, mirror, CHECK);
 919 
 920  // Set classData
 921   set_class_data(mirror(), classData());
 922 }
 923 
 924 // Set the java.lang.Module module field in the java_lang_Class mirror
 925 void java_lang_Class::set_mirror_module_field(JavaThread* current, Klass* k, Handle mirror, Handle module) {
 926   if (module.is_null()) {
 927     // During startup, the module may be null only if java.base has not been defined yet.
 928     // Put the class on the fixup_module_list to patch later when the java.lang.Module
 929     // for java.base is known. But note that since we captured the null module another
 930     // thread may have completed that initialization.
 931 
 932     bool javabase_was_defined = false;
 933     {
 934       MutexLocker m1(current, Module_lock);
 935       // Keep list of classes needing java.base module fixup
 936       if (!ModuleEntryTable::javabase_defined()) {
 937         assert(k->java_mirror() != nullptr, "Class's mirror is null");
 938         k->class_loader_data()->inc_keep_alive();
 939         assert(fixup_module_field_list() != nullptr, "fixup_module_field_list not initialized");
 940         fixup_module_field_list()->push(k);
 941       } else {
 942         javabase_was_defined = true;
 943       }
 944     }
 945 
 946     // If java.base was already defined then patch this particular class with java.base.
 947     if (javabase_was_defined) {
 948       ModuleEntry *javabase_entry = ModuleEntryTable::javabase_moduleEntry();
 949       assert(javabase_entry != nullptr && javabase_entry->module() != nullptr,
 950              "Setting class module field, " JAVA_BASE_NAME " should be defined");
 951       Handle javabase_handle(current, javabase_entry->module());
 952       set_module(mirror(), javabase_handle());
 953     }
 954   } else {
 955     assert(Universe::is_module_initialized() ||
 956            (ModuleEntryTable::javabase_defined() &&
 957             (module() == ModuleEntryTable::javabase_moduleEntry()->module())),
 958            "Incorrect java.lang.Module specification while creating mirror");
 959     set_module(mirror(), module());
 960   }
 961 }
 962 
 963 // Statically allocate fixup lists because they always get created.
 964 void java_lang_Class::allocate_fixup_lists() {
 965   GrowableArray<Klass*>* mirror_list =
 966     new (mtClass) GrowableArray<Klass*>(40, mtClass);
 967   set_fixup_mirror_list(mirror_list);
 968 
 969   GrowableArray<Klass*>* module_list =
 970     new (mtModule) GrowableArray<Klass*>(500, mtModule);
 971   set_fixup_module_field_list(module_list);
 972 }
 973 
 974 void java_lang_Class::allocate_mirror(Klass* k, bool is_scratch, Handle protection_domain, Handle classData,
 975                                       Handle& mirror, Handle& comp_mirror, TRAPS) {
 976   // Allocate mirror (java.lang.Class instance)
 977   oop mirror_oop = InstanceMirrorKlass::cast(vmClasses::Class_klass())->allocate_instance(k, CHECK);
 978   mirror = Handle(THREAD, mirror_oop);
 979 
 980   // Setup indirection from mirror->klass
 981   set_klass(mirror(), k);
 982 
 983   InstanceMirrorKlass* mk = InstanceMirrorKlass::cast(mirror->klass());
 984   assert(oop_size(mirror()) == mk->instance_size(k), "should have been set");
 985 
 986   set_static_oop_field_count(mirror(), mk->compute_static_oop_field_count(mirror()));
 987 
 988   // It might also have a component mirror.  This mirror must already exist.
 989   if (k->is_array_klass()) {
 990     if (k->is_typeArray_klass()) {








 991       BasicType type = TypeArrayKlass::cast(k)->element_type();
 992       if (is_scratch) {
 993         comp_mirror = Handle(THREAD, HeapShared::scratch_java_mirror(type));
 994       } else {
 995         comp_mirror = Handle(THREAD, Universe::java_mirror(type));
 996       }
 997     } else {
 998       assert(k->is_objArray_klass(), "Must be");
 999       Klass* element_klass = ObjArrayKlass::cast(k)->element_klass();
1000       assert(element_klass != nullptr, "Must have an element klass");





1001       if (is_scratch) {
1002         comp_mirror = Handle(THREAD, HeapShared::scratch_java_mirror(element_klass));
1003       } else {
1004         comp_mirror = Handle(THREAD, element_klass->java_mirror());
1005       }
1006     }
1007     assert(comp_mirror() != nullptr, "must have a mirror");
1008 
1009     // Two-way link between the array klass and its component mirror:
1010     // (array_klass) k -> mirror -> component_mirror -> array_klass -> k
1011     set_component_mirror(mirror(), comp_mirror());
1012     // See below for ordering dependencies between field array_klass in component mirror
1013     // and java_mirror in this klass.
1014   } else {
1015     assert(k->is_instance_klass(), "Must be");
1016 
1017     initialize_mirror_fields(k, mirror, protection_domain, classData, THREAD);
1018     if (HAS_PENDING_EXCEPTION) {
1019       // If any of the fields throws an exception like OOM remove the klass field
1020       // from the mirror so GC doesn't follow it after the klass has been deallocated.
1021       // This mirror looks like a primitive type, which logically it is because it
1022       // it represents no class.
1023       set_klass(mirror(), nullptr);
1024       return;
1025     }
1026   }
1027 }
1028 
1029 void java_lang_Class::create_mirror(Klass* k, Handle class_loader,
1030                                     Handle module, Handle protection_domain,
1031                                     Handle classData, TRAPS) {
1032   assert(k != nullptr, "Use create_basic_type_mirror for primitive types");
1033   assert(k->java_mirror() == nullptr, "should only assign mirror once");
1034 
1035   // Use this moment of initialization to cache modifier_flags also,
1036   // to support Class.getModifiers().  Instance classes recalculate
1037   // the cached flags after the class file is parsed, but before the
1038   // class is put into the system dictionary.
1039   int computed_modifiers = k->compute_modifier_flags();
1040   k->set_modifier_flags(computed_modifiers);
1041   // Class_klass has to be loaded because it is used to allocate
1042   // the mirror.
1043   if (vmClasses::Class_klass_loaded()) {
1044     Handle mirror;
1045     Handle comp_mirror;
1046 
1047     allocate_mirror(k, /*is_scratch=*/false, protection_domain, classData, mirror, comp_mirror, CHECK);
1048 
1049     // set the classLoader field in the java_lang_Class instance
1050     assert(class_loader() == k->class_loader(), "should be same");
1051     set_class_loader(mirror(), class_loader());
1052 
1053     // Setup indirection from klass->mirror
1054     // after any exceptions can happen during allocations.
1055     k->set_java_mirror(mirror);
1056 
1057     // Set the module field in the java_lang_Class instance.  This must be done
1058     // after the mirror is set.
1059     set_mirror_module_field(THREAD, k, mirror, module);
1060 
1061     if (comp_mirror() != nullptr) {
1062       // Set after k->java_mirror() is published, because compiled code running
1063       // concurrently doesn't expect a k to have a null java_mirror.
1064       release_set_array_klass(comp_mirror(), k);
1065     }

1066     if (CDSConfig::is_dumping_heap()) {
1067       create_scratch_mirror(k, CHECK);
1068     }
1069   } else {
1070     assert(fixup_mirror_list() != nullptr, "fixup_mirror_list not initialized");
1071     fixup_mirror_list()->push(k);
1072   }
1073 }
1074 
1075 #if INCLUDE_CDS_JAVA_HEAP
1076 // The "scratch mirror" stores the states of the mirror object that can be
1077 // decided at dump time (such as the initial values of the static fields, the
1078 // component mirror, etc). At runtime, more information is added to it by
1079 // java_lang_Class::restore_archived_mirror().
1080 //
1081 // Essentially, /*dumptime*/create_scratch_mirror() + /*runtime*/restore_archived_mirror()
1082 // produces the same result as /*runtime*/create_mirror().
1083 //
1084 // Note: we archive the "scratch mirror" instead of k->java_mirror(), because the
1085 // latter may contain dumptime-specific information that cannot be archived
1086 // (e.g., ClassLoaderData*, or static fields that are modified by Java code execution).
1087 void java_lang_Class::create_scratch_mirror(Klass* k, TRAPS) {
1088   if (k->class_loader() != nullptr &&
1089       k->class_loader() != SystemDictionary::java_platform_loader() &&
1090       k->class_loader() != SystemDictionary::java_system_loader()) {





1091     // We only archive the mirrors of classes loaded by the built-in loaders
1092     return;
1093   }
1094 
1095   Handle protection_domain, classData; // set to null. Will be reinitialized at runtime
1096   Handle mirror;
1097   Handle comp_mirror;
1098   allocate_mirror(k, /*is_scratch=*/true, protection_domain, classData, mirror, comp_mirror, CHECK);
1099 
1100   if (comp_mirror() != nullptr) {
1101     release_set_array_klass(comp_mirror(), k);
1102   }
1103 
1104   HeapShared::set_scratch_java_mirror(k, mirror());
1105 }
1106 
1107 // Returns true if the mirror is updated, false if no archived mirror
1108 // data is present. After the archived mirror object is restored, the
1109 // shared klass' _has_raw_archived_mirror flag is cleared.
1110 bool java_lang_Class::restore_archived_mirror(Klass *k,
1111                                               Handle class_loader, Handle module,
1112                                               Handle protection_domain, TRAPS) {
1113   // Postpone restoring archived mirror until java.lang.Class is loaded. Please
1114   // see more details in vmClasses::resolve_all().
1115   if (!vmClasses::Class_klass_loaded()) {
1116     assert(fixup_mirror_list() != nullptr, "fixup_mirror_list not initialized");
1117     fixup_mirror_list()->push(k);
1118     return true;
1119   }
1120 
1121   oop m = k->archived_java_mirror();
1122   assert(m != nullptr, "must have stored non-null archived mirror");
1123 
1124   // Sanity: clear it now to prevent re-initialization if any of the following fails
1125   k->clear_archived_mirror_index();
1126 
1127   // mirror is archived, restore
1128   log_debug(cds, mirror)("Archived mirror is: " PTR_FORMAT, p2i(m));
1129   assert(as_Klass(m) == k, "must be");
1130   Handle mirror(THREAD, m);
1131 
1132   if (!k->is_array_klass()) {
1133     // - local static final fields with initial values were initialized at dump time
1134 
1135     if (protection_domain.not_null()) {
1136       set_protection_domain(mirror(), protection_domain());
1137     }
1138   }
1139 
1140   assert(class_loader() == k->class_loader(), "should be same");
1141   if (class_loader.not_null()) {
1142     set_class_loader(mirror(), class_loader());
1143   }
1144 
1145   k->set_java_mirror(mirror);
1146 
1147   set_mirror_module_field(THREAD, k, mirror, module);
1148 
1149   if (log_is_enabled(Trace, cds, heap, mirror)) {
1150     ResourceMark rm(THREAD);
1151     log_trace(cds, heap, mirror)(
1152         "Restored %s archived mirror " PTR_FORMAT, k->external_name(), p2i(mirror()));
1153   }
1154 
1155   return true;
1156 }
1157 #endif // INCLUDE_CDS_JAVA_HEAP
1158 
1159 void java_lang_Class::fixup_module_field(Klass* k, Handle module) {
1160   assert(_module_offset != 0, "must have been computed already");
1161   set_module(k->java_mirror(), module());
1162 }
1163 
1164 void java_lang_Class::set_oop_size(HeapWord* java_class, size_t size) {
1165   assert(_oop_size_offset != 0, "must be set");
1166   assert(size > 0, "Oop size must be greater than zero, not " SIZE_FORMAT, size);
1167   assert(size <= INT_MAX, "Lossy conversion: " SIZE_FORMAT, size);
1168   *(int*)(((char*)java_class) + _oop_size_offset) = (int)size;
1169 }
1170 
1171 int  java_lang_Class::static_oop_field_count(oop java_class) {
1172   assert(_static_oop_field_count_offset != 0, "must be set");
1173   return java_class->int_field(_static_oop_field_count_offset);
1174 }
1175 
1176 void java_lang_Class::set_static_oop_field_count(oop java_class, int size) {
1177   assert(_static_oop_field_count_offset != 0, "must be set");
1178   java_class->int_field_put(_static_oop_field_count_offset, size);
1179 }
1180 
1181 oop java_lang_Class::protection_domain(oop java_class) {
1182   assert(_protection_domain_offset != 0, "must be set");
1183   return java_class->obj_field(_protection_domain_offset);
1184 }
1185 void java_lang_Class::set_protection_domain(oop java_class, oop pd) {
1186   assert(_protection_domain_offset != 0, "must be set");
1187   java_class->obj_field_put(_protection_domain_offset, pd);
1188 }
1189 
1190 void java_lang_Class::set_component_mirror(oop java_class, oop comp_mirror) {
1191   assert(_component_mirror_offset != 0, "must be set");
1192     java_class->obj_field_put(_component_mirror_offset, comp_mirror);
1193   }
1194 oop java_lang_Class::component_mirror(oop java_class) {
1195   assert(_component_mirror_offset != 0, "must be set");
1196   return java_class->obj_field(_component_mirror_offset);
1197 }
1198 
1199 objArrayOop java_lang_Class::signers(oop java_class) {
1200   assert(_signers_offset != 0, "must be set");
1201   return (objArrayOop)java_class->obj_field(_signers_offset);
1202 }
1203 void java_lang_Class::set_signers(oop java_class, objArrayOop signers) {
1204   assert(_signers_offset != 0, "must be set");
1205   java_class->obj_field_put(_signers_offset, signers);
1206 }
1207 
1208 oop java_lang_Class::class_data(oop java_class) {
1209   assert(_classData_offset != 0, "must be set");
1210   return java_class->obj_field(_classData_offset);
1211 }
1212 void java_lang_Class::set_class_data(oop java_class, oop class_data) {
1213   assert(_classData_offset != 0, "must be set");
1214   java_class->obj_field_put(_classData_offset, class_data);
1215 }
1216 
1217 void java_lang_Class::set_class_loader(oop java_class, oop loader) {
1218   assert(_class_loader_offset != 0, "offsets should have been initialized");
1219   java_class->obj_field_put(_class_loader_offset, loader);
1220 }
1221 
1222 oop java_lang_Class::class_loader(oop java_class) {
1223   assert(_class_loader_offset != 0, "must be set");
1224   return java_class->obj_field(_class_loader_offset);
1225 }
1226 
1227 oop java_lang_Class::module(oop java_class) {
1228   assert(_module_offset != 0, "must be set");
1229   return java_class->obj_field(_module_offset);
1230 }
1231 
1232 void java_lang_Class::set_module(oop java_class, oop module) {
1233   assert(_module_offset != 0, "must be set");
1234   java_class->obj_field_put(_module_offset, module);
1235 }
1236 
1237 oop java_lang_Class::name(Handle java_class, TRAPS) {
1238   assert(_name_offset != 0, "must be set");
1239   oop o = java_class->obj_field(_name_offset);
1240   if (o == nullptr) {
1241     o = StringTable::intern(as_external_name(java_class()), THREAD);
1242     java_class->obj_field_put(_name_offset, o);
1243   }
1244   return o;
1245 }
1246 
1247 oop java_lang_Class::source_file(oop java_class) {
1248   assert(_source_file_offset != 0, "must be set");
1249   return java_class->obj_field(_source_file_offset);
1250 }
1251 
1252 void java_lang_Class::set_source_file(oop java_class, oop source_file) {
1253   assert(_source_file_offset != 0, "must be set");
1254   java_class->obj_field_put(_source_file_offset, source_file);
1255 }
1256 
1257 oop java_lang_Class::create_basic_type_mirror(const char* basic_type_name, BasicType type, TRAPS) {
1258   // This should be improved by adding a field at the Java level or by
1259   // introducing a new VM klass (see comment in ClassFileParser)
1260   oop java_class = InstanceMirrorKlass::cast(vmClasses::Class_klass())->allocate_instance(nullptr, CHECK_NULL);
1261   if (type != T_VOID) {
1262     Klass* aklass = Universe::typeArrayKlassObj(type);
1263     assert(aklass != nullptr, "correct bootstrap");
1264     release_set_array_klass(java_class, aklass);
1265   }
1266 #ifdef ASSERT
1267   InstanceMirrorKlass* mk = InstanceMirrorKlass::cast(vmClasses::Class_klass());
1268   assert(static_oop_field_count(java_class) == 0, "should have been zeroed by allocation");
1269 #endif
1270   return java_class;
1271 }
1272 
1273 void java_lang_Class::set_klass(oop java_class, Klass* klass) {
1274   assert(is_instance(java_class), "must be a Class object");
1275   java_class->metadata_field_put(_klass_offset, klass);
1276 }
1277 
1278 
1279 void java_lang_Class::print_signature(oop java_class, outputStream* st) {
1280   assert(is_instance(java_class), "must be a Class object");
1281   Symbol* name = nullptr;
1282   bool is_instance = false;
1283   if (is_primitive(java_class)) {
1284     name = vmSymbols::type_signature(primitive_type(java_class));
1285   } else {
1286     Klass* k = as_Klass(java_class);
1287     is_instance = k->is_instance_klass();
1288     name = k->name();
1289   }
1290   if (name == nullptr) {
1291     st->print("<null>");
1292     return;
1293   }
1294   if (is_instance)  st->print("L");


1295   st->write((char*) name->base(), (int) name->utf8_length());
1296   if (is_instance)  st->print(";");
1297 }
1298 
1299 Symbol* java_lang_Class::as_signature(oop java_class, bool intern_if_not_found) {
1300   assert(is_instance(java_class), "must be a Class object");
1301   Symbol* name;
1302   if (is_primitive(java_class)) {
1303     name = vmSymbols::type_signature(primitive_type(java_class));
1304     // Because this can create a new symbol, the caller has to decrement
1305     // the refcount, so make adjustment here and below for symbols returned
1306     // that are not created or incremented due to a successful lookup.
1307     name->increment_refcount();
1308   } else {
1309     Klass* k = as_Klass(java_class);
1310     if (!k->is_instance_klass()) {
1311       name = k->name();
1312       name->increment_refcount();
1313     } else {
1314       ResourceMark rm;
1315       const char* sigstr = k->signature_name();
1316       int         siglen = (int) strlen(sigstr);
1317       if (!intern_if_not_found) {
1318         name = SymbolTable::probe(sigstr, siglen);
1319       } else {
1320         name = SymbolTable::new_symbol(sigstr, siglen);
1321       }
1322     }
1323   }
1324   return name;
1325 }
1326 
1327 // Returns the Java name for this Java mirror (Resource allocated)
1328 // See Klass::external_name().
1329 // For primitive type Java mirrors, its type name is returned.
1330 const char* java_lang_Class::as_external_name(oop java_class) {
1331   assert(is_instance(java_class), "must be a Class object");
1332   const char* name = nullptr;
1333   if (is_primitive(java_class)) {
1334     name = type2name(primitive_type(java_class));
1335   } else {
1336     name = as_Klass(java_class)->external_name();
1337   }
1338   if (name == nullptr) {
1339     name = "<null>";
1340   }
1341   return name;
1342 }
1343 
1344 Klass* java_lang_Class::array_klass_acquire(oop java_class) {
1345   Klass* k = ((Klass*)java_class->metadata_field_acquire(_array_klass_offset));
1346   assert(k == nullptr || (k->is_klass() && k->is_array_klass()), "should be array klass");
1347   return k;
1348 }
1349 
1350 
1351 void java_lang_Class::release_set_array_klass(oop java_class, Klass* klass) {
1352   assert(klass->is_klass() && klass->is_array_klass(), "should be array klass");




1353   java_class->release_metadata_field_put(_array_klass_offset, klass);
1354 }
1355 
1356 
1357 BasicType java_lang_Class::primitive_type(oop java_class) {
1358   assert(is_primitive(java_class), "just checking");
1359   Klass* ak = ((Klass*)java_class->metadata_field(_array_klass_offset));
1360   BasicType type = T_VOID;
1361   if (ak != nullptr) {
1362     // Note: create_basic_type_mirror above initializes ak to a non-null value.
1363     type = ArrayKlass::cast(ak)->element_type();
1364   } else {
1365     assert(java_class == Universe::void_mirror(), "only valid non-array primitive");
1366   }
1367 #ifdef ASSERT
1368   if (CDSConfig::is_dumping_heap()) {
1369     oop mirror = Universe::java_mirror(type);
1370     oop scratch_mirror = HeapShared::scratch_java_mirror(type);
1371     assert(java_class == mirror || java_class == scratch_mirror, "must be consistent");
1372   } else {
1373     assert(Universe::java_mirror(type) == java_class, "must be consistent");
1374   }
1375 #endif
1376   return type;
1377 }
1378 
1379 BasicType java_lang_Class::as_BasicType(oop java_class, Klass** reference_klass) {
1380   assert(is_instance(java_class), "must be a Class object");
1381   if (is_primitive(java_class)) {
1382     if (reference_klass != nullptr)
1383       (*reference_klass) = nullptr;
1384     return primitive_type(java_class);
1385   } else {
1386     if (reference_klass != nullptr)
1387       (*reference_klass) = as_Klass(java_class);
1388     return T_OBJECT;
1389   }
1390 }
1391 
1392 
1393 oop java_lang_Class::primitive_mirror(BasicType t) {
1394   oop mirror = Universe::java_mirror(t);
1395   assert(mirror != nullptr && mirror->is_a(vmClasses::Class_klass()), "must be a Class");
1396   assert(is_primitive(mirror), "must be primitive");
1397   return mirror;
1398 }
1399 
1400 #define CLASS_FIELDS_DO(macro) \
1401   macro(_classRedefinedCount_offset, k, "classRedefinedCount", int_signature,         false); \
1402   macro(_class_loader_offset,        k, "classLoader",         classloader_signature, false); \
1403   macro(_component_mirror_offset,    k, "componentType",       class_signature,       false); \
1404   macro(_module_offset,              k, "module",              module_signature,      false); \
1405   macro(_name_offset,                k, "name",                string_signature,      false); \
1406   macro(_classData_offset,           k, "classData",           object_signature,      false);
1407 
1408 void java_lang_Class::compute_offsets() {
1409   if (_offsets_computed) {
1410     return;
1411   }
1412 
1413   _offsets_computed = true;
1414 
1415   InstanceKlass* k = vmClasses::Class_klass();
1416   CLASS_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1417 
1418   CLASS_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
1419 }
1420 
1421 #if INCLUDE_CDS
1422 void java_lang_Class::serialize_offsets(SerializeClosure* f) {
1423   f->do_bool(&_offsets_computed);
1424 
1425   CLASS_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
1426 
1427   CLASS_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
1428 }
1429 #endif
1430 
1431 int java_lang_Class::classRedefinedCount(oop the_class_mirror) {
1432   assert(_classRedefinedCount_offset != 0, "offsets should have been initialized");
1433   return the_class_mirror->int_field(_classRedefinedCount_offset);
1434 }
1435 
1436 void java_lang_Class::set_classRedefinedCount(oop the_class_mirror, int value) {
1437   assert(_classRedefinedCount_offset != 0, "offsets should have been initialized");
1438   the_class_mirror->int_field_put(_classRedefinedCount_offset, value);
1439 }
1440 
1441 
1442 // Note: JDK1.1 and before had a privateInfo_offset field which was used for the
1443 //       platform thread structure, and a eetop offset which was used for thread
1444 //       local storage (and unused by the HotSpot VM). In JDK1.2 the two structures
1445 //       merged, so in the HotSpot VM we just use the eetop field for the thread
1446 //       instead of the privateInfo_offset.
1447 //
1448 // Note: The stackSize field is only present starting in 1.4.
1449 
1450 int java_lang_Thread_FieldHolder::_group_offset;
1451 int java_lang_Thread_FieldHolder::_priority_offset;
1452 int java_lang_Thread_FieldHolder::_stackSize_offset;
1453 int java_lang_Thread_FieldHolder::_daemon_offset;
1454 int java_lang_Thread_FieldHolder::_thread_status_offset;
1455 
1456 #define THREAD_FIELD_HOLDER_FIELDS_DO(macro) \
1457   macro(_group_offset,         k, vmSymbols::group_name(),    threadgroup_signature, false); \
1458   macro(_priority_offset,      k, vmSymbols::priority_name(), int_signature,         false); \
1459   macro(_stackSize_offset,     k, "stackSize",                long_signature,        false); \
1460   macro(_daemon_offset,        k, vmSymbols::daemon_name(),   bool_signature,        false); \
1461   macro(_thread_status_offset, k, "threadStatus",             int_signature,         false)
1462 
1463 void java_lang_Thread_FieldHolder::compute_offsets() {
1464   assert(_group_offset == 0, "offsets should be initialized only once");
1465 
1466   InstanceKlass* k = vmClasses::Thread_FieldHolder_klass();
1467   THREAD_FIELD_HOLDER_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1468 }
1469 
1470 #if INCLUDE_CDS
1471 void java_lang_Thread_FieldHolder::serialize_offsets(SerializeClosure* f) {
1472   THREAD_FIELD_HOLDER_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
1473 }
1474 #endif
1475 
1476 oop java_lang_Thread_FieldHolder::threadGroup(oop holder) {
1477   return holder->obj_field(_group_offset);
1478 }
1479 
1480 ThreadPriority java_lang_Thread_FieldHolder::priority(oop holder) {
1481   return (ThreadPriority)holder->int_field(_priority_offset);
1482 }
1483 
1484 void java_lang_Thread_FieldHolder::set_priority(oop holder, ThreadPriority priority) {
1485   holder->int_field_put(_priority_offset, priority);
1486 }
1487 
1488 jlong java_lang_Thread_FieldHolder::stackSize(oop holder) {
1489   return holder->long_field(_stackSize_offset);
1490 }
1491 
1492 bool java_lang_Thread_FieldHolder::is_daemon(oop holder) {
1493   return holder->bool_field(_daemon_offset) != 0;
1494 }
1495 
1496 void java_lang_Thread_FieldHolder::set_daemon(oop holder, bool val) {
1497   assert(val, "daemon status is never turned off");
1498   holder->bool_field_put(_daemon_offset, val);
1499 }
1500 
1501 void java_lang_Thread_FieldHolder::set_thread_status(oop holder, JavaThreadStatus status) {
1502   holder->int_field_put(_thread_status_offset, static_cast<int>(status));
1503 }
1504 
1505 JavaThreadStatus java_lang_Thread_FieldHolder::get_thread_status(oop holder) {
1506   return static_cast<JavaThreadStatus>(holder->int_field(_thread_status_offset));
1507 }
1508 
1509 
1510 int java_lang_Thread_Constants::_static_VTHREAD_GROUP_offset = 0;
1511 
1512 #define THREAD_CONSTANTS_STATIC_FIELDS_DO(macro) \
1513   macro(_static_VTHREAD_GROUP_offset,             k, "VTHREAD_GROUP",             threadgroup_signature, true);
1514 
1515 void java_lang_Thread_Constants::compute_offsets() {
1516   assert(_static_VTHREAD_GROUP_offset == 0, "offsets should be initialized only once");
1517 
1518   InstanceKlass* k = vmClasses::Thread_Constants_klass();
1519   THREAD_CONSTANTS_STATIC_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1520 }
1521 
1522 #if INCLUDE_CDS
1523 void java_lang_Thread_Constants::serialize_offsets(SerializeClosure* f) {
1524   THREAD_CONSTANTS_STATIC_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
1525 }
1526 #endif
1527 
1528 oop java_lang_Thread_Constants::get_VTHREAD_GROUP() {
1529   InstanceKlass* k = vmClasses::Thread_Constants_klass();
1530   oop base = k->static_field_base_raw();
1531   return base->obj_field(_static_VTHREAD_GROUP_offset);
1532 }
1533 
1534 
1535 int java_lang_Thread::_holder_offset;
1536 int java_lang_Thread::_name_offset;
1537 int java_lang_Thread::_contextClassLoader_offset;
1538 int java_lang_Thread::_inheritedAccessControlContext_offset;
1539 int java_lang_Thread::_eetop_offset;
1540 int java_lang_Thread::_jvmti_thread_state_offset;
1541 int java_lang_Thread::_jvmti_VTMS_transition_disable_count_offset;
1542 int java_lang_Thread::_jvmti_is_in_VTMS_transition_offset;
1543 int java_lang_Thread::_interrupted_offset;
1544 int java_lang_Thread::_tid_offset;
1545 int java_lang_Thread::_continuation_offset;
1546 int java_lang_Thread::_park_blocker_offset;
1547 int java_lang_Thread::_scopedValueBindings_offset;
1548 JFR_ONLY(int java_lang_Thread::_jfr_epoch_offset;)
1549 
1550 #define THREAD_FIELDS_DO(macro) \
1551   macro(_holder_offset,        k, "holder", thread_fieldholder_signature, false); \
1552   macro(_name_offset,          k, vmSymbols::name_name(), string_signature, false); \
1553   macro(_contextClassLoader_offset, k, vmSymbols::contextClassLoader_name(), classloader_signature, false); \
1554   macro(_inheritedAccessControlContext_offset, k, vmSymbols::inheritedAccessControlContext_name(), accesscontrolcontext_signature, false); \
1555   macro(_eetop_offset,         k, "eetop", long_signature, false); \
1556   macro(_interrupted_offset,   k, "interrupted", bool_signature, false); \
1557   macro(_tid_offset,           k, "tid", long_signature, false); \
1558   macro(_park_blocker_offset,  k, "parkBlocker", object_signature, false); \
1559   macro(_continuation_offset,  k, "cont", continuation_signature, false); \
1560   macro(_scopedValueBindings_offset, k, "scopedValueBindings", object_signature, false);
1561 
1562 void java_lang_Thread::compute_offsets() {
1563   assert(_holder_offset == 0, "offsets should be initialized only once");
1564 
1565   InstanceKlass* k = vmClasses::Thread_klass();
1566   THREAD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1567   THREAD_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
1568 }
1569 
1570 #if INCLUDE_CDS
1571 void java_lang_Thread::serialize_offsets(SerializeClosure* f) {
1572   THREAD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
1573   THREAD_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
1574 }
1575 #endif
1576 
1577 JavaThread* java_lang_Thread::thread(oop java_thread) {
1578   return reinterpret_cast<JavaThread*>(java_thread->address_field(_eetop_offset));
1579 }
1580 
1581 JavaThread* java_lang_Thread::thread_acquire(oop java_thread) {
1582   return reinterpret_cast<JavaThread*>(java_thread->address_field_acquire(_eetop_offset));
1583 }
1584 
1585 void java_lang_Thread::set_thread(oop java_thread, JavaThread* thread) {
1586   java_thread->address_field_put(_eetop_offset, (address)thread);
1587 }
1588 
1589 void java_lang_Thread::release_set_thread(oop java_thread, JavaThread* thread) {
1590   java_thread->release_address_field_put(_eetop_offset, (address)thread);
1591 }
1592 
1593 JvmtiThreadState* java_lang_Thread::jvmti_thread_state(oop java_thread) {
1594   return (JvmtiThreadState*)java_thread->address_field(_jvmti_thread_state_offset);
1595 }
1596 
1597 void java_lang_Thread::set_jvmti_thread_state(oop java_thread, JvmtiThreadState* state) {
1598   java_thread->address_field_put(_jvmti_thread_state_offset, (address)state);
1599 }
1600 
1601 int java_lang_Thread::VTMS_transition_disable_count(oop java_thread) {
1602   return java_thread->int_field(_jvmti_VTMS_transition_disable_count_offset);
1603 }
1604 
1605 void java_lang_Thread::inc_VTMS_transition_disable_count(oop java_thread) {
1606   assert(JvmtiVTMSTransition_lock->owned_by_self(), "Must be locked");
1607   int val = VTMS_transition_disable_count(java_thread);
1608   java_thread->int_field_put(_jvmti_VTMS_transition_disable_count_offset, val + 1);
1609 }
1610 
1611 void java_lang_Thread::dec_VTMS_transition_disable_count(oop java_thread) {
1612   assert(JvmtiVTMSTransition_lock->owned_by_self(), "Must be locked");
1613   int val = VTMS_transition_disable_count(java_thread);
1614   assert(val > 0, "VTMS_transition_disable_count should never be negative");
1615   java_thread->int_field_put(_jvmti_VTMS_transition_disable_count_offset, val - 1);
1616 }
1617 
1618 bool java_lang_Thread::is_in_VTMS_transition(oop java_thread) {
1619   return java_thread->bool_field_volatile(_jvmti_is_in_VTMS_transition_offset);
1620 }
1621 
1622 void java_lang_Thread::set_is_in_VTMS_transition(oop java_thread, bool val) {
1623   java_thread->bool_field_put_volatile(_jvmti_is_in_VTMS_transition_offset, val);
1624 }
1625 
1626 int java_lang_Thread::is_in_VTMS_transition_offset() {
1627   return _jvmti_is_in_VTMS_transition_offset;
1628 }
1629 
1630 void java_lang_Thread::clear_scopedValueBindings(oop java_thread) {
1631   assert(java_thread != nullptr, "need a java_lang_Thread pointer here");
1632   java_thread->obj_field_put(_scopedValueBindings_offset, nullptr);
1633 }
1634 
1635 oop java_lang_Thread::holder(oop java_thread) {
1636   // Note: may return null if the thread is still attaching
1637   return java_thread->obj_field(_holder_offset);
1638 }
1639 
1640 bool java_lang_Thread::interrupted(oop java_thread) {
1641   // Make sure the caller can safely access oops.
1642   assert(Thread::current()->is_VM_thread() ||
1643          (JavaThread::current()->thread_state() != _thread_blocked &&
1644           JavaThread::current()->thread_state() != _thread_in_native),
1645          "Unsafe access to oop");
1646   return java_thread->bool_field_volatile(_interrupted_offset);
1647 }
1648 
1649 void java_lang_Thread::set_interrupted(oop java_thread, bool val) {
1650   // Make sure the caller can safely access oops.
1651   assert(Thread::current()->is_VM_thread() ||
1652          (JavaThread::current()->thread_state() != _thread_blocked &&
1653           JavaThread::current()->thread_state() != _thread_in_native),
1654          "Unsafe access to oop");
1655   java_thread->bool_field_put_volatile(_interrupted_offset, val);
1656 }
1657 
1658 
1659 oop java_lang_Thread::name(oop java_thread) {
1660   return java_thread->obj_field(_name_offset);
1661 }
1662 
1663 
1664 void java_lang_Thread::set_name(oop java_thread, oop name) {
1665   java_thread->obj_field_put(_name_offset, name);
1666 }
1667 
1668 // Convenience macros for setting and getting Thread fields that
1669 // are actually stored in the FieldHolder object of the thread.
1670 // The FieldHolder can be null whilst a thread is attaching via
1671 // JNI, and when the main thread is attaching.
1672 
1673 // The default value should be the default/zero initialized value
1674 // of the field as it would be in java.lang.Thread.FieldHolder.
1675 #define GET_FIELDHOLDER_FIELD(java_thread, field, default_val)  \
1676   {                                                             \
1677     oop holder = java_lang_Thread::holder(java_thread);         \
1678     if (holder != nullptr)                                      \
1679       return java_lang_Thread_FieldHolder::field(holder);       \
1680     else                                                        \
1681       return default_val;                                       \
1682   }
1683 
1684 // We should never be trying to set a field of an attaching thread.
1685 #define SET_FIELDHOLDER_FIELD(java_thread, field, value)        \
1686   {                                                             \
1687     oop holder = java_lang_Thread::holder(java_thread);         \
1688     assert(holder != nullptr, "Thread not fully initialized");  \
1689     java_lang_Thread_FieldHolder::set_##field(holder, value);   \
1690   }
1691 
1692 
1693 ThreadPriority java_lang_Thread::priority(oop java_thread) {
1694   GET_FIELDHOLDER_FIELD(java_thread, priority, (ThreadPriority)0);
1695 }
1696 
1697 
1698 void java_lang_Thread::set_priority(oop java_thread, ThreadPriority priority) {
1699   SET_FIELDHOLDER_FIELD(java_thread, priority, priority)
1700 }
1701 
1702 
1703 oop java_lang_Thread::threadGroup(oop java_thread) {
1704   GET_FIELDHOLDER_FIELD(java_thread, threadGroup, nullptr);
1705 }
1706 
1707 
1708 bool java_lang_Thread::is_alive(oop java_thread) {
1709   JavaThread* thr = java_lang_Thread::thread(java_thread);
1710   return (thr != nullptr);
1711 }
1712 
1713 
1714 bool java_lang_Thread::is_daemon(oop java_thread) {
1715   GET_FIELDHOLDER_FIELD(java_thread, is_daemon, false);
1716 }
1717 
1718 
1719 void java_lang_Thread::set_daemon(oop java_thread) {
1720   SET_FIELDHOLDER_FIELD(java_thread, daemon, true);
1721 }
1722 
1723 oop java_lang_Thread::context_class_loader(oop java_thread) {
1724   return java_thread->obj_field(_contextClassLoader_offset);
1725 }
1726 
1727 oop java_lang_Thread::inherited_access_control_context(oop java_thread) {
1728   return java_thread->obj_field(_inheritedAccessControlContext_offset);
1729 }
1730 
1731 
1732 jlong java_lang_Thread::stackSize(oop java_thread) {
1733   GET_FIELDHOLDER_FIELD(java_thread, stackSize, 0);
1734 }
1735 
1736 // Write the thread status value to threadStatus field in java.lang.Thread java class.
1737 void java_lang_Thread::set_thread_status(oop java_thread, JavaThreadStatus status) {
1738   SET_FIELDHOLDER_FIELD(java_thread, thread_status, status);
1739 }
1740 
1741 // Read thread status value from threadStatus field in java.lang.Thread java class.
1742 JavaThreadStatus java_lang_Thread::get_thread_status(oop java_thread) {
1743   // Make sure the caller is operating on behalf of the VM or is
1744   // running VM code (state == _thread_in_vm).
1745   assert(Threads_lock->owned_by_self() || Thread::current()->is_VM_thread() ||
1746          JavaThread::current()->thread_state() == _thread_in_vm,
1747          "Java Thread is not running in vm");
1748   GET_FIELDHOLDER_FIELD(java_thread, get_thread_status, JavaThreadStatus::NEW /* not initialized */);
1749 }
1750 
1751 ByteSize java_lang_Thread::thread_id_offset() {
1752   return in_ByteSize(_tid_offset);
1753 }
1754 
1755 oop java_lang_Thread::park_blocker(oop java_thread) {
1756   return java_thread->obj_field(_park_blocker_offset);
1757 }
1758 
1759 oop java_lang_Thread::async_get_stack_trace(oop java_thread, TRAPS) {
1760   ThreadsListHandle tlh(JavaThread::current());
1761   JavaThread* thread;
1762   bool is_virtual = java_lang_VirtualThread::is_instance(java_thread);
1763   if (is_virtual) {
1764     oop carrier_thread = java_lang_VirtualThread::carrier_thread(java_thread);
1765     if (carrier_thread == nullptr) {
1766       return nullptr;
1767     }
1768     thread = java_lang_Thread::thread(carrier_thread);
1769   } else {
1770     thread = java_lang_Thread::thread(java_thread);
1771   }
1772   if (thread == nullptr) {
1773     return nullptr;
1774   }
1775 
1776   class GetStackTraceClosure : public HandshakeClosure {
1777   public:
1778     const Handle _java_thread;
1779     int _depth;
1780     bool _retry_handshake;
1781     GrowableArray<Method*>* _methods;
1782     GrowableArray<int>*     _bcis;
1783 
1784     GetStackTraceClosure(Handle java_thread) :
1785         HandshakeClosure("GetStackTraceClosure"), _java_thread(java_thread), _depth(0), _retry_handshake(false),
1786         _methods(nullptr), _bcis(nullptr) {
1787     }
1788     ~GetStackTraceClosure() {
1789       delete _methods;
1790       delete _bcis;
1791     }
1792 
1793     bool read_reset_retry() {
1794       bool ret = _retry_handshake;
1795       // If we re-execute the handshake this method need to return false
1796       // when the handshake cannot be performed. (E.g. thread terminating)
1797       _retry_handshake = false;
1798       return ret;
1799     }
1800 
1801     void do_thread(Thread* th) {
1802       if (!Thread::current()->is_Java_thread()) {
1803         _retry_handshake = true;
1804         return;
1805       }
1806 
1807       JavaThread* thread = JavaThread::cast(th);
1808 
1809       if (!thread->has_last_Java_frame()) {
1810         return;
1811       }
1812 
1813       bool carrier = false;
1814       if (java_lang_VirtualThread::is_instance(_java_thread())) {
1815         // if (thread->vthread() != _java_thread()) // We might be inside a System.executeOnCarrierThread
1816         const ContinuationEntry* ce = thread->vthread_continuation();
1817         if (ce == nullptr || ce->cont_oop(thread) != java_lang_VirtualThread::continuation(_java_thread())) {
1818           return; // not mounted
1819         }
1820       } else {
1821         carrier = (thread->vthread_continuation() != nullptr);
1822       }
1823 
1824       const int max_depth = MaxJavaStackTraceDepth;
1825       const bool skip_hidden = !ShowHiddenFrames;
1826 
1827       // Pick minimum length that will cover most cases
1828       int init_length = 64;
1829       _methods = new (mtInternal) GrowableArray<Method*>(init_length, mtInternal);
1830       _bcis = new (mtInternal) GrowableArray<int>(init_length, mtInternal);
1831 
1832       int total_count = 0;
1833       for (vframeStream vfst(thread, false, false, carrier); // we don't process frames as we don't care about oops
1834            !vfst.at_end() && (max_depth == 0 || max_depth != total_count);
1835            vfst.next()) {
1836 
1837         if (skip_hidden && (vfst.method()->is_hidden() ||
1838                             vfst.method()->is_continuation_enter_intrinsic())) {
1839           continue;
1840         }
1841 
1842         _methods->push(vfst.method());
1843         _bcis->push(vfst.bci());
1844         total_count++;
1845       }
1846 
1847       _depth = total_count;
1848     }
1849   };
1850 
1851   // Handshake with target
1852   ResourceMark rm(THREAD);
1853   HandleMark   hm(THREAD);
1854   GetStackTraceClosure gstc(Handle(THREAD, java_thread));
1855   do {
1856    Handshake::execute(&gstc, &tlh, thread);
1857   } while (gstc.read_reset_retry());
1858 
1859   // Stop if no stack trace is found.
1860   if (gstc._depth == 0) {
1861     return nullptr;
1862   }
1863 
1864   // Convert to StackTraceElement array
1865   InstanceKlass* k = vmClasses::StackTraceElement_klass();
1866   assert(k != nullptr, "must be loaded in 1.4+");
1867   if (k->should_be_initialized()) {
1868     k->initialize(CHECK_NULL);
1869   }
1870   objArrayHandle trace = oopFactory::new_objArray_handle(k, gstc._depth, CHECK_NULL);
1871 
1872   for (int i = 0; i < gstc._depth; i++) {
1873     methodHandle method(THREAD, gstc._methods->at(i));
1874     oop element = java_lang_StackTraceElement::create(method,
1875                                                       gstc._bcis->at(i),
1876                                                       CHECK_NULL);
1877     trace->obj_at_put(i, element);
1878   }
1879 
1880   return trace();
1881 }
1882 
1883 const char* java_lang_Thread::thread_status_name(oop java_thread) {
1884   JavaThreadStatus status = get_thread_status(java_thread);
1885   switch (status) {
1886     case JavaThreadStatus::NEW                      : return "NEW";
1887     case JavaThreadStatus::RUNNABLE                 : return "RUNNABLE";
1888     case JavaThreadStatus::SLEEPING                 : return "TIMED_WAITING (sleeping)";
1889     case JavaThreadStatus::IN_OBJECT_WAIT           : return "WAITING (on object monitor)";
1890     case JavaThreadStatus::IN_OBJECT_WAIT_TIMED     : return "TIMED_WAITING (on object monitor)";
1891     case JavaThreadStatus::PARKED                   : return "WAITING (parking)";
1892     case JavaThreadStatus::PARKED_TIMED             : return "TIMED_WAITING (parking)";
1893     case JavaThreadStatus::BLOCKED_ON_MONITOR_ENTER : return "BLOCKED (on object monitor)";
1894     case JavaThreadStatus::TERMINATED               : return "TERMINATED";
1895     default                       : return "UNKNOWN";
1896   };
1897 }
1898 int java_lang_ThreadGroup::_parent_offset;
1899 int java_lang_ThreadGroup::_name_offset;
1900 int java_lang_ThreadGroup::_maxPriority_offset;
1901 int java_lang_ThreadGroup::_daemon_offset;
1902 
1903 oop  java_lang_ThreadGroup::parent(oop java_thread_group) {
1904   assert(oopDesc::is_oop(java_thread_group), "thread group must be oop");
1905   return java_thread_group->obj_field(_parent_offset);
1906 }
1907 
1908 // ("name as oop" accessor is not necessary)
1909 
1910 const char* java_lang_ThreadGroup::name(oop java_thread_group) {
1911   oop name = java_thread_group->obj_field(_name_offset);
1912   // ThreadGroup.name can be null
1913   if (name != nullptr) {
1914     return java_lang_String::as_utf8_string(name);
1915   }
1916   return nullptr;
1917 }
1918 
1919 ThreadPriority java_lang_ThreadGroup::maxPriority(oop java_thread_group) {
1920   assert(oopDesc::is_oop(java_thread_group), "thread group must be oop");
1921   return (ThreadPriority) java_thread_group->int_field(_maxPriority_offset);
1922 }
1923 
1924 bool java_lang_ThreadGroup::is_daemon(oop java_thread_group) {
1925   assert(oopDesc::is_oop(java_thread_group), "thread group must be oop");
1926   return java_thread_group->bool_field(_daemon_offset) != 0;
1927 }
1928 
1929 #define THREADGROUP_FIELDS_DO(macro) \
1930   macro(_parent_offset,      k, vmSymbols::parent_name(),      threadgroup_signature,         false); \
1931   macro(_name_offset,        k, vmSymbols::name_name(),        string_signature,              false); \
1932   macro(_maxPriority_offset, k, vmSymbols::maxPriority_name(), int_signature,                 false); \
1933   macro(_daemon_offset,      k, vmSymbols::daemon_name(),      bool_signature,                false);
1934 
1935 void java_lang_ThreadGroup::compute_offsets() {
1936   assert(_parent_offset == 0, "offsets should be initialized only once");
1937 
1938   InstanceKlass* k = vmClasses::ThreadGroup_klass();
1939   THREADGROUP_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1940 }
1941 
1942 #if INCLUDE_CDS
1943 void java_lang_ThreadGroup::serialize_offsets(SerializeClosure* f) {
1944   THREADGROUP_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
1945 }
1946 #endif
1947 
1948 
1949 // java_lang_VirtualThread
1950 
1951 int java_lang_VirtualThread::static_vthread_scope_offset;
1952 int java_lang_VirtualThread::_carrierThread_offset;
1953 int java_lang_VirtualThread::_continuation_offset;
1954 int java_lang_VirtualThread::_state_offset;
1955 
1956 #define VTHREAD_FIELDS_DO(macro) \
1957   macro(static_vthread_scope_offset,       k, "VTHREAD_SCOPE",      continuationscope_signature, true);  \
1958   macro(_carrierThread_offset,             k, "carrierThread",      thread_signature,            false); \
1959   macro(_continuation_offset,              k, "cont",               continuation_signature,      false); \
1960   macro(_state_offset,                     k, "state",              int_signature,               false)
1961 
1962 
1963 void java_lang_VirtualThread::compute_offsets() {
1964   InstanceKlass* k = vmClasses::VirtualThread_klass();
1965   VTHREAD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
1966 }
1967 
1968 bool java_lang_VirtualThread::is_instance(oop obj) {
1969   return obj != nullptr && is_subclass(obj->klass());
1970 }
1971 
1972 oop java_lang_VirtualThread::carrier_thread(oop vthread) {
1973   oop thread = vthread->obj_field(_carrierThread_offset);
1974   return thread;
1975 }
1976 
1977 oop java_lang_VirtualThread::continuation(oop vthread) {
1978   oop cont = vthread->obj_field(_continuation_offset);
1979   return cont;
1980 }
1981 
1982 int java_lang_VirtualThread::state(oop vthread) {
1983   return vthread->int_field_acquire(_state_offset);
1984 }
1985 
1986 JavaThreadStatus java_lang_VirtualThread::map_state_to_thread_status(int state) {
1987   JavaThreadStatus status = JavaThreadStatus::NEW;
1988   switch (state & ~SUSPENDED) {
1989     case NEW:
1990       status = JavaThreadStatus::NEW;
1991       break;
1992     case STARTED:
1993     case RUNNING:
1994     case PARKING:
1995     case TIMED_PARKING:
1996     case UNPARKED:
1997     case YIELDING:
1998     case YIELDED:
1999       status = JavaThreadStatus::RUNNABLE;
2000       break;
2001     case PARKED:
2002     case PINNED:
2003       status = JavaThreadStatus::PARKED;
2004       break;
2005     case TIMED_PARKED:
2006     case TIMED_PINNED:
2007       status = JavaThreadStatus::PARKED_TIMED;
2008       break;
2009     case TERMINATED:
2010       status = JavaThreadStatus::TERMINATED;
2011       break;
2012     default:
2013       ShouldNotReachHere();
2014   }
2015   return status;
2016 }
2017 
2018 #if INCLUDE_CDS
2019 void java_lang_VirtualThread::serialize_offsets(SerializeClosure* f) {
2020    VTHREAD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
2021 }
2022 #endif
2023 
2024 // java_lang_Throwable
2025 
2026 int java_lang_Throwable::_backtrace_offset;
2027 int java_lang_Throwable::_detailMessage_offset;
2028 int java_lang_Throwable::_stackTrace_offset;
2029 int java_lang_Throwable::_depth_offset;
2030 int java_lang_Throwable::_cause_offset;
2031 int java_lang_Throwable::_static_unassigned_stacktrace_offset;
2032 
2033 #define THROWABLE_FIELDS_DO(macro) \
2034   macro(_backtrace_offset,     k, "backtrace",     object_signature,                  false); \
2035   macro(_detailMessage_offset, k, "detailMessage", string_signature,                  false); \
2036   macro(_stackTrace_offset,    k, "stackTrace",    java_lang_StackTraceElement_array, false); \
2037   macro(_depth_offset,         k, "depth",         int_signature,                     false); \
2038   macro(_cause_offset,         k, "cause",         throwable_signature,               false); \
2039   macro(_static_unassigned_stacktrace_offset, k, "UNASSIGNED_STACK", java_lang_StackTraceElement_array, true)
2040 
2041 void java_lang_Throwable::compute_offsets() {
2042   InstanceKlass* k = vmClasses::Throwable_klass();
2043   THROWABLE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
2044 }
2045 
2046 #if INCLUDE_CDS
2047 void java_lang_Throwable::serialize_offsets(SerializeClosure* f) {
2048   THROWABLE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
2049 }
2050 #endif
2051 
2052 oop java_lang_Throwable::unassigned_stacktrace() {
2053   InstanceKlass* ik = vmClasses::Throwable_klass();
2054   oop base = ik->static_field_base_raw();
2055   return base->obj_field(_static_unassigned_stacktrace_offset);
2056 }
2057 
2058 oop java_lang_Throwable::backtrace(oop throwable) {
2059   return throwable->obj_field_acquire(_backtrace_offset);
2060 }
2061 
2062 
2063 void java_lang_Throwable::set_backtrace(oop throwable, oop value) {
2064   throwable->release_obj_field_put(_backtrace_offset, value);
2065 }
2066 
2067 int java_lang_Throwable::depth(oop throwable) {
2068   return throwable->int_field(_depth_offset);
2069 }
2070 
2071 void java_lang_Throwable::set_depth(oop throwable, int value) {
2072   throwable->int_field_put(_depth_offset, value);
2073 }
2074 
2075 oop java_lang_Throwable::message(oop throwable) {
2076   return throwable->obj_field(_detailMessage_offset);
2077 }
2078 
2079 oop java_lang_Throwable::cause(oop throwable) {
2080   return throwable->obj_field(_cause_offset);
2081 }
2082 
2083 // Return Symbol for detailed_message or null
2084 Symbol* java_lang_Throwable::detail_message(oop throwable) {
2085   PreserveExceptionMark pm(Thread::current());
2086   oop detailed_message = java_lang_Throwable::message(throwable);
2087   if (detailed_message != nullptr) {
2088     return java_lang_String::as_symbol(detailed_message);
2089   }
2090   return nullptr;
2091 }
2092 
2093 void java_lang_Throwable::set_message(oop throwable, oop value) {
2094   throwable->obj_field_put(_detailMessage_offset, value);
2095 }
2096 
2097 
2098 void java_lang_Throwable::set_stacktrace(oop throwable, oop st_element_array) {
2099   throwable->obj_field_put(_stackTrace_offset, st_element_array);
2100 }
2101 
2102 void java_lang_Throwable::clear_stacktrace(oop throwable) {
2103   set_stacktrace(throwable, nullptr);
2104 }
2105 
2106 
2107 void java_lang_Throwable::print(oop throwable, outputStream* st) {
2108   ResourceMark rm;
2109   Klass* k = throwable->klass();
2110   assert(k != nullptr, "just checking");
2111   st->print("%s", k->external_name());
2112   oop msg = message(throwable);
2113   if (msg != nullptr) {
2114     st->print(": %s", java_lang_String::as_utf8_string(msg));
2115   }
2116 }
2117 
2118 // After this many redefines, the stack trace is unreliable.
2119 const int MAX_VERSION = USHRT_MAX;
2120 
2121 static inline bool version_matches(Method* method, int version) {
2122   assert(version < MAX_VERSION, "version is too big");
2123   return method != nullptr && (method->constants()->version() == version);
2124 }
2125 
2126 // This class provides a simple wrapper over the internal structure of
2127 // exception backtrace to insulate users of the backtrace from needing
2128 // to know what it looks like.
2129 // The code of this class is not GC safe. Allocations can only happen
2130 // in expand().
2131 class BacktraceBuilder: public StackObj {
2132  friend class BacktraceIterator;
2133  private:
2134   Handle          _backtrace;
2135   objArrayOop     _head;
2136   typeArrayOop    _methods;
2137   typeArrayOop    _bcis;
2138   objArrayOop     _mirrors;
2139   typeArrayOop    _names; // Needed to insulate method name against redefinition.
2140   // True if the top frame of the backtrace is omitted because it shall be hidden.
2141   bool            _has_hidden_top_frame;
2142   int             _index;
2143   NoSafepointVerifier _nsv;
2144 
2145   enum {
2146     trace_methods_offset = java_lang_Throwable::trace_methods_offset,
2147     trace_bcis_offset    = java_lang_Throwable::trace_bcis_offset,
2148     trace_mirrors_offset = java_lang_Throwable::trace_mirrors_offset,
2149     trace_names_offset   = java_lang_Throwable::trace_names_offset,
2150     trace_conts_offset   = java_lang_Throwable::trace_conts_offset,
2151     trace_next_offset    = java_lang_Throwable::trace_next_offset,
2152     trace_hidden_offset  = java_lang_Throwable::trace_hidden_offset,
2153     trace_size           = java_lang_Throwable::trace_size,
2154     trace_chunk_size     = java_lang_Throwable::trace_chunk_size
2155   };
2156 
2157   // get info out of chunks
2158   static typeArrayOop get_methods(objArrayHandle chunk) {
2159     typeArrayOop methods = typeArrayOop(chunk->obj_at(trace_methods_offset));
2160     assert(methods != nullptr, "method array should be initialized in backtrace");
2161     return methods;
2162   }
2163   static typeArrayOop get_bcis(objArrayHandle chunk) {
2164     typeArrayOop bcis = typeArrayOop(chunk->obj_at(trace_bcis_offset));
2165     assert(bcis != nullptr, "bci array should be initialized in backtrace");
2166     return bcis;
2167   }
2168   static objArrayOop get_mirrors(objArrayHandle chunk) {
2169     objArrayOop mirrors = objArrayOop(chunk->obj_at(trace_mirrors_offset));
2170     assert(mirrors != nullptr, "mirror array should be initialized in backtrace");
2171     return mirrors;
2172   }
2173   static typeArrayOop get_names(objArrayHandle chunk) {
2174     typeArrayOop names = typeArrayOop(chunk->obj_at(trace_names_offset));
2175     assert(names != nullptr, "names array should be initialized in backtrace");
2176     return names;
2177   }
2178   static bool has_hidden_top_frame(objArrayHandle chunk) {
2179     oop hidden = chunk->obj_at(trace_hidden_offset);
2180     return hidden != nullptr;
2181   }
2182 
2183  public:
2184 
2185   // constructor for new backtrace
2186   BacktraceBuilder(TRAPS): _head(nullptr), _methods(nullptr), _bcis(nullptr), _mirrors(nullptr), _names(nullptr), _has_hidden_top_frame(false) {
2187     expand(CHECK);
2188     _backtrace = Handle(THREAD, _head);
2189     _index = 0;
2190   }
2191 
2192   BacktraceBuilder(Thread* thread, objArrayHandle backtrace) {
2193     _methods = get_methods(backtrace);
2194     _bcis = get_bcis(backtrace);
2195     _mirrors = get_mirrors(backtrace);
2196     _names = get_names(backtrace);
2197     _has_hidden_top_frame = has_hidden_top_frame(backtrace);
2198     assert(_methods->length() == _bcis->length() &&
2199            _methods->length() == _mirrors->length() &&
2200            _mirrors->length() == _names->length(),
2201            "method and source information arrays should match");
2202 
2203     // head is the preallocated backtrace
2204     _head = backtrace();
2205     _backtrace = Handle(thread, _head);
2206     _index = 0;
2207   }
2208 
2209   void expand(TRAPS) {
2210     objArrayHandle old_head(THREAD, _head);
2211     PauseNoSafepointVerifier pnsv(&_nsv);
2212 
2213     objArrayOop head = oopFactory::new_objectArray(trace_size, CHECK);
2214     objArrayHandle new_head(THREAD, head);
2215 
2216     typeArrayOop methods = oopFactory::new_shortArray(trace_chunk_size, CHECK);
2217     typeArrayHandle new_methods(THREAD, methods);
2218 
2219     typeArrayOop bcis = oopFactory::new_intArray(trace_chunk_size, CHECK);
2220     typeArrayHandle new_bcis(THREAD, bcis);
2221 
2222     objArrayOop mirrors = oopFactory::new_objectArray(trace_chunk_size, CHECK);
2223     objArrayHandle new_mirrors(THREAD, mirrors);
2224 
2225     typeArrayOop names = oopFactory::new_symbolArray(trace_chunk_size, CHECK);
2226     typeArrayHandle new_names(THREAD, names);
2227 
2228     if (!old_head.is_null()) {
2229       old_head->obj_at_put(trace_next_offset, new_head());
2230     }
2231     new_head->obj_at_put(trace_methods_offset, new_methods());
2232     new_head->obj_at_put(trace_bcis_offset, new_bcis());
2233     new_head->obj_at_put(trace_mirrors_offset, new_mirrors());
2234     new_head->obj_at_put(trace_names_offset, new_names());
2235     new_head->obj_at_put(trace_hidden_offset, nullptr);
2236 
2237     _head    = new_head();
2238     _methods = new_methods();
2239     _bcis = new_bcis();
2240     _mirrors = new_mirrors();
2241     _names  = new_names();
2242     _index = 0;
2243   }
2244 
2245   oop backtrace() {
2246     return _backtrace();
2247   }
2248 
2249   inline void push(Method* method, int bci, TRAPS) {
2250     // Smear the -1 bci to 0 since the array only holds unsigned
2251     // shorts.  The later line number lookup would just smear the -1
2252     // to a 0 even if it could be recorded.
2253     if (bci == SynchronizationEntryBCI) bci = 0;
2254 
2255     if (_index >= trace_chunk_size) {
2256       methodHandle mhandle(THREAD, method);
2257       expand(CHECK);
2258       method = mhandle();
2259     }
2260 
2261     _methods->ushort_at_put(_index, method->orig_method_idnum());
2262     _bcis->int_at_put(_index, Backtrace::merge_bci_and_version(bci, method->constants()->version()));
2263 
2264     // Note:this doesn't leak symbols because the mirror in the backtrace keeps the
2265     // klass owning the symbols alive so their refcounts aren't decremented.
2266     Symbol* name = method->name();
2267     _names->symbol_at_put(_index, name);
2268 
2269     // We need to save the mirrors in the backtrace to keep the class
2270     // from being unloaded while we still have this stack trace.
2271     assert(method->method_holder()->java_mirror() != nullptr, "never push null for mirror");
2272     _mirrors->obj_at_put(_index, method->method_holder()->java_mirror());
2273 
2274     _index++;
2275   }
2276 
2277   void set_has_hidden_top_frame() {
2278     if (!_has_hidden_top_frame) {
2279       // It would be nice to add java/lang/Boolean::TRUE here
2280       // to indicate that this backtrace has a hidden top frame.
2281       // But this code is used before TRUE is allocated.
2282       // Therefore let's just use an arbitrary legal oop
2283       // available right here. _methods is a short[].
2284       assert(_methods != nullptr, "we need a legal oop");
2285       _has_hidden_top_frame = true;
2286       _head->obj_at_put(trace_hidden_offset, _methods);
2287     }
2288   }
2289 };
2290 
2291 struct BacktraceElement : public StackObj {
2292   int _method_id;
2293   int _bci;
2294   int _version;
2295   Symbol* _name;
2296   Handle _mirror;
2297   BacktraceElement(Handle mirror, int mid, int version, int bci, Symbol* name) :
2298                    _method_id(mid), _bci(bci), _version(version), _name(name), _mirror(mirror) {}
2299 };
2300 
2301 class BacktraceIterator : public StackObj {
2302   int _index;
2303   objArrayHandle  _result;
2304   objArrayHandle  _mirrors;
2305   typeArrayHandle _methods;
2306   typeArrayHandle _bcis;
2307   typeArrayHandle _names;
2308 
2309   void init(objArrayHandle result, Thread* thread) {
2310     // Get method id, bci, version and mirror from chunk
2311     _result = result;
2312     if (_result.not_null()) {
2313       _methods = typeArrayHandle(thread, BacktraceBuilder::get_methods(_result));
2314       _bcis = typeArrayHandle(thread, BacktraceBuilder::get_bcis(_result));
2315       _mirrors = objArrayHandle(thread, BacktraceBuilder::get_mirrors(_result));
2316       _names = typeArrayHandle(thread, BacktraceBuilder::get_names(_result));
2317       _index = 0;
2318     }
2319   }
2320  public:
2321   BacktraceIterator(objArrayHandle result, Thread* thread) {
2322     init(result, thread);
2323     assert(_methods.is_null() || _methods->length() == java_lang_Throwable::trace_chunk_size, "lengths don't match");
2324   }
2325 
2326   BacktraceElement next(Thread* thread) {
2327     BacktraceElement e (Handle(thread, _mirrors->obj_at(_index)),
2328                         _methods->ushort_at(_index),
2329                         Backtrace::version_at(_bcis->int_at(_index)),
2330                         Backtrace::bci_at(_bcis->int_at(_index)),
2331                         _names->symbol_at(_index));
2332     _index++;
2333 
2334     if (_index >= java_lang_Throwable::trace_chunk_size) {
2335       int next_offset = java_lang_Throwable::trace_next_offset;
2336       // Get next chunk
2337       objArrayHandle result (thread, objArrayOop(_result->obj_at(next_offset)));
2338       init(result, thread);
2339     }
2340     return e;
2341   }
2342 
2343   bool repeat() {
2344     return _result.not_null() && _mirrors->obj_at(_index) != nullptr;
2345   }
2346 };
2347 
2348 
2349 // Print stack trace element to resource allocated buffer
2350 static void print_stack_element_to_stream(outputStream* st, Handle mirror, int method_id,
2351                                           int version, int bci, Symbol* name) {
2352   ResourceMark rm;
2353 
2354   // Get strings and string lengths
2355   InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(mirror()));
2356   const char* klass_name  = holder->external_name();
2357   int buf_len = (int)strlen(klass_name);
2358 
2359   char* method_name = name->as_C_string();
2360   buf_len += (int)strlen(method_name);
2361 
2362   char* source_file_name = nullptr;
2363   Symbol* source = Backtrace::get_source_file_name(holder, version);
2364   if (source != nullptr) {
2365     source_file_name = source->as_C_string();
2366     buf_len += (int)strlen(source_file_name);
2367   }
2368 
2369   char *module_name = nullptr, *module_version = nullptr;
2370   ModuleEntry* module = holder->module();
2371   if (module->is_named()) {
2372     module_name = module->name()->as_C_string();
2373     buf_len += (int)strlen(module_name);
2374     if (module->version() != nullptr) {
2375       module_version = module->version()->as_C_string();
2376       buf_len += (int)strlen(module_version);
2377     }
2378   }
2379 
2380   // Allocate temporary buffer with extra space for formatting and line number
2381   const size_t buf_size = buf_len + 64;
2382   char* buf = NEW_RESOURCE_ARRAY(char, buf_size);
2383 
2384   // Print stack trace line in buffer
2385   size_t buf_off = os::snprintf_checked(buf, buf_size, "\tat %s.%s(", klass_name, method_name);
2386 
2387   // Print module information
2388   if (module_name != nullptr) {
2389     if (module_version != nullptr) {
2390       buf_off += os::snprintf_checked(buf + buf_off, buf_size - buf_off, "%s@%s/", module_name, module_version);
2391     } else {
2392       buf_off += os::snprintf_checked(buf + buf_off, buf_size - buf_off, "%s/", module_name);
2393     }
2394   }
2395 
2396   // The method can be null if the requested class version is gone
2397   Method* method = holder->method_with_orig_idnum(method_id, version);
2398   if (!version_matches(method, version)) {
2399     strcat(buf, "Redefined)");
2400   } else {
2401     int line_number = Backtrace::get_line_number(method, bci);
2402     if (line_number == -2) {
2403       strcat(buf, "Native Method)");
2404     } else {
2405       if (source_file_name != nullptr && (line_number != -1)) {
2406         // Sourcename and linenumber
2407         buf_off += os::snprintf_checked(buf + buf_off, buf_size - buf_off, "%s:%d)", source_file_name, line_number);
2408       } else if (source_file_name != nullptr) {
2409         // Just sourcename
2410         buf_off += os::snprintf_checked(buf + buf_off, buf_size - buf_off, "%s)", source_file_name);
2411       } else {
2412         // Neither sourcename nor linenumber
2413         buf_off += os::snprintf_checked(buf + buf_off, buf_size - buf_off, "Unknown Source)");
2414       }
2415       CompiledMethod* nm = method->code();
2416       if (WizardMode && nm != nullptr) {
2417         os::snprintf_checked(buf + buf_off, buf_size - buf_off, "(nmethod " INTPTR_FORMAT ")", (intptr_t)nm);
2418       }
2419     }
2420   }
2421 
2422   st->print_cr("%s", buf);
2423 }
2424 
2425 void java_lang_Throwable::print_stack_element(outputStream *st, Method* method, int bci) {
2426   Handle mirror (Thread::current(),  method->method_holder()->java_mirror());
2427   int method_id = method->orig_method_idnum();
2428   int version = method->constants()->version();
2429   print_stack_element_to_stream(st, mirror, method_id, version, bci, method->name());
2430 }
2431 
2432 /**
2433  * Print the throwable message and its stack trace plus all causes by walking the
2434  * cause chain.  The output looks the same as of Throwable.printStackTrace().
2435  */
2436 void java_lang_Throwable::print_stack_trace(Handle throwable, outputStream* st) {
2437   // First, print the message.
2438   print(throwable(), st);
2439   st->cr();
2440 
2441   // Now print the stack trace.
2442   JavaThread* THREAD = JavaThread::current(); // For exception macros.
2443   while (throwable.not_null()) {
2444     objArrayHandle result (THREAD, objArrayOop(backtrace(throwable())));
2445     if (result.is_null()) {
2446       st->print_raw_cr("\t<<no stack trace available>>");
2447       return;
2448     }
2449     BacktraceIterator iter(result, THREAD);
2450 
2451     while (iter.repeat()) {
2452       BacktraceElement bte = iter.next(THREAD);
2453       print_stack_element_to_stream(st, bte._mirror, bte._method_id, bte._version, bte._bci, bte._name);
2454     }
2455     if (THREAD->can_call_java()) {
2456       // Call getCause() which doesn't necessarily return the _cause field.
2457       ExceptionMark em(THREAD);
2458       JavaValue cause(T_OBJECT);
2459       JavaCalls::call_virtual(&cause,
2460                               throwable,
2461                               throwable->klass(),
2462                               vmSymbols::getCause_name(),
2463                               vmSymbols::void_throwable_signature(),
2464                               THREAD);
2465       // Ignore any exceptions. we are in the middle of exception handling. Same as classic VM.
2466       if (HAS_PENDING_EXCEPTION) {
2467         CLEAR_PENDING_EXCEPTION;
2468         throwable = Handle();
2469       } else {
2470         throwable = Handle(THREAD, cause.get_oop());
2471         if (throwable.not_null()) {
2472           st->print("Caused by: ");
2473           print(throwable(), st);
2474           st->cr();
2475         }
2476       }
2477     } else {
2478       st->print_raw_cr("<<cannot call Java to get cause>>");
2479       return;
2480     }
2481   }
2482 }
2483 
2484 /**
2485  * Print the throwable stack trace by calling the Java method java.lang.Throwable.printStackTrace().
2486  */
2487 void java_lang_Throwable::java_printStackTrace(Handle throwable, TRAPS) {
2488   assert(throwable->is_a(vmClasses::Throwable_klass()), "Throwable instance expected");
2489   JavaValue result(T_VOID);
2490   JavaCalls::call_virtual(&result,
2491                           throwable,
2492                           vmClasses::Throwable_klass(),
2493                           vmSymbols::printStackTrace_name(),
2494                           vmSymbols::void_method_signature(),
2495                           THREAD);
2496 }
2497 
2498 void java_lang_Throwable::fill_in_stack_trace(Handle throwable, const methodHandle& method, TRAPS) {
2499   if (!StackTraceInThrowable) return;
2500   ResourceMark rm(THREAD);
2501 
2502   // Start out by clearing the backtrace for this object, in case the VM
2503   // runs out of memory while allocating the stack trace
2504   set_backtrace(throwable(), nullptr);
2505   // Clear lazily constructed Java level stacktrace if refilling occurs
2506   // This is unnecessary in 1.7+ but harmless
2507   clear_stacktrace(throwable());
2508 
2509   int max_depth = MaxJavaStackTraceDepth;
2510   JavaThread* thread = THREAD;
2511 
2512   BacktraceBuilder bt(CHECK);
2513 
2514   // If there is no Java frame just return the method that was being called
2515   // with bci 0
2516   if (!thread->has_last_Java_frame()) {
2517     if (max_depth >= 1 && method() != nullptr) {
2518       bt.push(method(), 0, CHECK);
2519       log_info(stacktrace)("%s, %d", throwable->klass()->external_name(), 1);
2520       set_depth(throwable(), 1);
2521       set_backtrace(throwable(), bt.backtrace());
2522     }
2523     return;
2524   }
2525 
2526   // Instead of using vframe directly, this version of fill_in_stack_trace
2527   // basically handles everything by hand. This significantly improved the
2528   // speed of this method call up to 28.5% on Solaris sparc. 27.1% on Windows.
2529   // See bug 6333838 for  more details.
2530   // The "ASSERT" here is to verify this method generates the exactly same stack
2531   // trace as utilizing vframe.
2532 #ifdef ASSERT
2533   vframeStream st(thread, false /* stop_at_java_call_stub */, false /* process_frames */);
2534 #endif
2535   int total_count = 0;
2536   RegisterMap map(thread,
2537                   RegisterMap::UpdateMap::skip,
2538                   RegisterMap::ProcessFrames::skip,
2539                   RegisterMap::WalkContinuation::include);
2540   int decode_offset = 0;
2541   CompiledMethod* nm = nullptr;
2542   bool skip_fillInStackTrace_check = false;
2543   bool skip_throwableInit_check = false;
2544   bool skip_hidden = !ShowHiddenFrames;
2545   bool show_carrier = ShowCarrierFrames;
2546   ContinuationEntry* cont_entry = thread->last_continuation();
2547   for (frame fr = thread->last_frame(); max_depth == 0 || max_depth != total_count;) {
2548     Method* method = nullptr;
2549     int bci = 0;
2550 
2551     // Compiled java method case.
2552     if (decode_offset != 0) {
2553       DebugInfoReadStream stream(nm, decode_offset);
2554       decode_offset = stream.read_int();
2555       method = (Method*)nm->metadata_at(stream.read_int());
2556       bci = stream.read_bci();
2557     } else {
2558       if (fr.is_first_frame()) break;
2559 
2560       if (Continuation::is_continuation_enterSpecial(fr)) {
2561         assert(cont_entry == Continuation::get_continuation_entry_for_entry_frame(thread, fr), "");
2562         if (!show_carrier && cont_entry->is_virtual_thread()) {
2563           break;
2564         }
2565         cont_entry = cont_entry->parent();
2566       }
2567 
2568       address pc = fr.pc();
2569       if (fr.is_interpreted_frame()) {
2570         address bcp;
2571         if (!map.in_cont()) {
2572           bcp = fr.interpreter_frame_bcp();
2573           method = fr.interpreter_frame_method();
2574         } else {
2575           bcp = map.stack_chunk()->interpreter_frame_bcp(fr);
2576           method = map.stack_chunk()->interpreter_frame_method(fr);
2577         }
2578         bci =  method->bci_from(bcp);
2579         fr = fr.sender(&map);
2580       } else {
2581         CodeBlob* cb = fr.cb();
2582         // HMMM QQQ might be nice to have frame return nm as null if cb is non-null
2583         // but non nmethod
2584         fr = fr.sender(&map);
2585         if (cb == nullptr || !cb->is_compiled()) {
2586           continue;
2587         }
2588         nm = cb->as_compiled_method();
2589         assert(nm->method() != nullptr, "must be");
2590         if (nm->method()->is_native()) {
2591           method = nm->method();
2592           bci = 0;
2593         } else {
2594           PcDesc* pd = nm->pc_desc_at(pc);
2595           decode_offset = pd->scope_decode_offset();
2596           // if decode_offset is not equal to 0, it will execute the
2597           // "compiled java method case" at the beginning of the loop.
2598           continue;
2599         }
2600       }
2601     }
2602 #ifdef ASSERT
2603     if (!st.at_end()) { // TODO LOOM remove once we show only vthread trace
2604       assert(st.method() == method && st.bci() == bci, "Wrong stack trace");
2605       st.next();
2606     }
2607 #endif
2608 
2609     // the format of the stacktrace will be:
2610     // - 1 or more fillInStackTrace frames for the exception class (skipped)
2611     // - 0 or more <init> methods for the exception class (skipped)
2612     // - rest of the stack
2613 
2614     if (!skip_fillInStackTrace_check) {
2615       if (method->name() == vmSymbols::fillInStackTrace_name() &&
2616           throwable->is_a(method->method_holder())) {
2617         continue;
2618       }
2619       else {
2620         skip_fillInStackTrace_check = true; // gone past them all
2621       }
2622     }
2623     if (!skip_throwableInit_check) {
2624       assert(skip_fillInStackTrace_check, "logic error in backtrace filtering");
2625 
2626       // skip <init> methods of the exception class and superclasses
2627       // This is similar to classic VM.
2628       if (method->name() == vmSymbols::object_initializer_name() &&
2629           throwable->is_a(method->method_holder())) {
2630         continue;
2631       } else {
2632         // there are none or we've seen them all - either way stop checking
2633         skip_throwableInit_check = true;
2634       }
2635     }
2636     if (method->is_hidden() || method->is_continuation_enter_intrinsic()) {
2637       if (skip_hidden) {
2638         if (total_count == 0) {
2639           // The top frame will be hidden from the stack trace.
2640           bt.set_has_hidden_top_frame();
2641         }
2642         continue;
2643       }
2644     }
2645 
2646     bt.push(method, bci, CHECK);
2647     total_count++;
2648   }
2649 
2650   log_info(stacktrace)("%s, %d", throwable->klass()->external_name(), total_count);
2651 
2652   // Put completed stack trace into throwable object
2653   set_backtrace(throwable(), bt.backtrace());
2654   set_depth(throwable(), total_count);
2655 }
2656 
2657 void java_lang_Throwable::fill_in_stack_trace(Handle throwable, const methodHandle& method) {
2658   // No-op if stack trace is disabled
2659   if (!StackTraceInThrowable) {
2660     return;
2661   }
2662 
2663   // Disable stack traces for some preallocated out of memory errors
2664   if (!Universe::should_fill_in_stack_trace(throwable)) {
2665     return;
2666   }
2667 
2668   JavaThread* THREAD = JavaThread::current(); // For exception macros.
2669   PreserveExceptionMark pm(THREAD);
2670 
2671   fill_in_stack_trace(throwable, method, THREAD);
2672   // Ignore exceptions thrown during stack trace filling (OOM) and reinstall the
2673   // original exception via the PreserveExceptionMark destructor.
2674   CLEAR_PENDING_EXCEPTION;
2675 }
2676 
2677 void java_lang_Throwable::allocate_backtrace(Handle throwable, TRAPS) {
2678   // Allocate stack trace - backtrace is created but not filled in
2679 
2680   // No-op if stack trace is disabled
2681   if (!StackTraceInThrowable) return;
2682   BacktraceBuilder bt(CHECK);   // creates a backtrace
2683   set_backtrace(throwable(), bt.backtrace());
2684 }
2685 
2686 
2687 void java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(Handle throwable) {
2688   // Fill in stack trace into preallocated backtrace (no GC)
2689 
2690   // No-op if stack trace is disabled
2691   if (!StackTraceInThrowable) return;
2692 
2693   assert(throwable->is_a(vmClasses::Throwable_klass()), "sanity check");
2694 
2695   JavaThread* THREAD = JavaThread::current(); // For exception macros.
2696 
2697   objArrayHandle backtrace (THREAD, (objArrayOop)java_lang_Throwable::backtrace(throwable()));
2698   assert(backtrace.not_null(), "backtrace should have been preallocated");
2699 
2700   ResourceMark rm(THREAD);
2701   vframeStream st(THREAD, false /* stop_at_java_call_stub */, false /* process_frames */);
2702 
2703   BacktraceBuilder bt(THREAD, backtrace);
2704 
2705   // Unlike fill_in_stack_trace we do not skip fillInStackTrace or throwable init
2706   // methods as preallocated errors aren't created by "java" code.
2707 
2708   // fill in as much stack trace as possible
2709   int chunk_count = 0;
2710   for (;!st.at_end(); st.next()) {
2711     bt.push(st.method(), st.bci(), CHECK);
2712     chunk_count++;
2713 
2714     // Bail-out for deep stacks
2715     if (chunk_count >= trace_chunk_size) break;
2716   }
2717   set_depth(throwable(), chunk_count);
2718   log_info(stacktrace)("%s, %d", throwable->klass()->external_name(), chunk_count);
2719 
2720   // We support the Throwable immutability protocol defined for Java 7.
2721   java_lang_Throwable::set_stacktrace(throwable(), java_lang_Throwable::unassigned_stacktrace());
2722   assert(java_lang_Throwable::unassigned_stacktrace() != nullptr, "not initialized");
2723 }
2724 
2725 void java_lang_Throwable::get_stack_trace_elements(int depth, Handle backtrace,
2726                                                    objArrayHandle stack_trace_array_h, TRAPS) {
2727 
2728   if (backtrace.is_null() || stack_trace_array_h.is_null()) {
2729     THROW(vmSymbols::java_lang_NullPointerException());
2730   }
2731 
2732   assert(stack_trace_array_h->is_objArray(), "Stack trace array should be an array of StackTraceElenent");
2733 
2734   if (stack_trace_array_h->length() != depth) {
2735     THROW(vmSymbols::java_lang_IndexOutOfBoundsException());
2736   }
2737 
2738   objArrayHandle result(THREAD, objArrayOop(backtrace()));
2739   BacktraceIterator iter(result, THREAD);
2740 
2741   int index = 0;
2742   while (iter.repeat()) {
2743     BacktraceElement bte = iter.next(THREAD);
2744 
2745     Handle stack_trace_element(THREAD, stack_trace_array_h->obj_at(index++));
2746 
2747     if (stack_trace_element.is_null()) {
2748       THROW(vmSymbols::java_lang_NullPointerException());
2749     }
2750 
2751     InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(bte._mirror()));
2752     methodHandle method (THREAD, holder->method_with_orig_idnum(bte._method_id, bte._version));
2753 
2754     java_lang_StackTraceElement::fill_in(stack_trace_element, holder,
2755                                          method,
2756                                          bte._version,
2757                                          bte._bci,
2758                                          bte._name,
2759                                          CHECK);
2760   }
2761 }
2762 
2763 Handle java_lang_Throwable::create_initialization_error(JavaThread* current, Handle throwable) {
2764   // Creates an ExceptionInInitializerError to be recorded as the initialization error when class initialization
2765   // failed due to the passed in 'throwable'. We cannot save 'throwable' directly due to issues with keeping alive
2766   // all objects referenced via its stacktrace. So instead we save a new EIIE instance, with the same message and
2767   // symbolic stacktrace of 'throwable'.
2768   assert(throwable.not_null(), "shouldn't be");
2769 
2770   // Now create the message from the original exception and thread name.
2771   ResourceMark rm(current);
2772   const char *message = nullptr;
2773   oop detailed_message = java_lang_Throwable::message(throwable());
2774   if (detailed_message != nullptr) {
2775     message = java_lang_String::as_utf8_string(detailed_message);
2776   }
2777   stringStream st;
2778   st.print("Exception %s%s ", throwable()->klass()->name()->as_klass_external_name(),
2779              message == nullptr ? "" : ":");
2780   if (message == nullptr) {
2781     st.print("[in thread \"%s\"]", current->name());
2782   } else {
2783     st.print("%s [in thread \"%s\"]", message, current->name());
2784   }
2785 
2786   Symbol* exception_name = vmSymbols::java_lang_ExceptionInInitializerError();
2787   Handle init_error = Exceptions::new_exception(current, exception_name, st.as_string());
2788   // If new_exception returns a different exception while creating the exception,
2789   // abandon the attempt to save the initialization error and return null.
2790   if (init_error->klass()->name() != exception_name) {
2791     log_info(class, init)("Exception %s thrown while saving initialization exception",
2792                         init_error->klass()->external_name());
2793     return Handle();
2794   }
2795 
2796   // Call to java to fill in the stack trace and clear declaringClassObject to
2797   // not keep classes alive in the stack trace.
2798   // call this:  public StackTraceElement[] getStackTrace()
2799   JavaValue result(T_ARRAY);
2800   JavaCalls::call_virtual(&result, throwable,
2801                           vmClasses::Throwable_klass(),
2802                           vmSymbols::getStackTrace_name(),
2803                           vmSymbols::getStackTrace_signature(),
2804                           current);
2805   if (!current->has_pending_exception()){
2806     Handle stack_trace(current, result.get_oop());
2807     assert(stack_trace->is_objArray(), "Should be an array");
2808     java_lang_Throwable::set_stacktrace(init_error(), stack_trace());
2809     // Clear backtrace because the stacktrace should be used instead.
2810     set_backtrace(init_error(), nullptr);
2811   } else {
2812     log_info(class, init)("Exception thrown while getting stack trace for initialization exception %s",
2813                         init_error->klass()->external_name());
2814     current->clear_pending_exception();
2815   }
2816 
2817   return init_error;
2818 }
2819 
2820 bool java_lang_Throwable::get_top_method_and_bci(oop throwable, Method** method, int* bci) {
2821   JavaThread* current = JavaThread::current();
2822   objArrayHandle result(current, objArrayOop(backtrace(throwable)));
2823   BacktraceIterator iter(result, current);
2824   // No backtrace available.
2825   if (!iter.repeat()) return false;
2826 
2827   // If the exception happened in a frame that has been hidden, i.e.,
2828   // omitted from the back trace, we can not compute the message.
2829   oop hidden = ((objArrayOop)backtrace(throwable))->obj_at(trace_hidden_offset);
2830   if (hidden != nullptr) {
2831     return false;
2832   }
2833 
2834   // Get first backtrace element.
2835   BacktraceElement bte = iter.next(current);
2836 
2837   InstanceKlass* holder = InstanceKlass::cast(java_lang_Class::as_Klass(bte._mirror()));
2838   assert(holder != nullptr, "first element should be non-null");
2839   Method* m = holder->method_with_orig_idnum(bte._method_id, bte._version);
2840 
2841   // Original version is no longer available.
2842   if (m == nullptr || !version_matches(m, bte._version)) {
2843     return false;
2844   }
2845 
2846   *method = m;
2847   *bci = bte._bci;
2848   return true;
2849 }
2850 
2851 oop java_lang_StackTraceElement::create(const methodHandle& method, int bci, TRAPS) {
2852   // Allocate java.lang.StackTraceElement instance
2853   InstanceKlass* k = vmClasses::StackTraceElement_klass();
2854   assert(k != nullptr, "must be loaded in 1.4+");
2855   if (k->should_be_initialized()) {
2856     k->initialize(CHECK_NULL);
2857   }
2858 
2859   Handle element = k->allocate_instance_handle(CHECK_NULL);
2860 
2861   int version = method->constants()->version();
2862   fill_in(element, method->method_holder(), method, version, bci, method->name(), CHECK_NULL);
2863   return element();
2864 }
2865 
2866 void java_lang_StackTraceElement::fill_in(Handle element,
2867                                           InstanceKlass* holder, const methodHandle& method,
2868                                           int version, int bci, Symbol* name, TRAPS) {
2869   assert(element->is_a(vmClasses::StackTraceElement_klass()), "sanity check");
2870 
2871   ResourceMark rm(THREAD);
2872   HandleMark hm(THREAD);
2873 
2874   // Fill in class name
2875   Handle java_class(THREAD, holder->java_mirror());
2876   oop classname = java_lang_Class::name(java_class, CHECK);
2877   java_lang_StackTraceElement::set_declaringClass(element(), classname);
2878   java_lang_StackTraceElement::set_declaringClassObject(element(), java_class());
2879 
2880   oop loader = holder->class_loader();
2881   if (loader != nullptr) {
2882     oop loader_name = java_lang_ClassLoader::name(loader);
2883     if (loader_name != nullptr)
2884       java_lang_StackTraceElement::set_classLoaderName(element(), loader_name);
2885   }
2886 
2887   // Fill in method name
2888   oop methodname = StringTable::intern(name, CHECK);
2889   java_lang_StackTraceElement::set_methodName(element(), methodname);
2890 
2891   // Fill in module name and version
2892   ModuleEntry* module = holder->module();
2893   if (module->is_named()) {
2894     oop module_name = StringTable::intern(module->name(), CHECK);
2895     java_lang_StackTraceElement::set_moduleName(element(), module_name);
2896     oop module_version;
2897     if (module->version() != nullptr) {
2898       module_version = StringTable::intern(module->version(), CHECK);
2899     } else {
2900       module_version = nullptr;
2901     }
2902     java_lang_StackTraceElement::set_moduleVersion(element(), module_version);
2903   }
2904 
2905   if (method() == nullptr || !version_matches(method(), version)) {
2906     // The method was redefined, accurate line number information isn't available
2907     java_lang_StackTraceElement::set_fileName(element(), nullptr);
2908     java_lang_StackTraceElement::set_lineNumber(element(), -1);
2909   } else {
2910     Symbol* source;
2911     oop source_file;
2912     int line_number;
2913     decode_file_and_line(java_class, holder, version, method, bci, source, source_file, line_number, CHECK);
2914 
2915     java_lang_StackTraceElement::set_fileName(element(), source_file);
2916     java_lang_StackTraceElement::set_lineNumber(element(), line_number);
2917   }
2918 }
2919 
2920 void java_lang_StackTraceElement::decode_file_and_line(Handle java_class,
2921                                                        InstanceKlass* holder,
2922                                                        int version,
2923                                                        const methodHandle& method,
2924                                                        int bci,
2925                                                        Symbol*& source,
2926                                                        oop& source_file,
2927                                                        int& line_number, TRAPS) {
2928   // Fill in source file name and line number.
2929   source = Backtrace::get_source_file_name(holder, version);
2930   source_file = java_lang_Class::source_file(java_class());
2931   if (source != nullptr) {
2932     // Class was not redefined. We can trust its cache if set,
2933     // else we have to initialize it.
2934     if (source_file == nullptr) {
2935       source_file = StringTable::intern(source, CHECK);
2936       java_lang_Class::set_source_file(java_class(), source_file);
2937     }
2938   } else {
2939     // Class was redefined. Dump the cache if it was set.
2940     if (source_file != nullptr) {
2941       source_file = nullptr;
2942       java_lang_Class::set_source_file(java_class(), source_file);
2943     }
2944   }
2945   line_number = Backtrace::get_line_number(method(), bci);
2946 }
2947 
2948 #if INCLUDE_JVMCI
2949 void java_lang_StackTraceElement::decode(const methodHandle& method, int bci,
2950                                          Symbol*& filename, int& line_number, TRAPS) {
2951   ResourceMark rm(THREAD);
2952   HandleMark hm(THREAD);
2953 
2954   filename = nullptr;
2955   line_number = -1;
2956 
2957   oop source_file;
2958   int version = method->constants()->version();
2959   InstanceKlass* holder = method->method_holder();
2960   Handle java_class(THREAD, holder->java_mirror());
2961   decode_file_and_line(java_class, holder, version, method, bci, filename, source_file, line_number, CHECK);
2962 }
2963 #endif // INCLUDE_JVMCI
2964 
2965 // java_lang_ClassFrameInfo
2966 
2967 int java_lang_ClassFrameInfo::_classOrMemberName_offset;
2968 int java_lang_ClassFrameInfo::_flags_offset;
2969 
2970 #define CLASSFRAMEINFO_FIELDS_DO(macro) \
2971   macro(_classOrMemberName_offset, k, "classOrMemberName", object_signature,  false); \
2972   macro(_flags_offset,             k, vmSymbols::flags_name(), int_signature, false)
2973 
2974 void java_lang_ClassFrameInfo::compute_offsets() {
2975   InstanceKlass* k = vmClasses::ClassFrameInfo_klass();
2976   CLASSFRAMEINFO_FIELDS_DO(FIELD_COMPUTE_OFFSET);
2977 }
2978 
2979 #if INCLUDE_CDS
2980 void java_lang_ClassFrameInfo::serialize_offsets(SerializeClosure* f) {
2981   CLASSFRAMEINFO_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
2982 }
2983 #endif
2984 
2985 static int get_flags(const methodHandle& m) {
2986   int flags = (jushort)( m->access_flags().as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS );
2987   if (m->is_initializer()) {
2988     flags |= java_lang_invoke_MemberName::MN_IS_CONSTRUCTOR;
2989   } else {
2990     flags |= java_lang_invoke_MemberName::MN_IS_METHOD;
2991   }
2992   if (m->caller_sensitive()) {
2993     flags |= java_lang_invoke_MemberName::MN_CALLER_SENSITIVE;
2994   }
2995   if (m->is_hidden()) {
2996     flags |= java_lang_invoke_MemberName::MN_HIDDEN_MEMBER;
2997   }
2998   assert((flags & 0xFF000000) == 0, "unexpected flags");
2999   return flags;
3000 }
3001 
3002 oop java_lang_ClassFrameInfo::classOrMemberName(oop obj) {
3003   return obj->obj_field(_classOrMemberName_offset);
3004 }
3005 
3006 int java_lang_ClassFrameInfo::flags(oop obj) {
3007   return obj->int_field(_flags_offset);
3008 }
3009 
3010 void java_lang_ClassFrameInfo::init_class(Handle stackFrame, const methodHandle& m) {
3011   stackFrame->obj_field_put(_classOrMemberName_offset, m->method_holder()->java_mirror());
3012   // flags is initialized when ClassFrameInfo object is constructed and retain the value
3013   int flags = java_lang_ClassFrameInfo::flags(stackFrame()) | get_flags(m);
3014   stackFrame->int_field_put(_flags_offset, flags);
3015 }
3016 
3017 void java_lang_ClassFrameInfo::init_method(Handle stackFrame, const methodHandle& m, TRAPS) {
3018   oop rmethod_name = java_lang_invoke_ResolvedMethodName::find_resolved_method(m, CHECK);
3019   stackFrame->obj_field_put(_classOrMemberName_offset, rmethod_name);
3020   // flags is initialized when ClassFrameInfo object is constructed and retain the value
3021   int flags = java_lang_ClassFrameInfo::flags(stackFrame()) | get_flags(m);
3022   stackFrame->int_field_put(_flags_offset, flags);
3023 }
3024 
3025 
3026 // java_lang_StackFrameInfo
3027 
3028 int java_lang_StackFrameInfo::_type_offset;
3029 int java_lang_StackFrameInfo::_name_offset;
3030 int java_lang_StackFrameInfo::_bci_offset;
3031 int java_lang_StackFrameInfo::_version_offset;
3032 int java_lang_StackFrameInfo::_contScope_offset;
3033 
3034 #define STACKFRAMEINFO_FIELDS_DO(macro) \
3035   macro(_type_offset,       k, "type",       object_signature,            false); \
3036   macro(_name_offset,       k, "name",       string_signature,            false); \
3037   macro(_bci_offset,        k, "bci",        int_signature,               false); \
3038   macro(_contScope_offset,  k, "contScope",  continuationscope_signature, false)
3039 
3040 void java_lang_StackFrameInfo::compute_offsets() {
3041   InstanceKlass* k = vmClasses::StackFrameInfo_klass();
3042   STACKFRAMEINFO_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3043   STACKFRAMEINFO_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
3044 }
3045 
3046 #if INCLUDE_CDS
3047 void java_lang_StackFrameInfo::serialize_offsets(SerializeClosure* f) {
3048   STACKFRAMEINFO_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3049   STACKFRAMEINFO_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
3050 }
3051 #endif
3052 
3053 Method* java_lang_StackFrameInfo::get_method(oop obj) {
3054   oop m = java_lang_ClassFrameInfo::classOrMemberName(obj);
3055   Method* method = java_lang_invoke_ResolvedMethodName::vmtarget(m);
3056   return method;
3057 }
3058 
3059 void java_lang_StackFrameInfo::set_method_and_bci(Handle stackFrame, const methodHandle& method, int bci, oop cont, TRAPS) {
3060   // set Method* or mid/cpref
3061   HandleMark hm(THREAD);
3062   Handle cont_h(THREAD, cont);
3063   java_lang_ClassFrameInfo::init_method(stackFrame, method, CHECK);
3064 
3065   // set bci
3066   java_lang_StackFrameInfo::set_bci(stackFrame(), bci);
3067   // method may be redefined; store the version
3068   int version = method->constants()->version();
3069   assert((jushort)version == version, "version should be short");
3070   java_lang_StackFrameInfo::set_version(stackFrame(), (short)version);
3071 
3072   oop contScope = cont_h() != nullptr ? jdk_internal_vm_Continuation::scope(cont_h()) : (oop)nullptr;
3073   java_lang_StackFrameInfo::set_contScope(stackFrame(), contScope);
3074 }
3075 
3076 void java_lang_StackFrameInfo::to_stack_trace_element(Handle stackFrame, Handle stack_trace_element, TRAPS) {
3077   ResourceMark rm(THREAD);
3078   HandleMark hm(THREAD);
3079 
3080   Method* method = java_lang_StackFrameInfo::get_method(stackFrame());
3081   InstanceKlass* holder = method->method_holder();
3082   short version = stackFrame->short_field(_version_offset);
3083   int bci = stackFrame->int_field(_bci_offset);
3084   Symbol* name = method->name();
3085   java_lang_StackTraceElement::fill_in(stack_trace_element, holder, methodHandle(THREAD, method), version, bci, name, CHECK);
3086 }
3087 
3088 oop java_lang_StackFrameInfo::type(oop obj) {
3089   return obj->obj_field(_type_offset);
3090 }
3091 
3092 void java_lang_StackFrameInfo::set_type(oop obj, oop value) {
3093   obj->obj_field_put(_type_offset, value);
3094 }
3095 
3096 oop java_lang_StackFrameInfo::name(oop obj) {
3097   return obj->obj_field(_name_offset);
3098 }
3099 
3100 void java_lang_StackFrameInfo::set_name(oop obj, oop value) {
3101   obj->obj_field_put(_name_offset, value);
3102 }
3103 
3104 void java_lang_StackFrameInfo::set_version(oop obj, short value) {
3105   obj->short_field_put(_version_offset, value);
3106 }
3107 
3108 void java_lang_StackFrameInfo::set_bci(oop obj, int value) {
3109   assert(value >= 0 && value < max_jushort, "must be a valid bci value");
3110   obj->int_field_put(_bci_offset, value);
3111 }
3112 
3113 void java_lang_StackFrameInfo::set_contScope(oop obj, oop value) {
3114   obj->obj_field_put(_contScope_offset, value);
3115 }
3116 
3117 int java_lang_LiveStackFrameInfo::_monitors_offset;
3118 int java_lang_LiveStackFrameInfo::_locals_offset;
3119 int java_lang_LiveStackFrameInfo::_operands_offset;
3120 int java_lang_LiveStackFrameInfo::_mode_offset;
3121 
3122 #define LIVESTACKFRAMEINFO_FIELDS_DO(macro) \
3123   macro(_monitors_offset,   k, "monitors",    object_array_signature, false); \
3124   macro(_locals_offset,     k, "locals",      object_array_signature, false); \
3125   macro(_operands_offset,   k, "operands",    object_array_signature, false); \
3126   macro(_mode_offset,       k, "mode",        int_signature,          false)
3127 
3128 void java_lang_LiveStackFrameInfo::compute_offsets() {
3129   InstanceKlass* k = vmClasses::LiveStackFrameInfo_klass();
3130   LIVESTACKFRAMEINFO_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3131 }
3132 
3133 #if INCLUDE_CDS
3134 void java_lang_LiveStackFrameInfo::serialize_offsets(SerializeClosure* f) {
3135   LIVESTACKFRAMEINFO_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3136 }
3137 #endif
3138 
3139 void java_lang_LiveStackFrameInfo::set_monitors(oop obj, oop value) {
3140   obj->obj_field_put(_monitors_offset, value);
3141 }
3142 
3143 void java_lang_LiveStackFrameInfo::set_locals(oop obj, oop value) {
3144   obj->obj_field_put(_locals_offset, value);
3145 }
3146 
3147 void java_lang_LiveStackFrameInfo::set_operands(oop obj, oop value) {
3148   obj->obj_field_put(_operands_offset, value);
3149 }
3150 
3151 void java_lang_LiveStackFrameInfo::set_mode(oop obj, int value) {
3152   obj->int_field_put(_mode_offset, value);
3153 }
3154 
3155 
3156 // java_lang_AccessibleObject
3157 
3158 int java_lang_reflect_AccessibleObject::_override_offset;
3159 
3160 #define ACCESSIBLEOBJECT_FIELDS_DO(macro) \
3161   macro(_override_offset, k, "override", bool_signature, false)
3162 
3163 void java_lang_reflect_AccessibleObject::compute_offsets() {
3164   InstanceKlass* k = vmClasses::reflect_AccessibleObject_klass();
3165   ACCESSIBLEOBJECT_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3166 }
3167 
3168 #if INCLUDE_CDS
3169 void java_lang_reflect_AccessibleObject::serialize_offsets(SerializeClosure* f) {
3170   ACCESSIBLEOBJECT_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3171 }
3172 #endif
3173 
3174 jboolean java_lang_reflect_AccessibleObject::override(oop reflect) {
3175   return (jboolean) reflect->bool_field(_override_offset);
3176 }
3177 
3178 void java_lang_reflect_AccessibleObject::set_override(oop reflect, jboolean value) {
3179   reflect->bool_field_put(_override_offset, (int) value);
3180 }
3181 
3182 // java_lang_reflect_Method
3183 
3184 int java_lang_reflect_Method::_clazz_offset;
3185 int java_lang_reflect_Method::_name_offset;
3186 int java_lang_reflect_Method::_returnType_offset;
3187 int java_lang_reflect_Method::_parameterTypes_offset;
3188 int java_lang_reflect_Method::_exceptionTypes_offset;
3189 int java_lang_reflect_Method::_slot_offset;
3190 int java_lang_reflect_Method::_modifiers_offset;
3191 int java_lang_reflect_Method::_signature_offset;
3192 int java_lang_reflect_Method::_annotations_offset;
3193 int java_lang_reflect_Method::_parameter_annotations_offset;
3194 int java_lang_reflect_Method::_annotation_default_offset;
3195 
3196 #define METHOD_FIELDS_DO(macro) \
3197   macro(_clazz_offset,          k, vmSymbols::clazz_name(),          class_signature,       false); \
3198   macro(_name_offset,           k, vmSymbols::name_name(),           string_signature,      false); \
3199   macro(_returnType_offset,     k, vmSymbols::returnType_name(),     class_signature,       false); \
3200   macro(_parameterTypes_offset, k, vmSymbols::parameterTypes_name(), class_array_signature, false); \
3201   macro(_exceptionTypes_offset, k, vmSymbols::exceptionTypes_name(), class_array_signature, false); \
3202   macro(_slot_offset,           k, vmSymbols::slot_name(),           int_signature,         false); \
3203   macro(_modifiers_offset,      k, vmSymbols::modifiers_name(),      int_signature,         false); \
3204   macro(_signature_offset,             k, vmSymbols::signature_name(),             string_signature,     false); \
3205   macro(_annotations_offset,           k, vmSymbols::annotations_name(),           byte_array_signature, false); \
3206   macro(_parameter_annotations_offset, k, vmSymbols::parameter_annotations_name(), byte_array_signature, false); \
3207   macro(_annotation_default_offset,    k, vmSymbols::annotation_default_name(),    byte_array_signature, false);
3208 
3209 void java_lang_reflect_Method::compute_offsets() {
3210   InstanceKlass* k = vmClasses::reflect_Method_klass();
3211   METHOD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3212 }
3213 
3214 #if INCLUDE_CDS
3215 void java_lang_reflect_Method::serialize_offsets(SerializeClosure* f) {
3216   METHOD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3217 }
3218 #endif
3219 
3220 Handle java_lang_reflect_Method::create(TRAPS) {
3221   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3222   Klass* klass = vmClasses::reflect_Method_klass();
3223   // This class is eagerly initialized during VM initialization, since we keep a reference
3224   // to one of the methods
3225   assert(InstanceKlass::cast(klass)->is_initialized(), "must be initialized");
3226   return InstanceKlass::cast(klass)->allocate_instance_handle(THREAD);
3227 }
3228 
3229 oop java_lang_reflect_Method::clazz(oop reflect) {
3230   return reflect->obj_field(_clazz_offset);
3231 }
3232 
3233 void java_lang_reflect_Method::set_clazz(oop reflect, oop value) {
3234    reflect->obj_field_put(_clazz_offset, value);
3235 }
3236 
3237 int java_lang_reflect_Method::slot(oop reflect) {
3238   return reflect->int_field(_slot_offset);
3239 }
3240 
3241 void java_lang_reflect_Method::set_slot(oop reflect, int value) {
3242   reflect->int_field_put(_slot_offset, value);
3243 }
3244 
3245 void java_lang_reflect_Method::set_name(oop method, oop value) {
3246   method->obj_field_put(_name_offset, value);
3247 }
3248 
3249 oop java_lang_reflect_Method::return_type(oop method) {
3250   return method->obj_field(_returnType_offset);
3251 }
3252 
3253 void java_lang_reflect_Method::set_return_type(oop method, oop value) {
3254   method->obj_field_put(_returnType_offset, value);
3255 }
3256 
3257 oop java_lang_reflect_Method::parameter_types(oop method) {
3258   return method->obj_field(_parameterTypes_offset);
3259 }
3260 
3261 void java_lang_reflect_Method::set_parameter_types(oop method, oop value) {
3262   method->obj_field_put(_parameterTypes_offset, value);
3263 }
3264 
3265 void java_lang_reflect_Method::set_exception_types(oop method, oop value) {
3266   method->obj_field_put(_exceptionTypes_offset, value);
3267 }
3268 
3269 void java_lang_reflect_Method::set_modifiers(oop method, int value) {
3270   method->int_field_put(_modifiers_offset, value);
3271 }
3272 
3273 void java_lang_reflect_Method::set_signature(oop method, oop value) {
3274   method->obj_field_put(_signature_offset, value);
3275 }
3276 
3277 void java_lang_reflect_Method::set_annotations(oop method, oop value) {
3278   method->obj_field_put(_annotations_offset, value);
3279 }
3280 
3281 void java_lang_reflect_Method::set_parameter_annotations(oop method, oop value) {
3282   method->obj_field_put(_parameter_annotations_offset, value);
3283 }
3284 
3285 void java_lang_reflect_Method::set_annotation_default(oop method, oop value) {
3286   method->obj_field_put(_annotation_default_offset, value);
3287 }
3288 
3289 int java_lang_reflect_Constructor::_clazz_offset;
3290 int java_lang_reflect_Constructor::_parameterTypes_offset;
3291 int java_lang_reflect_Constructor::_exceptionTypes_offset;
3292 int java_lang_reflect_Constructor::_slot_offset;
3293 int java_lang_reflect_Constructor::_modifiers_offset;
3294 int java_lang_reflect_Constructor::_signature_offset;
3295 int java_lang_reflect_Constructor::_annotations_offset;
3296 int java_lang_reflect_Constructor::_parameter_annotations_offset;
3297 
3298 #define CONSTRUCTOR_FIELDS_DO(macro) \
3299   macro(_clazz_offset,          k, vmSymbols::clazz_name(),          class_signature,       false); \
3300   macro(_parameterTypes_offset, k, vmSymbols::parameterTypes_name(), class_array_signature, false); \
3301   macro(_exceptionTypes_offset, k, vmSymbols::exceptionTypes_name(), class_array_signature, false); \
3302   macro(_slot_offset,           k, vmSymbols::slot_name(),           int_signature,         false); \
3303   macro(_modifiers_offset,      k, vmSymbols::modifiers_name(),      int_signature,         false); \
3304   macro(_signature_offset,             k, vmSymbols::signature_name(),             string_signature,     false); \
3305   macro(_annotations_offset,           k, vmSymbols::annotations_name(),           byte_array_signature, false); \
3306   macro(_parameter_annotations_offset, k, vmSymbols::parameter_annotations_name(), byte_array_signature, false);
3307 
3308 void java_lang_reflect_Constructor::compute_offsets() {
3309   InstanceKlass* k = vmClasses::reflect_Constructor_klass();
3310   CONSTRUCTOR_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3311 }
3312 
3313 #if INCLUDE_CDS
3314 void java_lang_reflect_Constructor::serialize_offsets(SerializeClosure* f) {
3315   CONSTRUCTOR_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3316 }
3317 #endif
3318 
3319 Handle java_lang_reflect_Constructor::create(TRAPS) {
3320   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3321   Symbol* name = vmSymbols::java_lang_reflect_Constructor();
3322   Klass* k = SystemDictionary::resolve_or_fail(name, true, CHECK_NH);
3323   InstanceKlass* ik = InstanceKlass::cast(k);
3324   // Ensure it is initialized
3325   ik->initialize(CHECK_NH);
3326   return ik->allocate_instance_handle(THREAD);
3327 }
3328 
3329 oop java_lang_reflect_Constructor::clazz(oop reflect) {
3330   return reflect->obj_field(_clazz_offset);
3331 }
3332 
3333 void java_lang_reflect_Constructor::set_clazz(oop reflect, oop value) {
3334    reflect->obj_field_put(_clazz_offset, value);
3335 }
3336 
3337 oop java_lang_reflect_Constructor::parameter_types(oop constructor) {
3338   return constructor->obj_field(_parameterTypes_offset);
3339 }
3340 
3341 void java_lang_reflect_Constructor::set_parameter_types(oop constructor, oop value) {
3342   constructor->obj_field_put(_parameterTypes_offset, value);
3343 }
3344 
3345 void java_lang_reflect_Constructor::set_exception_types(oop constructor, oop value) {
3346   constructor->obj_field_put(_exceptionTypes_offset, value);
3347 }
3348 
3349 int java_lang_reflect_Constructor::slot(oop reflect) {
3350   return reflect->int_field(_slot_offset);
3351 }
3352 
3353 void java_lang_reflect_Constructor::set_slot(oop reflect, int value) {
3354   reflect->int_field_put(_slot_offset, value);
3355 }
3356 
3357 void java_lang_reflect_Constructor::set_modifiers(oop constructor, int value) {
3358   constructor->int_field_put(_modifiers_offset, value);
3359 }
3360 
3361 void java_lang_reflect_Constructor::set_signature(oop constructor, oop value) {
3362   constructor->obj_field_put(_signature_offset, value);
3363 }
3364 
3365 void java_lang_reflect_Constructor::set_annotations(oop constructor, oop value) {
3366   constructor->obj_field_put(_annotations_offset, value);
3367 }
3368 
3369 void java_lang_reflect_Constructor::set_parameter_annotations(oop method, oop value) {
3370   method->obj_field_put(_parameter_annotations_offset, value);
3371 }
3372 
3373 int java_lang_reflect_Field::_clazz_offset;
3374 int java_lang_reflect_Field::_name_offset;
3375 int java_lang_reflect_Field::_type_offset;
3376 int java_lang_reflect_Field::_slot_offset;
3377 int java_lang_reflect_Field::_modifiers_offset;
3378 int java_lang_reflect_Field::_trusted_final_offset;
3379 int java_lang_reflect_Field::_signature_offset;
3380 int java_lang_reflect_Field::_annotations_offset;
3381 
3382 #define FIELD_FIELDS_DO(macro) \
3383   macro(_clazz_offset,     k, vmSymbols::clazz_name(),     class_signature,  false); \
3384   macro(_name_offset,      k, vmSymbols::name_name(),      string_signature, false); \
3385   macro(_type_offset,      k, vmSymbols::type_name(),      class_signature,  false); \
3386   macro(_slot_offset,      k, vmSymbols::slot_name(),      int_signature,    false); \
3387   macro(_modifiers_offset, k, vmSymbols::modifiers_name(), int_signature,    false); \
3388   macro(_trusted_final_offset,    k, vmSymbols::trusted_final_name(),    bool_signature,       false); \
3389   macro(_signature_offset,        k, vmSymbols::signature_name(),        string_signature,     false); \
3390   macro(_annotations_offset,      k, vmSymbols::annotations_name(),      byte_array_signature, false);
3391 
3392 void java_lang_reflect_Field::compute_offsets() {
3393   InstanceKlass* k = vmClasses::reflect_Field_klass();
3394   FIELD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3395 }
3396 
3397 #if INCLUDE_CDS
3398 void java_lang_reflect_Field::serialize_offsets(SerializeClosure* f) {
3399   FIELD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3400 }
3401 #endif
3402 
3403 Handle java_lang_reflect_Field::create(TRAPS) {
3404   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3405   Symbol* name = vmSymbols::java_lang_reflect_Field();
3406   Klass* k = SystemDictionary::resolve_or_fail(name, true, CHECK_NH);
3407   InstanceKlass* ik = InstanceKlass::cast(k);
3408   // Ensure it is initialized
3409   ik->initialize(CHECK_NH);
3410   return ik->allocate_instance_handle(THREAD);
3411 }
3412 
3413 oop java_lang_reflect_Field::clazz(oop reflect) {
3414   return reflect->obj_field(_clazz_offset);
3415 }
3416 
3417 void java_lang_reflect_Field::set_clazz(oop reflect, oop value) {
3418   reflect->obj_field_put(_clazz_offset, value);
3419 }
3420 
3421 oop java_lang_reflect_Field::name(oop field) {
3422   return field->obj_field(_name_offset);
3423 }
3424 
3425 void java_lang_reflect_Field::set_name(oop field, oop value) {
3426   field->obj_field_put(_name_offset, value);
3427 }
3428 
3429 oop java_lang_reflect_Field::type(oop field) {
3430   return field->obj_field(_type_offset);
3431 }
3432 
3433 void java_lang_reflect_Field::set_type(oop field, oop value) {
3434   field->obj_field_put(_type_offset, value);
3435 }
3436 
3437 int java_lang_reflect_Field::slot(oop reflect) {
3438   return reflect->int_field(_slot_offset);
3439 }
3440 
3441 void java_lang_reflect_Field::set_slot(oop reflect, int value) {
3442   reflect->int_field_put(_slot_offset, value);
3443 }
3444 
3445 int java_lang_reflect_Field::modifiers(oop field) {
3446   return field->int_field(_modifiers_offset);
3447 }
3448 
3449 void java_lang_reflect_Field::set_modifiers(oop field, int value) {
3450   field->int_field_put(_modifiers_offset, value);
3451 }
3452 
3453 void java_lang_reflect_Field::set_trusted_final(oop field) {
3454   field->bool_field_put(_trusted_final_offset, true);
3455 }
3456 
3457 void java_lang_reflect_Field::set_signature(oop field, oop value) {
3458   field->obj_field_put(_signature_offset, value);
3459 }
3460 
3461 void java_lang_reflect_Field::set_annotations(oop field, oop value) {
3462   field->obj_field_put(_annotations_offset, value);
3463 }
3464 
3465 oop java_lang_reflect_RecordComponent::create(InstanceKlass* holder, RecordComponent* component, TRAPS) {
3466   // Allocate java.lang.reflect.RecordComponent instance
3467   HandleMark hm(THREAD);
3468   InstanceKlass* ik = vmClasses::RecordComponent_klass();
3469   assert(ik != nullptr, "must be loaded");
3470   ik->initialize(CHECK_NULL);
3471 
3472   Handle element = ik->allocate_instance_handle(CHECK_NULL);
3473 
3474   Handle decl_class(THREAD, holder->java_mirror());
3475   java_lang_reflect_RecordComponent::set_clazz(element(), decl_class());
3476 
3477   Symbol* name = holder->constants()->symbol_at(component->name_index()); // name_index is a utf8
3478   oop component_name = StringTable::intern(name, CHECK_NULL);
3479   java_lang_reflect_RecordComponent::set_name(element(), component_name);
3480 
3481   Symbol* type = holder->constants()->symbol_at(component->descriptor_index());
3482   Handle component_type_h =
3483     SystemDictionary::find_java_mirror_for_type(type, holder, SignatureStream::NCDFError, CHECK_NULL);
3484   java_lang_reflect_RecordComponent::set_type(element(), component_type_h());
3485 
3486   Method* accessor_method = nullptr;
3487   {
3488     // Prepend "()" to type to create the full method signature.
3489     ResourceMark rm(THREAD);
3490     int sig_len = type->utf8_length() + 3; // "()" and null char
3491     char* sig = NEW_RESOURCE_ARRAY(char, sig_len);
3492     jio_snprintf(sig, sig_len, "%c%c%s", JVM_SIGNATURE_FUNC, JVM_SIGNATURE_ENDFUNC, type->as_C_string());
3493     TempNewSymbol full_sig = SymbolTable::new_symbol(sig);
3494     accessor_method = holder->find_instance_method(name, full_sig, Klass::PrivateLookupMode::find);
3495   }
3496 
3497   if (accessor_method != nullptr) {
3498     methodHandle method(THREAD, accessor_method);
3499     oop m = Reflection::new_method(method, false, CHECK_NULL);
3500     java_lang_reflect_RecordComponent::set_accessor(element(), m);
3501   } else {
3502     java_lang_reflect_RecordComponent::set_accessor(element(), nullptr);
3503   }
3504 
3505   int sig_index = component->generic_signature_index();
3506   if (sig_index > 0) {
3507     Symbol* sig = holder->constants()->symbol_at(sig_index); // sig_index is a utf8
3508     oop component_sig = StringTable::intern(sig, CHECK_NULL);
3509     java_lang_reflect_RecordComponent::set_signature(element(), component_sig);
3510   } else {
3511     java_lang_reflect_RecordComponent::set_signature(element(), nullptr);
3512   }
3513 
3514   typeArrayOop annotation_oop = Annotations::make_java_array(component->annotations(), CHECK_NULL);
3515   java_lang_reflect_RecordComponent::set_annotations(element(), annotation_oop);
3516 
3517   typeArrayOop type_annotation_oop = Annotations::make_java_array(component->type_annotations(), CHECK_NULL);
3518   java_lang_reflect_RecordComponent::set_typeAnnotations(element(), type_annotation_oop);
3519 
3520   return element();
3521 }
3522 
3523 int reflect_ConstantPool::_oop_offset;
3524 
3525 #define CONSTANTPOOL_FIELDS_DO(macro) \
3526   macro(_oop_offset, k, "constantPoolOop", object_signature, false)
3527 
3528 void reflect_ConstantPool::compute_offsets() {
3529   InstanceKlass* k = vmClasses::reflect_ConstantPool_klass();
3530   // The field is called ConstantPool* in the sun.reflect.ConstantPool class.
3531   CONSTANTPOOL_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3532 }
3533 
3534 #if INCLUDE_CDS
3535 void reflect_ConstantPool::serialize_offsets(SerializeClosure* f) {
3536   CONSTANTPOOL_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3537 }
3538 #endif
3539 
3540 int java_lang_reflect_Parameter::_name_offset;
3541 int java_lang_reflect_Parameter::_modifiers_offset;
3542 int java_lang_reflect_Parameter::_index_offset;
3543 int java_lang_reflect_Parameter::_executable_offset;
3544 
3545 #define PARAMETER_FIELDS_DO(macro) \
3546   macro(_name_offset,        k, vmSymbols::name_name(),        string_signature, false); \
3547   macro(_modifiers_offset,   k, vmSymbols::modifiers_name(),   int_signature,    false); \
3548   macro(_index_offset,       k, vmSymbols::index_name(),       int_signature,    false); \
3549   macro(_executable_offset,  k, vmSymbols::executable_name(),  executable_signature, false)
3550 
3551 void java_lang_reflect_Parameter::compute_offsets() {
3552   InstanceKlass* k = vmClasses::reflect_Parameter_klass();
3553   PARAMETER_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3554 }
3555 
3556 #if INCLUDE_CDS
3557 void java_lang_reflect_Parameter::serialize_offsets(SerializeClosure* f) {
3558   PARAMETER_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3559 }
3560 #endif
3561 
3562 Handle java_lang_reflect_Parameter::create(TRAPS) {
3563   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3564   Symbol* name = vmSymbols::java_lang_reflect_Parameter();
3565   Klass* k = SystemDictionary::resolve_or_fail(name, true, CHECK_NH);
3566   InstanceKlass* ik = InstanceKlass::cast(k);
3567   // Ensure it is initialized
3568   ik->initialize(CHECK_NH);
3569   return ik->allocate_instance_handle(THREAD);
3570 }
3571 
3572 oop java_lang_reflect_Parameter::name(oop param) {
3573   return param->obj_field(_name_offset);
3574 }
3575 
3576 void java_lang_reflect_Parameter::set_name(oop param, oop value) {
3577   param->obj_field_put(_name_offset, value);
3578 }
3579 
3580 int java_lang_reflect_Parameter::modifiers(oop param) {
3581   return param->int_field(_modifiers_offset);
3582 }
3583 
3584 void java_lang_reflect_Parameter::set_modifiers(oop param, int value) {
3585   param->int_field_put(_modifiers_offset, value);
3586 }
3587 
3588 int java_lang_reflect_Parameter::index(oop param) {
3589   return param->int_field(_index_offset);
3590 }
3591 
3592 void java_lang_reflect_Parameter::set_index(oop param, int value) {
3593   param->int_field_put(_index_offset, value);
3594 }
3595 
3596 oop java_lang_reflect_Parameter::executable(oop param) {
3597   return param->obj_field(_executable_offset);
3598 }
3599 
3600 void java_lang_reflect_Parameter::set_executable(oop param, oop value) {
3601   param->obj_field_put(_executable_offset, value);
3602 }
3603 
3604 // java_lang_Module
3605 
3606 int java_lang_Module::_loader_offset;
3607 int java_lang_Module::_name_offset;
3608 int java_lang_Module::_module_entry_offset;
3609 
3610 Handle java_lang_Module::create(Handle loader, Handle module_name, TRAPS) {
3611   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3612   return JavaCalls::construct_new_instance(vmClasses::Module_klass(),
3613                           vmSymbols::java_lang_module_init_signature(),
3614                           loader, module_name, CHECK_NH);
3615 }
3616 
3617 #define MODULE_FIELDS_DO(macro) \
3618   macro(_loader_offset,  k, vmSymbols::loader_name(),  classloader_signature, false); \
3619   macro(_name_offset,    k, vmSymbols::name_name(),    string_signature,      false)
3620 
3621 void java_lang_Module::compute_offsets() {
3622   InstanceKlass* k = vmClasses::Module_klass();
3623   MODULE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3624   MODULE_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
3625 }
3626 
3627 #if INCLUDE_CDS
3628 void java_lang_Module::serialize_offsets(SerializeClosure* f) {
3629   MODULE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3630   MODULE_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
3631 }
3632 #endif
3633 
3634 oop java_lang_Module::loader(oop module) {
3635   return module->obj_field(_loader_offset);
3636 }
3637 
3638 void java_lang_Module::set_loader(oop module, oop value) {
3639   module->obj_field_put(_loader_offset, value);
3640 }
3641 
3642 oop java_lang_Module::name(oop module) {
3643   return module->obj_field(_name_offset);
3644 }
3645 
3646 void java_lang_Module::set_name(oop module, oop value) {
3647   module->obj_field_put(_name_offset, value);
3648 }
3649 
3650 ModuleEntry* java_lang_Module::module_entry_raw(oop module) {
3651   assert(_module_entry_offset != 0, "Uninitialized module_entry_offset");
3652   assert(module != nullptr, "module can't be null");
3653   assert(oopDesc::is_oop(module), "module must be oop");
3654 
3655   ModuleEntry* module_entry = (ModuleEntry*)module->address_field(_module_entry_offset);
3656   return module_entry;
3657 }
3658 
3659 ModuleEntry* java_lang_Module::module_entry(oop module) {
3660   ModuleEntry* module_entry = module_entry_raw(module);
3661   if (module_entry == nullptr) {
3662     // If the inject field containing the ModuleEntry* is null then return the
3663     // class loader's unnamed module.
3664     oop loader = java_lang_Module::loader(module);
3665     Handle h_loader = Handle(Thread::current(), loader);
3666     ClassLoaderData* loader_cld = SystemDictionary::register_loader(h_loader);
3667     return loader_cld->unnamed_module();
3668   }
3669   return module_entry;
3670 }
3671 
3672 void java_lang_Module::set_module_entry(oop module, ModuleEntry* module_entry) {
3673   assert(_module_entry_offset != 0, "Uninitialized module_entry_offset");
3674   assert(module != nullptr, "module can't be null");
3675   assert(oopDesc::is_oop(module), "module must be oop");
3676   module->address_field_put(_module_entry_offset, (address)module_entry);
3677 }
3678 
3679 Handle reflect_ConstantPool::create(TRAPS) {
3680   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
3681   InstanceKlass* k = vmClasses::reflect_ConstantPool_klass();
3682   // Ensure it is initialized
3683   k->initialize(CHECK_NH);
3684   return k->allocate_instance_handle(THREAD);
3685 }
3686 
3687 
3688 void reflect_ConstantPool::set_cp(oop reflect, ConstantPool* value) {
3689   oop mirror = value->pool_holder()->java_mirror();
3690   // Save the mirror to get back the constant pool.
3691   reflect->obj_field_put(_oop_offset, mirror);
3692 }
3693 
3694 ConstantPool* reflect_ConstantPool::get_cp(oop reflect) {
3695 
3696   oop mirror = reflect->obj_field(_oop_offset);
3697   Klass* k = java_lang_Class::as_Klass(mirror);
3698   assert(k->is_instance_klass(), "Must be");
3699 
3700   // Get the constant pool back from the klass.  Since class redefinition
3701   // merges the new constant pool into the old, this is essentially the
3702   // same constant pool as the original.  If constant pool merging is
3703   // no longer done in the future, this will have to change to save
3704   // the original.
3705   return InstanceKlass::cast(k)->constants();
3706 }
3707 
3708 
3709 // Support for java_lang_ref_Reference
3710 
3711 bool java_lang_ref_Reference::_offsets_initialized;
3712 
3713 int java_lang_ref_Reference::_referent_offset;
3714 int java_lang_ref_Reference::_queue_offset;
3715 int java_lang_ref_Reference::_next_offset;
3716 int java_lang_ref_Reference::_discovered_offset;
3717 
3718 #define REFERENCE_FIELDS_DO(macro) \
3719   macro(_referent_offset,   k, "referent", object_signature, false); \
3720   macro(_queue_offset,      k, "queue", referencequeue_signature, false); \
3721   macro(_next_offset,       k, "next", reference_signature, false); \
3722   macro(_discovered_offset, k, "discovered", reference_signature, false);
3723 
3724 void java_lang_ref_Reference::compute_offsets() {
3725   if (_offsets_initialized) {
3726     return;
3727   }
3728   _offsets_initialized = true;
3729   InstanceKlass* k = vmClasses::Reference_klass();
3730   REFERENCE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3731 }
3732 
3733 #if INCLUDE_CDS
3734 void java_lang_ref_Reference::serialize_offsets(SerializeClosure* f) {
3735   f->do_bool(&_offsets_initialized);
3736   REFERENCE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3737 }
3738 #endif
3739 
3740 bool java_lang_ref_Reference::is_referent_field(oop obj, ptrdiff_t offset) {
3741   assert(obj != nullptr, "sanity");
3742   if (offset != _referent_offset) {
3743     return false;
3744   }
3745 
3746   Klass* k = obj->klass();
3747   if (!k->is_instance_klass()) {
3748     return false;
3749   }
3750 
3751   InstanceKlass* ik = InstanceKlass::cast(obj->klass());
3752   bool is_reference = ik->reference_type() != REF_NONE;
3753   assert(!is_reference || ik->is_subclass_of(vmClasses::Reference_klass()), "sanity");
3754   return is_reference;
3755 }
3756 
3757 int java_lang_boxing_object::_value_offset;
3758 int java_lang_boxing_object::_long_value_offset;
3759 
3760 #define BOXING_FIELDS_DO(macro) \
3761   macro(_value_offset,      integerKlass, "value", int_signature, false); \
3762   macro(_long_value_offset, longKlass, "value", long_signature, false);
3763 
3764 void java_lang_boxing_object::compute_offsets() {
3765   InstanceKlass* integerKlass = vmClasses::Integer_klass();
3766   InstanceKlass* longKlass = vmClasses::Long_klass();
3767   BOXING_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3768 }
3769 
3770 #if INCLUDE_CDS
3771 void java_lang_boxing_object::serialize_offsets(SerializeClosure* f) {
3772   BOXING_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3773 }
3774 #endif
3775 
3776 oop java_lang_boxing_object::initialize_and_allocate(BasicType type, TRAPS) {
3777   Klass* k = vmClasses::box_klass(type);
3778   if (k == nullptr)  return nullptr;
3779   InstanceKlass* ik = InstanceKlass::cast(k);
3780   if (!ik->is_initialized()) {
3781     ik->initialize(CHECK_NULL);
3782   }
3783   return ik->allocate_instance(THREAD);
3784 }
3785 
3786 
3787 oop java_lang_boxing_object::create(BasicType type, jvalue* value, TRAPS) {
3788   oop box = initialize_and_allocate(type, CHECK_NULL);
3789   if (box == nullptr)  return nullptr;
3790   switch (type) {
3791     case T_BOOLEAN:
3792       box->bool_field_put(_value_offset, value->z);
3793       break;
3794     case T_CHAR:
3795       box->char_field_put(_value_offset, value->c);
3796       break;
3797     case T_FLOAT:
3798       box->float_field_put(_value_offset, value->f);
3799       break;
3800     case T_DOUBLE:
3801       box->double_field_put(_long_value_offset, value->d);
3802       break;
3803     case T_BYTE:
3804       box->byte_field_put(_value_offset, value->b);
3805       break;
3806     case T_SHORT:
3807       box->short_field_put(_value_offset, value->s);
3808       break;
3809     case T_INT:
3810       box->int_field_put(_value_offset, value->i);
3811       break;
3812     case T_LONG:
3813       box->long_field_put(_long_value_offset, value->j);
3814       break;
3815     default:
3816       return nullptr;
3817   }
3818   return box;
3819 }
3820 
3821 
3822 BasicType java_lang_boxing_object::basic_type(oop box) {
3823   if (box == nullptr)  return T_ILLEGAL;
3824   BasicType type = vmClasses::box_klass_type(box->klass());
3825   if (type == T_OBJECT)         // 'unknown' value returned by SD::bkt
3826     return T_ILLEGAL;
3827   return type;
3828 }
3829 
3830 
3831 BasicType java_lang_boxing_object::get_value(oop box, jvalue* value) {
3832   BasicType type = vmClasses::box_klass_type(box->klass());
3833   switch (type) {
3834   case T_BOOLEAN:
3835     value->z = box->bool_field(_value_offset);
3836     break;
3837   case T_CHAR:
3838     value->c = box->char_field(_value_offset);
3839     break;
3840   case T_FLOAT:
3841     value->f = box->float_field(_value_offset);
3842     break;
3843   case T_DOUBLE:
3844     value->d = box->double_field(_long_value_offset);
3845     break;
3846   case T_BYTE:
3847     value->b = box->byte_field(_value_offset);
3848     break;
3849   case T_SHORT:
3850     value->s = box->short_field(_value_offset);
3851     break;
3852   case T_INT:
3853     value->i = box->int_field(_value_offset);
3854     break;
3855   case T_LONG:
3856     value->j = box->long_field(_long_value_offset);
3857     break;
3858   default:
3859     return T_ILLEGAL;
3860   } // end switch
3861   return type;
3862 }
3863 
3864 
3865 BasicType java_lang_boxing_object::set_value(oop box, jvalue* value) {
3866   BasicType type = vmClasses::box_klass_type(box->klass());
3867   switch (type) {
3868   case T_BOOLEAN:
3869     box->bool_field_put(_value_offset, value->z);
3870     break;
3871   case T_CHAR:
3872     box->char_field_put(_value_offset, value->c);
3873     break;
3874   case T_FLOAT:
3875     box->float_field_put(_value_offset, value->f);
3876     break;
3877   case T_DOUBLE:
3878     box->double_field_put(_long_value_offset, value->d);
3879     break;
3880   case T_BYTE:
3881     box->byte_field_put(_value_offset, value->b);
3882     break;
3883   case T_SHORT:
3884     box->short_field_put(_value_offset, value->s);
3885     break;
3886   case T_INT:
3887     box->int_field_put(_value_offset, value->i);
3888     break;
3889   case T_LONG:
3890     box->long_field_put(_long_value_offset, value->j);
3891     break;
3892   default:
3893     return T_ILLEGAL;
3894   } // end switch
3895   return type;
3896 }
3897 
3898 
3899 void java_lang_boxing_object::print(BasicType type, jvalue* value, outputStream* st) {
3900   switch (type) {
3901   case T_BOOLEAN:   st->print("%s", value->z ? "true" : "false");   break;
3902   case T_CHAR:      st->print("%d", value->c);                      break;
3903   case T_BYTE:      st->print("%d", value->b);                      break;
3904   case T_SHORT:     st->print("%d", value->s);                      break;
3905   case T_INT:       st->print("%d", value->i);                      break;
3906   case T_LONG:      st->print(JLONG_FORMAT, value->j);              break;
3907   case T_FLOAT:     st->print("%f", value->f);                      break;
3908   case T_DOUBLE:    st->print("%lf", value->d);                     break;
3909   default:          st->print("type %d?", type);                    break;
3910   }
3911 }
3912 
3913 
3914 // Support for java_lang_ref_SoftReference
3915 //
3916 
3917 int java_lang_ref_SoftReference::_timestamp_offset;
3918 int java_lang_ref_SoftReference::_static_clock_offset;
3919 
3920 #define SOFTREFERENCE_FIELDS_DO(macro) \
3921   macro(_timestamp_offset,    k, "timestamp", long_signature, false); \
3922   macro(_static_clock_offset, k, "clock",     long_signature, true)
3923 
3924 void java_lang_ref_SoftReference::compute_offsets() {
3925   InstanceKlass* k = vmClasses::SoftReference_klass();
3926   SOFTREFERENCE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3927 }
3928 
3929 #if INCLUDE_CDS
3930 void java_lang_ref_SoftReference::serialize_offsets(SerializeClosure* f) {
3931   SOFTREFERENCE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3932 }
3933 #endif
3934 
3935 jlong java_lang_ref_SoftReference::timestamp(oop ref) {
3936   return ref->long_field(_timestamp_offset);
3937 }
3938 
3939 jlong java_lang_ref_SoftReference::clock() {
3940   InstanceKlass* ik = vmClasses::SoftReference_klass();
3941   oop base = ik->static_field_base_raw();
3942   return base->long_field(_static_clock_offset);
3943 }
3944 
3945 void java_lang_ref_SoftReference::set_clock(jlong value) {
3946   InstanceKlass* ik = vmClasses::SoftReference_klass();
3947   oop base = ik->static_field_base_raw();
3948   base->long_field_put(_static_clock_offset, value);
3949 }
3950 
3951 // Support for java_lang_invoke_DirectMethodHandle
3952 
3953 int java_lang_invoke_DirectMethodHandle::_member_offset;
3954 
3955 oop java_lang_invoke_DirectMethodHandle::member(oop dmh) {
3956   oop member_name = nullptr;
3957   assert(oopDesc::is_oop(dmh) && java_lang_invoke_DirectMethodHandle::is_instance(dmh),
3958          "a DirectMethodHandle oop is expected");
3959   return dmh->obj_field(_member_offset);
3960 }
3961 
3962 #define DIRECTMETHODHANDLE_FIELDS_DO(macro) \
3963   macro(_member_offset, k, "member", java_lang_invoke_MemberName_signature, false)
3964 
3965 void java_lang_invoke_DirectMethodHandle::compute_offsets() {
3966   InstanceKlass* k = vmClasses::DirectMethodHandle_klass();
3967   DIRECTMETHODHANDLE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
3968 }
3969 
3970 #if INCLUDE_CDS
3971 void java_lang_invoke_DirectMethodHandle::serialize_offsets(SerializeClosure* f) {
3972   DIRECTMETHODHANDLE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
3973 }
3974 #endif
3975 
3976 // Support for java_lang_invoke_MethodHandle
3977 
3978 int java_lang_invoke_MethodHandle::_type_offset;
3979 int java_lang_invoke_MethodHandle::_form_offset;
3980 
3981 int java_lang_invoke_MemberName::_clazz_offset;
3982 int java_lang_invoke_MemberName::_name_offset;
3983 int java_lang_invoke_MemberName::_type_offset;
3984 int java_lang_invoke_MemberName::_flags_offset;
3985 int java_lang_invoke_MemberName::_method_offset;
3986 int java_lang_invoke_MemberName::_vmindex_offset;
3987 
3988 int java_lang_invoke_ResolvedMethodName::_vmtarget_offset;
3989 int java_lang_invoke_ResolvedMethodName::_vmholder_offset;
3990 
3991 int java_lang_invoke_LambdaForm::_vmentry_offset;
3992 
3993 #define METHODHANDLE_FIELDS_DO(macro) \
3994   macro(_type_offset, k, vmSymbols::type_name(), java_lang_invoke_MethodType_signature, false); \
3995   macro(_form_offset, k, "form",                 java_lang_invoke_LambdaForm_signature, false)
3996 
3997 void java_lang_invoke_MethodHandle::compute_offsets() {
3998   InstanceKlass* k = vmClasses::MethodHandle_klass();
3999   METHODHANDLE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4000 }
4001 
4002 #if INCLUDE_CDS
4003 void java_lang_invoke_MethodHandle::serialize_offsets(SerializeClosure* f) {
4004   METHODHANDLE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4005 }
4006 #endif
4007 
4008 #define MEMBERNAME_FIELDS_DO(macro) \
4009   macro(_clazz_offset,   k, vmSymbols::clazz_name(),   class_signature,  false); \
4010   macro(_name_offset,    k, vmSymbols::name_name(),    string_signature, false); \
4011   macro(_type_offset,    k, vmSymbols::type_name(),    object_signature, false); \
4012   macro(_flags_offset,   k, vmSymbols::flags_name(),   int_signature,    false); \
4013   macro(_method_offset,  k, vmSymbols::method_name(),  java_lang_invoke_ResolvedMethodName_signature, false)
4014 
4015 void java_lang_invoke_MemberName::compute_offsets() {
4016   InstanceKlass* k = vmClasses::MemberName_klass();
4017   MEMBERNAME_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4018   MEMBERNAME_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
4019 }
4020 
4021 #if INCLUDE_CDS
4022 void java_lang_invoke_MemberName::serialize_offsets(SerializeClosure* f) {
4023   MEMBERNAME_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4024   MEMBERNAME_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
4025 }
4026 #endif
4027 
4028 #define RESOLVEDMETHOD_FIELDS_DO(macro) \
4029   macro(_vmholder_offset, k, "vmholder", class_signature, false)
4030 
4031 void java_lang_invoke_ResolvedMethodName::compute_offsets() {
4032   InstanceKlass* k = vmClasses::ResolvedMethodName_klass();
4033   assert(k != nullptr, "jdk mismatch");
4034   RESOLVEDMETHOD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4035   RESOLVEDMETHOD_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
4036 }
4037 
4038 #if INCLUDE_CDS
4039 void java_lang_invoke_ResolvedMethodName::serialize_offsets(SerializeClosure* f) {
4040   RESOLVEDMETHOD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4041   RESOLVEDMETHOD_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
4042 }
4043 #endif
4044 
4045 #define LAMBDAFORM_FIELDS_DO(macro) \
4046   macro(_vmentry_offset, k, "vmentry", java_lang_invoke_MemberName_signature, false)
4047 
4048 void java_lang_invoke_LambdaForm::compute_offsets() {
4049   InstanceKlass* k = vmClasses::LambdaForm_klass();
4050   assert (k != nullptr, "jdk mismatch");
4051   LAMBDAFORM_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4052 }
4053 
4054 #if INCLUDE_CDS
4055 void java_lang_invoke_LambdaForm::serialize_offsets(SerializeClosure* f) {
4056   LAMBDAFORM_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4057 }
4058 #endif
4059 
4060 bool java_lang_invoke_LambdaForm::is_instance(oop obj) {
4061   return obj != nullptr && is_subclass(obj->klass());
4062 }
4063 
4064 int jdk_internal_foreign_abi_NativeEntryPoint::_method_type_offset;
4065 int jdk_internal_foreign_abi_NativeEntryPoint::_downcall_stub_address_offset;
4066 
4067 #define NEP_FIELDS_DO(macro) \
4068   macro(_method_type_offset,           k, "methodType",          java_lang_invoke_MethodType_signature, false); \
4069   macro(_downcall_stub_address_offset, k, "downcallStubAddress", long_signature, false);
4070 
4071 bool jdk_internal_foreign_abi_NativeEntryPoint::is_instance(oop obj) {
4072   return obj != nullptr && is_subclass(obj->klass());
4073 }
4074 
4075 void jdk_internal_foreign_abi_NativeEntryPoint::compute_offsets() {
4076   InstanceKlass* k = vmClasses::NativeEntryPoint_klass();
4077   NEP_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4078 }
4079 
4080 #if INCLUDE_CDS
4081 void jdk_internal_foreign_abi_NativeEntryPoint::serialize_offsets(SerializeClosure* f) {
4082   NEP_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4083 }
4084 #endif
4085 
4086 oop jdk_internal_foreign_abi_NativeEntryPoint::method_type(oop entry) {
4087   return entry->obj_field(_method_type_offset);
4088 }
4089 
4090 jlong jdk_internal_foreign_abi_NativeEntryPoint::downcall_stub_address(oop entry) {
4091   return entry->long_field(_downcall_stub_address_offset);
4092 }
4093 
4094 int jdk_internal_foreign_abi_ABIDescriptor::_inputStorage_offset;
4095 int jdk_internal_foreign_abi_ABIDescriptor::_outputStorage_offset;
4096 int jdk_internal_foreign_abi_ABIDescriptor::_volatileStorage_offset;
4097 int jdk_internal_foreign_abi_ABIDescriptor::_stackAlignment_offset;
4098 int jdk_internal_foreign_abi_ABIDescriptor::_shadowSpace_offset;
4099 int jdk_internal_foreign_abi_ABIDescriptor::_scratch1_offset;
4100 int jdk_internal_foreign_abi_ABIDescriptor::_scratch2_offset;
4101 
4102 #define ABIDescriptor_FIELDS_DO(macro) \
4103   macro(_inputStorage_offset,    k, "inputStorage",    jdk_internal_foreign_abi_VMStorage_array_array_signature, false); \
4104   macro(_outputStorage_offset,   k, "outputStorage",   jdk_internal_foreign_abi_VMStorage_array_array_signature, false); \
4105   macro(_volatileStorage_offset, k, "volatileStorage", jdk_internal_foreign_abi_VMStorage_array_array_signature, false); \
4106   macro(_stackAlignment_offset,  k, "stackAlignment",  int_signature, false); \
4107   macro(_shadowSpace_offset,     k, "shadowSpace",     int_signature, false); \
4108   macro(_scratch1_offset,        k, "scratch1",        jdk_internal_foreign_abi_VMStorage_signature, false); \
4109   macro(_scratch2_offset,        k, "scratch2",        jdk_internal_foreign_abi_VMStorage_signature, false);
4110 
4111 bool jdk_internal_foreign_abi_ABIDescriptor::is_instance(oop obj) {
4112   return obj != nullptr && is_subclass(obj->klass());
4113 }
4114 
4115 void jdk_internal_foreign_abi_ABIDescriptor::compute_offsets() {
4116   InstanceKlass* k = vmClasses::ABIDescriptor_klass();
4117   ABIDescriptor_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4118 }
4119 
4120 #if INCLUDE_CDS
4121 void jdk_internal_foreign_abi_ABIDescriptor::serialize_offsets(SerializeClosure* f) {
4122   ABIDescriptor_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4123 }
4124 #endif
4125 
4126 objArrayOop jdk_internal_foreign_abi_ABIDescriptor::inputStorage(oop entry) {
4127   return oop_cast<objArrayOop>(entry->obj_field(_inputStorage_offset));
4128 }
4129 
4130 objArrayOop jdk_internal_foreign_abi_ABIDescriptor::outputStorage(oop entry) {
4131   return oop_cast<objArrayOop>(entry->obj_field(_outputStorage_offset));
4132 }
4133 
4134 objArrayOop jdk_internal_foreign_abi_ABIDescriptor::volatileStorage(oop entry) {
4135   return oop_cast<objArrayOop>(entry->obj_field(_volatileStorage_offset));
4136 }
4137 
4138 jint jdk_internal_foreign_abi_ABIDescriptor::stackAlignment(oop entry) {
4139   return entry->int_field(_stackAlignment_offset);
4140 }
4141 
4142 jint jdk_internal_foreign_abi_ABIDescriptor::shadowSpace(oop entry) {
4143   return entry->int_field(_shadowSpace_offset);
4144 }
4145 
4146 oop jdk_internal_foreign_abi_ABIDescriptor::scratch1(oop entry) {
4147   return entry->obj_field(_scratch1_offset);
4148 }
4149 
4150 oop jdk_internal_foreign_abi_ABIDescriptor::scratch2(oop entry) {
4151   return entry->obj_field(_scratch2_offset);
4152 }
4153 
4154 int jdk_internal_foreign_abi_VMStorage::_type_offset;
4155 int jdk_internal_foreign_abi_VMStorage::_indexOrOffset_offset;
4156 int jdk_internal_foreign_abi_VMStorage::_segmentMaskOrSize_offset;
4157 int jdk_internal_foreign_abi_VMStorage::_debugName_offset;
4158 
4159 #define VMStorage_FIELDS_DO(macro) \
4160   macro(_type_offset,              k, "type",              byte_signature, false); \
4161   macro(_indexOrOffset_offset,     k, "indexOrOffset",     int_signature, false); \
4162   macro(_segmentMaskOrSize_offset, k, "segmentMaskOrSize", short_signature, false); \
4163   macro(_debugName_offset,         k, "debugName",         string_signature, false); \
4164 
4165 bool jdk_internal_foreign_abi_VMStorage::is_instance(oop obj) {
4166   return obj != nullptr && is_subclass(obj->klass());
4167 }
4168 
4169 void jdk_internal_foreign_abi_VMStorage::compute_offsets() {
4170   InstanceKlass* k = vmClasses::VMStorage_klass();
4171   VMStorage_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4172 }
4173 
4174 #if INCLUDE_CDS
4175 void jdk_internal_foreign_abi_VMStorage::serialize_offsets(SerializeClosure* f) {
4176   VMStorage_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4177 }
4178 #endif
4179 
4180 jbyte jdk_internal_foreign_abi_VMStorage::type(oop entry) {
4181   return entry->byte_field(_type_offset);
4182 }
4183 
4184 jint jdk_internal_foreign_abi_VMStorage::index_or_offset(oop entry) {
4185   return entry->int_field(_indexOrOffset_offset);
4186 }
4187 
4188 jshort jdk_internal_foreign_abi_VMStorage::segment_mask_or_size(oop entry) {
4189   return entry->short_field(_segmentMaskOrSize_offset);
4190 }
4191 
4192 oop jdk_internal_foreign_abi_VMStorage::debugName(oop entry) {
4193   return entry->obj_field(_debugName_offset);
4194 }
4195 
4196 int jdk_internal_foreign_abi_CallConv::_argRegs_offset;
4197 int jdk_internal_foreign_abi_CallConv::_retRegs_offset;
4198 
4199 #define CallConv_FIELDS_DO(macro) \
4200   macro(_argRegs_offset, k, "argRegs", jdk_internal_foreign_abi_VMStorage_array_signature, false); \
4201   macro(_retRegs_offset, k, "retRegs", jdk_internal_foreign_abi_VMStorage_array_signature, false); \
4202 
4203 bool jdk_internal_foreign_abi_CallConv::is_instance(oop obj) {
4204   return obj != nullptr && is_subclass(obj->klass());
4205 }
4206 
4207 void jdk_internal_foreign_abi_CallConv::compute_offsets() {
4208   InstanceKlass* k = vmClasses::CallConv_klass();
4209   CallConv_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4210 }
4211 
4212 #if INCLUDE_CDS
4213 void jdk_internal_foreign_abi_CallConv::serialize_offsets(SerializeClosure* f) {
4214   CallConv_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4215 }
4216 #endif
4217 
4218 objArrayOop jdk_internal_foreign_abi_CallConv::argRegs(oop entry) {
4219   return oop_cast<objArrayOop>(entry->obj_field(_argRegs_offset));
4220 }
4221 
4222 objArrayOop jdk_internal_foreign_abi_CallConv::retRegs(oop entry) {
4223   return oop_cast<objArrayOop>(entry->obj_field(_retRegs_offset));
4224 }
4225 
4226 oop java_lang_invoke_MethodHandle::type(oop mh) {
4227   return mh->obj_field(_type_offset);
4228 }
4229 
4230 void java_lang_invoke_MethodHandle::set_type(oop mh, oop mtype) {
4231   mh->obj_field_put(_type_offset, mtype);
4232 }
4233 
4234 oop java_lang_invoke_MethodHandle::form(oop mh) {
4235   assert(_form_offset != 0, "");
4236   return mh->obj_field(_form_offset);
4237 }
4238 
4239 void java_lang_invoke_MethodHandle::set_form(oop mh, oop lform) {
4240   assert(_form_offset != 0, "");
4241   mh->obj_field_put(_form_offset, lform);
4242 }
4243 
4244 /// MemberName accessors
4245 
4246 oop java_lang_invoke_MemberName::clazz(oop mname) {
4247   assert(is_instance(mname), "wrong type");
4248   return mname->obj_field(_clazz_offset);
4249 }
4250 
4251 void java_lang_invoke_MemberName::set_clazz(oop mname, oop clazz) {
4252   assert(is_instance(mname), "wrong type");
4253   mname->obj_field_put(_clazz_offset, clazz);
4254 }
4255 
4256 oop java_lang_invoke_MemberName::name(oop mname) {
4257   assert(is_instance(mname), "wrong type");
4258   return mname->obj_field(_name_offset);
4259 }
4260 
4261 void java_lang_invoke_MemberName::set_name(oop mname, oop name) {
4262   assert(is_instance(mname), "wrong type");
4263   mname->obj_field_put(_name_offset, name);
4264 }
4265 
4266 oop java_lang_invoke_MemberName::type(oop mname) {
4267   assert(is_instance(mname), "wrong type");
4268   return mname->obj_field(_type_offset);
4269 }
4270 
4271 void java_lang_invoke_MemberName::set_type(oop mname, oop type) {
4272   assert(is_instance(mname), "wrong type");
4273   mname->obj_field_put(_type_offset, type);
4274 }
4275 
4276 int java_lang_invoke_MemberName::flags(oop mname) {
4277   assert(is_instance(mname), "wrong type");
4278   return mname->int_field(_flags_offset);
4279 }
4280 
4281 void java_lang_invoke_MemberName::set_flags(oop mname, int flags) {
4282   assert(is_instance(mname), "wrong type");
4283   mname->int_field_put(_flags_offset, flags);
4284 }
4285 
4286 
4287 // Return vmtarget from ResolvedMethodName method field through indirection
4288 Method* java_lang_invoke_MemberName::vmtarget(oop mname) {
4289   assert(is_instance(mname), "wrong type");
4290   oop method = mname->obj_field(_method_offset);
4291   return method == nullptr ? nullptr : java_lang_invoke_ResolvedMethodName::vmtarget(method);
4292 }
4293 
4294 bool java_lang_invoke_MemberName::is_method(oop mname) {
4295   assert(is_instance(mname), "must be MemberName");
4296   return (flags(mname) & (MN_IS_METHOD | MN_IS_CONSTRUCTOR)) > 0;
4297 }
4298 
4299 void java_lang_invoke_MemberName::set_method(oop mname, oop resolved_method) {
4300   assert(is_instance(mname), "wrong type");
4301   mname->obj_field_put(_method_offset, resolved_method);
4302 }
4303 
4304 intptr_t java_lang_invoke_MemberName::vmindex(oop mname) {
4305   assert(is_instance(mname), "wrong type");
4306   return (intptr_t) mname->address_field(_vmindex_offset);
4307 }
4308 
4309 void java_lang_invoke_MemberName::set_vmindex(oop mname, intptr_t index) {
4310   assert(is_instance(mname), "wrong type");
4311   mname->address_field_put(_vmindex_offset, (address) index);
4312 }
4313 
4314 
4315 Method* java_lang_invoke_ResolvedMethodName::vmtarget(oop resolved_method) {
4316   assert(is_instance(resolved_method), "wrong type");
4317   Method* m = (Method*)resolved_method->address_field(_vmtarget_offset);
4318   assert(m->is_method(), "must be");
4319   return m;
4320 }
4321 
4322 // Used by redefinition to change Method* to new Method* with same hash (name, signature)
4323 void java_lang_invoke_ResolvedMethodName::set_vmtarget(oop resolved_method, Method* m) {
4324   assert(is_instance(resolved_method), "wrong type");
4325   resolved_method->address_field_put(_vmtarget_offset, (address)m);
4326 }
4327 
4328 void java_lang_invoke_ResolvedMethodName::set_vmholder(oop resolved_method, oop holder) {
4329   assert(is_instance(resolved_method), "wrong type");
4330   resolved_method->obj_field_put(_vmholder_offset, holder);
4331 }
4332 
4333 oop java_lang_invoke_ResolvedMethodName::find_resolved_method(const methodHandle& m, TRAPS) {
4334   const Method* method = m();
4335 
4336   // lookup ResolvedMethod oop in the table, or create a new one and intern it
4337   oop resolved_method = ResolvedMethodTable::find_method(method);
4338   if (resolved_method != nullptr) {
4339     return resolved_method;
4340   }
4341 
4342   InstanceKlass* k = vmClasses::ResolvedMethodName_klass();
4343   if (!k->is_initialized()) {
4344     k->initialize(CHECK_NULL);
4345   }
4346 
4347   oop new_resolved_method = k->allocate_instance(CHECK_NULL);
4348 
4349   NoSafepointVerifier nsv;
4350 
4351   if (method->is_old()) {
4352     method = (method->is_deleted()) ? Universe::throw_no_such_method_error() :
4353                                       method->get_new_method();
4354   }
4355 
4356   InstanceKlass* holder = method->method_holder();
4357 
4358   set_vmtarget(new_resolved_method, const_cast<Method*>(method));
4359   // Add a reference to the loader (actually mirror because hidden classes may not have
4360   // distinct loaders) to ensure the metadata is kept alive.
4361   // This mirror may be different than the one in clazz field.
4362   set_vmholder(new_resolved_method, holder->java_mirror());
4363 
4364   // Set flag in class to indicate this InstanceKlass has entries in the table
4365   // to avoid walking table during redefinition if none of the redefined classes
4366   // have any membernames in the table.
4367   holder->set_has_resolved_methods();
4368 
4369   return ResolvedMethodTable::add_method(method, Handle(THREAD, new_resolved_method));
4370 }
4371 
4372 oop java_lang_invoke_LambdaForm::vmentry(oop lform) {
4373   assert(is_instance(lform), "wrong type");
4374   return lform->obj_field(_vmentry_offset);
4375 }
4376 
4377 
4378 // Support for java_lang_invoke_MethodType
4379 
4380 int java_lang_invoke_MethodType::_rtype_offset;
4381 int java_lang_invoke_MethodType::_ptypes_offset;
4382 
4383 #define METHODTYPE_FIELDS_DO(macro) \
4384   macro(_rtype_offset,  k, "rtype",  class_signature,       false); \
4385   macro(_ptypes_offset, k, "ptypes", class_array_signature, false)
4386 
4387 void java_lang_invoke_MethodType::compute_offsets() {
4388   InstanceKlass* k = vmClasses::MethodType_klass();
4389   METHODTYPE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4390 }
4391 
4392 #if INCLUDE_CDS
4393 void java_lang_invoke_MethodType::serialize_offsets(SerializeClosure* f) {
4394   METHODTYPE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4395 }
4396 #endif
4397 
4398 void java_lang_invoke_MethodType::print_signature(oop mt, outputStream* st) {
4399   st->print("(");
4400   objArrayOop pts = ptypes(mt);
4401   if (pts != nullptr) {
4402     for (int i = 0, limit = pts->length(); i < limit; i++) {
4403       java_lang_Class::print_signature(pts->obj_at(i), st);
4404     }
4405   } else {
4406     st->print("null");
4407   }
4408   st->print(")");
4409   oop rt = rtype(mt);
4410   if (rt != nullptr) {
4411     java_lang_Class::print_signature(rt, st);
4412   } else {
4413     st->print("null");
4414   }
4415 }
4416 
4417 Symbol* java_lang_invoke_MethodType::as_signature(oop mt, bool intern_if_not_found) {
4418   ResourceMark rm;
4419   stringStream buffer(128);
4420   print_signature(mt, &buffer);
4421   const char* sigstr =       buffer.base();
4422   int         siglen = (int) buffer.size();
4423   Symbol *name;
4424   if (!intern_if_not_found) {
4425     name = SymbolTable::probe(sigstr, siglen);
4426   } else {
4427     name = SymbolTable::new_symbol(sigstr, siglen);
4428   }
4429   return name;
4430 }
4431 
4432 bool java_lang_invoke_MethodType::equals(oop mt1, oop mt2) {
4433   if (mt1 == mt2)
4434     return true;
4435   if (rtype(mt1) != rtype(mt2))
4436     return false;
4437   if (ptype_count(mt1) != ptype_count(mt2))
4438     return false;
4439   for (int i = ptype_count(mt1) - 1; i >= 0; i--) {
4440     if (ptype(mt1, i) != ptype(mt2, i))
4441       return false;
4442   }
4443   return true;
4444 }
4445 
4446 oop java_lang_invoke_MethodType::rtype(oop mt) {
4447   assert(is_instance(mt), "must be a MethodType");
4448   return mt->obj_field(_rtype_offset);
4449 }
4450 
4451 objArrayOop java_lang_invoke_MethodType::ptypes(oop mt) {
4452   assert(is_instance(mt), "must be a MethodType");
4453   return (objArrayOop) mt->obj_field(_ptypes_offset);
4454 }
4455 
4456 oop java_lang_invoke_MethodType::ptype(oop mt, int idx) {
4457   return ptypes(mt)->obj_at(idx);
4458 }
4459 
4460 int java_lang_invoke_MethodType::ptype_count(oop mt) {
4461   return ptypes(mt)->length();
4462 }
4463 
4464 int java_lang_invoke_MethodType::ptype_slot_count(oop mt) {
4465   objArrayOop pts = ptypes(mt);
4466   int count = pts->length();
4467   int slots = 0;
4468   for (int i = 0; i < count; i++) {
4469     BasicType bt = java_lang_Class::as_BasicType(pts->obj_at(i));
4470     slots += type2size[bt];
4471   }
4472   return slots;
4473 }
4474 
4475 int java_lang_invoke_MethodType::rtype_slot_count(oop mt) {
4476   BasicType bt = java_lang_Class::as_BasicType(rtype(mt));
4477   return type2size[bt];
4478 }
4479 
4480 
4481 // Support for java_lang_invoke_CallSite
4482 
4483 int java_lang_invoke_CallSite::_target_offset;
4484 int java_lang_invoke_CallSite::_context_offset;
4485 
4486 #define CALLSITE_FIELDS_DO(macro) \
4487   macro(_target_offset,  k, "target", java_lang_invoke_MethodHandle_signature, false); \
4488   macro(_context_offset, k, "context", java_lang_invoke_MethodHandleNatives_CallSiteContext_signature, false)
4489 
4490 void java_lang_invoke_CallSite::compute_offsets() {
4491   InstanceKlass* k = vmClasses::CallSite_klass();
4492   CALLSITE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4493 }
4494 
4495 #if INCLUDE_CDS
4496 void java_lang_invoke_CallSite::serialize_offsets(SerializeClosure* f) {
4497   CALLSITE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4498 }
4499 #endif
4500 
4501 oop java_lang_invoke_CallSite::context_no_keepalive(oop call_site) {
4502   assert(java_lang_invoke_CallSite::is_instance(call_site), "");
4503 
4504   oop dep_oop = call_site->obj_field_access<AS_NO_KEEPALIVE>(_context_offset);
4505   return dep_oop;
4506 }
4507 
4508 // Support for java_lang_invoke_ConstantCallSite
4509 
4510 int java_lang_invoke_ConstantCallSite::_is_frozen_offset;
4511 
4512 #define CONSTANTCALLSITE_FIELDS_DO(macro) \
4513   macro(_is_frozen_offset, k, "isFrozen", bool_signature, false)
4514 
4515 void java_lang_invoke_ConstantCallSite::compute_offsets() {
4516   InstanceKlass* k = vmClasses::ConstantCallSite_klass();
4517   CONSTANTCALLSITE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4518 }
4519 
4520 #if INCLUDE_CDS
4521 void java_lang_invoke_ConstantCallSite::serialize_offsets(SerializeClosure* f) {
4522   CONSTANTCALLSITE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4523 }
4524 #endif
4525 
4526 // Support for java_lang_invoke_MethodHandleNatives_CallSiteContext
4527 
4528 int java_lang_invoke_MethodHandleNatives_CallSiteContext::_vmdependencies_offset;
4529 int java_lang_invoke_MethodHandleNatives_CallSiteContext::_last_cleanup_offset;
4530 
4531 void java_lang_invoke_MethodHandleNatives_CallSiteContext::compute_offsets() {
4532   InstanceKlass* k = vmClasses::Context_klass();
4533   CALLSITECONTEXT_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
4534 }
4535 
4536 #if INCLUDE_CDS
4537 void java_lang_invoke_MethodHandleNatives_CallSiteContext::serialize_offsets(SerializeClosure* f) {
4538   CALLSITECONTEXT_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
4539 }
4540 #endif
4541 
4542 DependencyContext java_lang_invoke_MethodHandleNatives_CallSiteContext::vmdependencies(oop call_site) {
4543   assert(java_lang_invoke_MethodHandleNatives_CallSiteContext::is_instance(call_site), "");
4544   nmethodBucket* volatile* vmdeps_addr = call_site->field_addr<nmethodBucket* volatile>(_vmdependencies_offset);
4545   volatile uint64_t* last_cleanup_addr = call_site->field_addr<volatile uint64_t>(_last_cleanup_offset);
4546   DependencyContext dep_ctx(vmdeps_addr, last_cleanup_addr);
4547   return dep_ctx;
4548 }
4549 
4550 // Support for java_security_AccessControlContext
4551 
4552 int java_security_AccessControlContext::_context_offset;
4553 int java_security_AccessControlContext::_privilegedContext_offset;
4554 int java_security_AccessControlContext::_isPrivileged_offset;
4555 int java_security_AccessControlContext::_isAuthorized_offset;
4556 
4557 #define ACCESSCONTROLCONTEXT_FIELDS_DO(macro) \
4558   macro(_context_offset,           k, "context",      protectiondomain_signature, false); \
4559   macro(_privilegedContext_offset, k, "privilegedContext", accesscontrolcontext_signature, false); \
4560   macro(_isPrivileged_offset,      k, "isPrivileged", bool_signature, false); \
4561   macro(_isAuthorized_offset,      k, "isAuthorized", bool_signature, false)
4562 
4563 void java_security_AccessControlContext::compute_offsets() {
4564   assert(_isPrivileged_offset == 0, "offsets should be initialized only once");
4565   InstanceKlass* k = vmClasses::AccessControlContext_klass();
4566   ACCESSCONTROLCONTEXT_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4567 }
4568 
4569 #if INCLUDE_CDS
4570 void java_security_AccessControlContext::serialize_offsets(SerializeClosure* f) {
4571   ACCESSCONTROLCONTEXT_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4572 }
4573 #endif
4574 
4575 oop java_security_AccessControlContext::create(objArrayHandle context, bool isPrivileged, Handle privileged_context, TRAPS) {
4576   assert(_isPrivileged_offset != 0, "offsets should have been initialized");
4577   assert(_isAuthorized_offset != 0, "offsets should have been initialized");
4578   // Ensure klass is initialized
4579   vmClasses::AccessControlContext_klass()->initialize(CHECK_NULL);
4580   // Allocate result
4581   oop result = vmClasses::AccessControlContext_klass()->allocate_instance(CHECK_NULL);
4582   // Fill in values
4583   result->obj_field_put(_context_offset, context());
4584   result->obj_field_put(_privilegedContext_offset, privileged_context());
4585   result->bool_field_put(_isPrivileged_offset, isPrivileged);
4586   result->bool_field_put(_isAuthorized_offset, true);
4587   return result;
4588 }
4589 
4590 
4591 // Support for java_lang_ClassLoader
4592 
4593 int  java_lang_ClassLoader::_loader_data_offset;
4594 int  java_lang_ClassLoader::_parallelCapable_offset;
4595 int  java_lang_ClassLoader::_name_offset;
4596 int  java_lang_ClassLoader::_nameAndId_offset;
4597 int  java_lang_ClassLoader::_unnamedModule_offset;
4598 int  java_lang_ClassLoader::_parent_offset;
4599 
4600 ClassLoaderData* java_lang_ClassLoader::loader_data_acquire(oop loader) {
4601   assert(loader != nullptr, "loader must not be null");
4602   assert(oopDesc::is_oop(loader), "loader must be oop");
4603   return Atomic::load_acquire(loader->field_addr<ClassLoaderData*>(_loader_data_offset));
4604 }
4605 
4606 ClassLoaderData* java_lang_ClassLoader::loader_data(oop loader) {
4607   assert(loader != nullptr, "loader must not be null");
4608   assert(oopDesc::is_oop(loader), "loader must be oop");
4609   return *loader->field_addr<ClassLoaderData*>(_loader_data_offset);
4610 }
4611 
4612 void java_lang_ClassLoader::release_set_loader_data(oop loader, ClassLoaderData* new_data) {
4613   assert(loader != nullptr, "loader must not be null");
4614   assert(oopDesc::is_oop(loader), "loader must be oop");
4615   Atomic::release_store(loader->field_addr<ClassLoaderData*>(_loader_data_offset), new_data);
4616 }
4617 
4618 #define CLASSLOADER_FIELDS_DO(macro) \
4619   macro(_parallelCapable_offset, k1, "parallelLockMap",      concurrenthashmap_signature, false); \
4620   macro(_name_offset,            k1, vmSymbols::name_name(), string_signature, false); \
4621   macro(_nameAndId_offset,       k1, "nameAndId",            string_signature, false); \
4622   macro(_unnamedModule_offset,   k1, "unnamedModule",        module_signature, false); \
4623   macro(_parent_offset,          k1, "parent",               classloader_signature, false)
4624 
4625 void java_lang_ClassLoader::compute_offsets() {
4626   InstanceKlass* k1 = vmClasses::ClassLoader_klass();
4627   CLASSLOADER_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4628 
4629   CLASSLOADER_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
4630 }
4631 
4632 #if INCLUDE_CDS
4633 void java_lang_ClassLoader::serialize_offsets(SerializeClosure* f) {
4634   CLASSLOADER_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4635   CLASSLOADER_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
4636 }
4637 #endif
4638 
4639 oop java_lang_ClassLoader::parent(oop loader) {
4640   assert(is_instance(loader), "loader must be oop");
4641   return loader->obj_field(_parent_offset);
4642 }
4643 
4644 oop java_lang_ClassLoader::parent_no_keepalive(oop loader) {
4645   assert(is_instance(loader), "loader must be oop");
4646   return loader->obj_field_access<AS_NO_KEEPALIVE>(_parent_offset);
4647 }
4648 
4649 // Returns the name field of this class loader.  If the name field has not
4650 // been set, null will be returned.
4651 oop java_lang_ClassLoader::name(oop loader) {
4652   assert(is_instance(loader), "loader must be oop");
4653   return loader->obj_field(_name_offset);
4654 }
4655 
4656 // Returns the nameAndId field of this class loader. The format is
4657 // as follows:
4658 //   If the defining loader has a name explicitly set then '<loader-name>' @<id>
4659 //   If the defining loader has no name then <qualified-class-name> @<id>
4660 //   If built-in loader, then omit '@<id>' as there is only one instance.
4661 // Use ClassLoader::loader_name_id() to obtain this String as a char*.
4662 oop java_lang_ClassLoader::nameAndId(oop loader) {
4663   assert(is_instance(loader), "loader must be oop");
4664   return loader->obj_field(_nameAndId_offset);
4665 }
4666 
4667 bool java_lang_ClassLoader::isAncestor(oop loader, oop cl) {
4668   assert(is_instance(loader), "loader must be oop");
4669   assert(cl == nullptr || is_instance(cl), "cl argument must be oop");
4670   oop acl = loader;
4671   debug_only(jint loop_count = 0);
4672   // This loop taken verbatim from ClassLoader.java:
4673   do {
4674     acl = parent(acl);
4675     if (cl == acl) {
4676       return true;
4677     }
4678     assert(++loop_count > 0, "loop_count overflow");
4679   } while (acl != nullptr);
4680   return false;
4681 }
4682 
4683 bool java_lang_ClassLoader::is_instance(oop obj) {
4684   return obj != nullptr && is_subclass(obj->klass());
4685 }
4686 
4687 
4688 // For class loader classes, parallelCapable defined
4689 // based on non-null field
4690 // Written to by java.lang.ClassLoader, vm only reads this field, doesn't set it
4691 bool java_lang_ClassLoader::parallelCapable(oop class_loader) {
4692   assert(_parallelCapable_offset != 0, "offsets should have been initialized");
4693   return (class_loader->obj_field(_parallelCapable_offset) != nullptr);
4694 }
4695 
4696 bool java_lang_ClassLoader::is_trusted_loader(oop loader) {
4697   // Fix for 4474172; see evaluation for more details
4698   loader = non_reflection_class_loader(loader);
4699 
4700   oop cl = SystemDictionary::java_system_loader();
4701   while(cl != nullptr) {
4702     if (cl == loader) return true;
4703     cl = parent(cl);
4704   }
4705   return false;
4706 }
4707 
4708 // Return true if this is one of the class loaders associated with
4709 // the generated bytecodes for serialization constructor returned
4710 // by sun.reflect.ReflectionFactory::newConstructorForSerialization
4711 bool java_lang_ClassLoader::is_reflection_class_loader(oop loader) {
4712   if (loader != nullptr) {
4713     Klass* delegating_cl_class = vmClasses::reflect_DelegatingClassLoader_klass();
4714     // This might be null in non-1.4 JDKs
4715     return (delegating_cl_class != nullptr && loader->is_a(delegating_cl_class));
4716   }
4717   return false;
4718 }
4719 
4720 oop java_lang_ClassLoader::non_reflection_class_loader(oop loader) {
4721   // See whether this is one of the class loaders associated with
4722   // the generated bytecodes for reflection, and if so, "magically"
4723   // delegate to its parent to prevent class loading from occurring
4724   // in places where applications using reflection didn't expect it.
4725   if (is_reflection_class_loader(loader)) {
4726     return parent(loader);
4727   }
4728   return loader;
4729 }
4730 
4731 oop java_lang_ClassLoader::unnamedModule(oop loader) {
4732   assert(is_instance(loader), "loader must be oop");
4733   return loader->obj_field(_unnamedModule_offset);
4734 }
4735 
4736 // Support for java_lang_System
4737 //
4738 
4739 int java_lang_System::_static_in_offset;
4740 int java_lang_System::_static_out_offset;
4741 int java_lang_System::_static_err_offset;
4742 int java_lang_System::_static_security_offset;
4743 int java_lang_System::_static_allow_security_offset;
4744 int java_lang_System::_static_never_offset;
4745 
4746 #define SYSTEM_FIELDS_DO(macro) \
4747   macro(_static_in_offset,  k, "in",  input_stream_signature, true); \
4748   macro(_static_out_offset, k, "out", print_stream_signature, true); \
4749   macro(_static_err_offset, k, "err", print_stream_signature, true); \
4750   macro(_static_security_offset, k, "security", security_manager_signature, true); \
4751   macro(_static_allow_security_offset, k, "allowSecurityManager", int_signature, true); \
4752   macro(_static_never_offset, k, "NEVER", int_signature, true)
4753 
4754 void java_lang_System::compute_offsets() {
4755   InstanceKlass* k = vmClasses::System_klass();
4756   SYSTEM_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4757 }
4758 
4759 // This field tells us that a security manager can never be installed so we
4760 // can completely skip populating the ProtectionDomainCacheTable.
4761 bool java_lang_System::allow_security_manager() {
4762   static int initialized = false;
4763   static bool allowed = true; // default
4764   if (!initialized) {
4765     oop base = vmClasses::System_klass()->static_field_base_raw();
4766     int never = base->int_field(_static_never_offset);
4767     allowed = (base->int_field(_static_allow_security_offset) != never);
4768     initialized = true;
4769   }
4770   return allowed;
4771 }
4772 
4773 // This field tells us that a security manager is installed.
4774 bool java_lang_System::has_security_manager() {
4775   oop base = vmClasses::System_klass()->static_field_base_raw();
4776   return base->obj_field(_static_security_offset) != nullptr;
4777 }
4778 
4779 #if INCLUDE_CDS
4780 void java_lang_System::serialize_offsets(SerializeClosure* f) {
4781    SYSTEM_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4782 }
4783 #endif
4784 
4785 // Support for jdk_internal_misc_UnsafeConstants
4786 //
4787 class UnsafeConstantsFixup : public FieldClosure {
4788 private:
4789   int _address_size;
4790   int _page_size;
4791   bool _big_endian;
4792   bool _use_unaligned_access;
4793   int _data_cache_line_flush_size;
4794 public:
4795   UnsafeConstantsFixup() {
4796     // round up values for all static final fields
4797     _address_size = sizeof(void*);
4798     _page_size = AIX_ONLY(sysconf(_SC_PAGESIZE)) NOT_AIX((int)os::vm_page_size());
4799     _big_endian = LITTLE_ENDIAN_ONLY(false) BIG_ENDIAN_ONLY(true);
4800     _use_unaligned_access = UseUnalignedAccesses;
4801     _data_cache_line_flush_size = (int)VM_Version::data_cache_line_flush_size();
4802   }
4803 
4804   void do_field(fieldDescriptor* fd) {
4805     oop mirror = fd->field_holder()->java_mirror();
4806     assert(mirror != nullptr, "UnsafeConstants must have mirror already");
4807     assert(fd->field_holder() == vmClasses::UnsafeConstants_klass(), "Should be UnsafeConstants");
4808     assert(fd->is_final(), "fields of UnsafeConstants must be final");
4809     assert(fd->is_static(), "fields of UnsafeConstants must be static");
4810     if (fd->name() == vmSymbols::address_size_name()) {
4811       mirror->int_field_put(fd->offset(), _address_size);
4812     } else if (fd->name() == vmSymbols::page_size_name()) {
4813       mirror->int_field_put(fd->offset(), _page_size);
4814     } else if (fd->name() == vmSymbols::big_endian_name()) {
4815       mirror->bool_field_put(fd->offset(), _big_endian);
4816     } else if (fd->name() == vmSymbols::use_unaligned_access_name()) {
4817       mirror->bool_field_put(fd->offset(), _use_unaligned_access);
4818     } else if (fd->name() == vmSymbols::data_cache_line_flush_size_name()) {
4819       mirror->int_field_put(fd->offset(), _data_cache_line_flush_size);
4820     } else {
4821       assert(false, "unexpected UnsafeConstants field");
4822     }
4823   }
4824 };
4825 
4826 void jdk_internal_misc_UnsafeConstants::set_unsafe_constants() {
4827   UnsafeConstantsFixup fixup;
4828   vmClasses::UnsafeConstants_klass()->do_local_static_fields(&fixup);
4829 }
4830 
4831 
4832 // java_lang_StackTraceElement
4833 
4834 int java_lang_StackTraceElement::_methodName_offset;
4835 int java_lang_StackTraceElement::_fileName_offset;
4836 int java_lang_StackTraceElement::_lineNumber_offset;
4837 int java_lang_StackTraceElement::_moduleName_offset;
4838 int java_lang_StackTraceElement::_moduleVersion_offset;
4839 int java_lang_StackTraceElement::_classLoaderName_offset;
4840 int java_lang_StackTraceElement::_declaringClass_offset;
4841 int java_lang_StackTraceElement::_declaringClassObject_offset;
4842 
4843 #define STACKTRACEELEMENT_FIELDS_DO(macro) \
4844   macro(_declaringClassObject_offset,  k, "declaringClassObject", class_signature, false); \
4845   macro(_classLoaderName_offset, k, "classLoaderName", string_signature, false); \
4846   macro(_moduleName_offset,      k, "moduleName",      string_signature, false); \
4847   macro(_moduleVersion_offset,   k, "moduleVersion",   string_signature, false); \
4848   macro(_declaringClass_offset,  k, "declaringClass",  string_signature, false); \
4849   macro(_methodName_offset,      k, "methodName",      string_signature, false); \
4850   macro(_fileName_offset,        k, "fileName",        string_signature, false); \
4851   macro(_lineNumber_offset,      k, "lineNumber",      int_signature,    false)
4852 
4853 // Support for java_lang_StackTraceElement
4854 void java_lang_StackTraceElement::compute_offsets() {
4855   InstanceKlass* k = vmClasses::StackTraceElement_klass();
4856   STACKTRACEELEMENT_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4857 }
4858 
4859 #if INCLUDE_CDS
4860 void java_lang_StackTraceElement::serialize_offsets(SerializeClosure* f) {
4861   STACKTRACEELEMENT_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4862 }
4863 #endif
4864 
4865 void java_lang_StackTraceElement::set_fileName(oop element, oop value) {
4866   element->obj_field_put(_fileName_offset, value);
4867 }
4868 
4869 void java_lang_StackTraceElement::set_declaringClass(oop element, oop value) {
4870   element->obj_field_put(_declaringClass_offset, value);
4871 }
4872 
4873 void java_lang_StackTraceElement::set_methodName(oop element, oop value) {
4874   element->obj_field_put(_methodName_offset, value);
4875 }
4876 
4877 void java_lang_StackTraceElement::set_lineNumber(oop element, int value) {
4878   element->int_field_put(_lineNumber_offset, value);
4879 }
4880 
4881 void java_lang_StackTraceElement::set_moduleName(oop element, oop value) {
4882   element->obj_field_put(_moduleName_offset, value);
4883 }
4884 
4885 void java_lang_StackTraceElement::set_moduleVersion(oop element, oop value) {
4886   element->obj_field_put(_moduleVersion_offset, value);
4887 }
4888 
4889 void java_lang_StackTraceElement::set_classLoaderName(oop element, oop value) {
4890   element->obj_field_put(_classLoaderName_offset, value);
4891 }
4892 
4893 void java_lang_StackTraceElement::set_declaringClassObject(oop element, oop value) {
4894   element->obj_field_put(_declaringClassObject_offset, value);
4895 }
4896 
4897 
4898 // java_lang_AssertionStatusDirectives
4899 
4900 int java_lang_AssertionStatusDirectives::_classes_offset;
4901 int java_lang_AssertionStatusDirectives::_classEnabled_offset;
4902 int java_lang_AssertionStatusDirectives::_packages_offset;
4903 int java_lang_AssertionStatusDirectives::_packageEnabled_offset;
4904 int java_lang_AssertionStatusDirectives::_deflt_offset;
4905 
4906 // Support for java Assertions - java_lang_AssertionStatusDirectives.
4907 #define ASSERTIONSTATUSDIRECTIVES_FIELDS_DO(macro) \
4908   macro(_classes_offset,        k, "classes",        string_array_signature, false); \
4909   macro(_classEnabled_offset,   k, "classEnabled",   bool_array_signature, false); \
4910   macro(_packages_offset,       k, "packages",       string_array_signature, false); \
4911   macro(_packageEnabled_offset, k, "packageEnabled", bool_array_signature,   false); \
4912   macro(_deflt_offset,          k, "deflt",          bool_signature,         false)
4913 
4914 void java_lang_AssertionStatusDirectives::compute_offsets() {
4915   InstanceKlass* k = vmClasses::AssertionStatusDirectives_klass();
4916   ASSERTIONSTATUSDIRECTIVES_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4917 }
4918 
4919 #if INCLUDE_CDS
4920 void java_lang_AssertionStatusDirectives::serialize_offsets(SerializeClosure* f) {
4921   ASSERTIONSTATUSDIRECTIVES_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4922 }
4923 #endif
4924 
4925 void java_lang_AssertionStatusDirectives::set_classes(oop o, oop val) {
4926   o->obj_field_put(_classes_offset, val);
4927 }
4928 
4929 void java_lang_AssertionStatusDirectives::set_classEnabled(oop o, oop val) {
4930   o->obj_field_put(_classEnabled_offset, val);
4931 }
4932 
4933 void java_lang_AssertionStatusDirectives::set_packages(oop o, oop val) {
4934   o->obj_field_put(_packages_offset, val);
4935 }
4936 
4937 void java_lang_AssertionStatusDirectives::set_packageEnabled(oop o, oop val) {
4938   o->obj_field_put(_packageEnabled_offset, val);
4939 }
4940 
4941 void java_lang_AssertionStatusDirectives::set_deflt(oop o, bool val) {
4942   o->bool_field_put(_deflt_offset, val);
4943 }
4944 
4945 int java_util_concurrent_locks_AbstractOwnableSynchronizer::_owner_offset;
4946 
4947 #define AOS_FIELDS_DO(macro) \
4948   macro(_owner_offset, k, "exclusiveOwnerThread", thread_signature, false)
4949 
4950 void java_util_concurrent_locks_AbstractOwnableSynchronizer::compute_offsets() {
4951   InstanceKlass* k = vmClasses::java_util_concurrent_locks_AbstractOwnableSynchronizer_klass();
4952   AOS_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4953 }
4954 
4955 oop java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(oop obj) {
4956   assert(_owner_offset != 0, "Must be initialized");
4957   return obj->obj_field(_owner_offset);
4958 }
4959 
4960 #if INCLUDE_CDS
4961 void java_util_concurrent_locks_AbstractOwnableSynchronizer::serialize_offsets(SerializeClosure* f) {
4962   AOS_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4963 }
4964 #endif
4965 
4966 int vector_VectorPayload::_payload_offset;
4967 
4968 #define VECTORPAYLOAD_FIELDS_DO(macro) \
4969   macro(_payload_offset, k, "payload", object_signature, false)
4970 
4971 void vector_VectorPayload::compute_offsets() {
4972   InstanceKlass* k = vmClasses::vector_VectorPayload_klass();
4973   VECTORPAYLOAD_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4974 }
4975 
4976 #if INCLUDE_CDS
4977 void vector_VectorPayload::serialize_offsets(SerializeClosure* f) {
4978   VECTORPAYLOAD_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4979 }
4980 #endif
4981 
4982 void vector_VectorPayload::set_payload(oop o, oop val) {
4983   o->obj_field_put(_payload_offset, val);
4984 }
4985 
4986 bool vector_VectorPayload::is_instance(oop obj) {
4987   return obj != nullptr && is_subclass(obj->klass());
4988 }
4989 
4990 int java_lang_Integer_IntegerCache::_static_cache_offset;
4991 int java_lang_Long_LongCache::_static_cache_offset;
4992 int java_lang_Character_CharacterCache::_static_cache_offset;
4993 int java_lang_Short_ShortCache::_static_cache_offset;
4994 int java_lang_Byte_ByteCache::_static_cache_offset;
4995 
4996 #define INTEGER_CACHE_FIELDS_DO(macro) \
4997   macro(_static_cache_offset, k, "cache", java_lang_Integer_array_signature, true)
4998 
4999 void java_lang_Integer_IntegerCache::compute_offsets(InstanceKlass *k) {
5000   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5001   INTEGER_CACHE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5002 }
5003 
5004 objArrayOop java_lang_Integer_IntegerCache::cache(InstanceKlass *ik) {
5005   oop base = ik->static_field_base_raw();
5006   return objArrayOop(base->obj_field(_static_cache_offset));
5007 }
5008 
5009 Symbol* java_lang_Integer_IntegerCache::symbol() {
5010   return vmSymbols::java_lang_Integer_IntegerCache();
5011 }
5012 
5013 #if INCLUDE_CDS
5014 void java_lang_Integer_IntegerCache::serialize_offsets(SerializeClosure* f) {
5015   INTEGER_CACHE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5016 }
5017 #endif
5018 #undef INTEGER_CACHE_FIELDS_DO
5019 
5020 jint java_lang_Integer::value(oop obj) {
5021    jvalue v;
5022    java_lang_boxing_object::get_value(obj, &v);
5023    return v.i;
5024 }
5025 
5026 #define LONG_CACHE_FIELDS_DO(macro) \
5027   macro(_static_cache_offset, k, "cache", java_lang_Long_array_signature, true)
5028 
5029 void java_lang_Long_LongCache::compute_offsets(InstanceKlass *k) {
5030   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5031   LONG_CACHE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5032 }
5033 
5034 objArrayOop java_lang_Long_LongCache::cache(InstanceKlass *ik) {
5035   oop base = ik->static_field_base_raw();
5036   return objArrayOop(base->obj_field(_static_cache_offset));
5037 }
5038 
5039 Symbol* java_lang_Long_LongCache::symbol() {
5040   return vmSymbols::java_lang_Long_LongCache();
5041 }
5042 
5043 #if INCLUDE_CDS
5044 void java_lang_Long_LongCache::serialize_offsets(SerializeClosure* f) {
5045   LONG_CACHE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5046 }
5047 #endif
5048 #undef LONG_CACHE_FIELDS_DO
5049 
5050 jlong java_lang_Long::value(oop obj) {
5051    jvalue v;
5052    java_lang_boxing_object::get_value(obj, &v);
5053    return v.j;
5054 }
5055 
5056 #define CHARACTER_CACHE_FIELDS_DO(macro) \
5057   macro(_static_cache_offset, k, "cache", java_lang_Character_array_signature, true)
5058 
5059 void java_lang_Character_CharacterCache::compute_offsets(InstanceKlass *k) {
5060   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5061   CHARACTER_CACHE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5062 }
5063 
5064 objArrayOop java_lang_Character_CharacterCache::cache(InstanceKlass *ik) {
5065   oop base = ik->static_field_base_raw();
5066   return objArrayOop(base->obj_field(_static_cache_offset));
5067 }
5068 
5069 Symbol* java_lang_Character_CharacterCache::symbol() {
5070   return vmSymbols::java_lang_Character_CharacterCache();
5071 }
5072 
5073 #if INCLUDE_CDS
5074 void java_lang_Character_CharacterCache::serialize_offsets(SerializeClosure* f) {
5075   CHARACTER_CACHE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5076 }
5077 #endif
5078 #undef CHARACTER_CACHE_FIELDS_DO
5079 
5080 jchar java_lang_Character::value(oop obj) {
5081    jvalue v;
5082    java_lang_boxing_object::get_value(obj, &v);
5083    return v.c;
5084 }
5085 
5086 #define SHORT_CACHE_FIELDS_DO(macro) \
5087   macro(_static_cache_offset, k, "cache", java_lang_Short_array_signature, true)
5088 
5089 void java_lang_Short_ShortCache::compute_offsets(InstanceKlass *k) {
5090   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5091   SHORT_CACHE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5092 }
5093 
5094 objArrayOop java_lang_Short_ShortCache::cache(InstanceKlass *ik) {
5095   oop base = ik->static_field_base_raw();
5096   return objArrayOop(base->obj_field(_static_cache_offset));
5097 }
5098 
5099 Symbol* java_lang_Short_ShortCache::symbol() {
5100   return vmSymbols::java_lang_Short_ShortCache();
5101 }
5102 
5103 #if INCLUDE_CDS
5104 void java_lang_Short_ShortCache::serialize_offsets(SerializeClosure* f) {
5105   SHORT_CACHE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5106 }
5107 #endif
5108 #undef SHORT_CACHE_FIELDS_DO
5109 
5110 jshort java_lang_Short::value(oop obj) {
5111    jvalue v;
5112    java_lang_boxing_object::get_value(obj, &v);
5113    return v.s;
5114 }
5115 
5116 #define BYTE_CACHE_FIELDS_DO(macro) \
5117   macro(_static_cache_offset, k, "cache", java_lang_Byte_array_signature, true)
5118 
5119 void java_lang_Byte_ByteCache::compute_offsets(InstanceKlass *k) {
5120   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5121   BYTE_CACHE_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5122 }
5123 
5124 objArrayOop java_lang_Byte_ByteCache::cache(InstanceKlass *ik) {
5125   oop base = ik->static_field_base_raw();
5126   return objArrayOop(base->obj_field(_static_cache_offset));
5127 }
5128 
5129 Symbol* java_lang_Byte_ByteCache::symbol() {
5130   return vmSymbols::java_lang_Byte_ByteCache();
5131 }
5132 
5133 #if INCLUDE_CDS
5134 void java_lang_Byte_ByteCache::serialize_offsets(SerializeClosure* f) {
5135   BYTE_CACHE_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5136 }
5137 #endif
5138 #undef BYTE_CACHE_FIELDS_DO
5139 
5140 jbyte java_lang_Byte::value(oop obj) {
5141    jvalue v;
5142    java_lang_boxing_object::get_value(obj, &v);
5143    return v.b;
5144 }
5145 
5146 int java_lang_Boolean::_static_TRUE_offset;
5147 int java_lang_Boolean::_static_FALSE_offset;
5148 
5149 #define BOOLEAN_FIELDS_DO(macro) \
5150   macro(_static_TRUE_offset, k, "TRUE", java_lang_Boolean_signature, true); \
5151   macro(_static_FALSE_offset, k, "FALSE", java_lang_Boolean_signature, true)
5152 
5153 
5154 void java_lang_Boolean::compute_offsets(InstanceKlass *k) {
5155   guarantee(k != nullptr && k->is_initialized(), "must be loaded and initialized");
5156   BOOLEAN_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5157 }
5158 
5159 oop java_lang_Boolean::get_TRUE(InstanceKlass *ik) {
5160   oop base = ik->static_field_base_raw();
5161   return base->obj_field(_static_TRUE_offset);
5162 }
5163 
5164 oop java_lang_Boolean::get_FALSE(InstanceKlass *ik) {
5165   oop base = ik->static_field_base_raw();
5166   return base->obj_field(_static_FALSE_offset);
5167 }
5168 
5169 Symbol* java_lang_Boolean::symbol() {
5170   return vmSymbols::java_lang_Boolean();
5171 }
5172 
5173 #if INCLUDE_CDS
5174 void java_lang_Boolean::serialize_offsets(SerializeClosure* f) {
5175   BOOLEAN_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5176 }
5177 #endif
5178 #undef BOOLEAN_CACHE_FIELDS_DO
5179 
5180 jboolean java_lang_Boolean::value(oop obj) {
5181    jvalue v;
5182    java_lang_boxing_object::get_value(obj, &v);
5183    return v.z;
5184 }
5185 
5186 // java_lang_reflect_RecordComponent
5187 
5188 int java_lang_reflect_RecordComponent::_clazz_offset;
5189 int java_lang_reflect_RecordComponent::_name_offset;
5190 int java_lang_reflect_RecordComponent::_type_offset;
5191 int java_lang_reflect_RecordComponent::_accessor_offset;
5192 int java_lang_reflect_RecordComponent::_signature_offset;
5193 int java_lang_reflect_RecordComponent::_annotations_offset;
5194 int java_lang_reflect_RecordComponent::_typeAnnotations_offset;
5195 
5196 #define RECORDCOMPONENT_FIELDS_DO(macro) \
5197   macro(_clazz_offset,       k, "clazz",       class_signature,  false); \
5198   macro(_name_offset,        k, "name",        string_signature, false); \
5199   macro(_type_offset,        k, "type",        class_signature,  false); \
5200   macro(_accessor_offset,    k, "accessor",    reflect_method_signature, false); \
5201   macro(_signature_offset,   k, "signature",   string_signature, false); \
5202   macro(_annotations_offset, k, "annotations", byte_array_signature,     false); \
5203   macro(_typeAnnotations_offset, k, "typeAnnotations", byte_array_signature, false);
5204 
5205 // Support for java_lang_reflect_RecordComponent
5206 void java_lang_reflect_RecordComponent::compute_offsets() {
5207   InstanceKlass* k = vmClasses::RecordComponent_klass();
5208   RECORDCOMPONENT_FIELDS_DO(FIELD_COMPUTE_OFFSET);
5209 }
5210 
5211 #if INCLUDE_CDS
5212 void java_lang_reflect_RecordComponent::serialize_offsets(SerializeClosure* f) {
5213   RECORDCOMPONENT_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
5214 }
5215 #endif
5216 
5217 void java_lang_reflect_RecordComponent::set_clazz(oop element, oop value) {
5218   element->obj_field_put(_clazz_offset, value);
5219 }
5220 
5221 void java_lang_reflect_RecordComponent::set_name(oop element, oop value) {
5222   element->obj_field_put(_name_offset, value);
5223 }
5224 
5225 void java_lang_reflect_RecordComponent::set_type(oop element, oop value) {
5226   element->obj_field_put(_type_offset, value);
5227 }
5228 
5229 void java_lang_reflect_RecordComponent::set_accessor(oop element, oop value) {
5230   element->obj_field_put(_accessor_offset, value);
5231 }
5232 
5233 void java_lang_reflect_RecordComponent::set_signature(oop element, oop value) {
5234   element->obj_field_put(_signature_offset, value);
5235 }
5236 
5237 void java_lang_reflect_RecordComponent::set_annotations(oop element, oop value) {
5238   element->obj_field_put(_annotations_offset, value);
5239 }
5240 
5241 void java_lang_reflect_RecordComponent::set_typeAnnotations(oop element, oop value) {
5242   element->obj_field_put(_typeAnnotations_offset, value);
5243 }
5244 
5245 // java_lang_InternalError
5246 int java_lang_InternalError::_during_unsafe_access_offset;
5247 
5248 void java_lang_InternalError::set_during_unsafe_access(oop internal_error) {
5249   internal_error->bool_field_put(_during_unsafe_access_offset, true);
5250 }
5251 
5252 jboolean java_lang_InternalError::during_unsafe_access(oop internal_error) {
5253   return internal_error->bool_field(_during_unsafe_access_offset);
5254 }
5255 
5256 void java_lang_InternalError::compute_offsets() {
5257   INTERNALERROR_INJECTED_FIELDS(INJECTED_FIELD_COMPUTE_OFFSET);
5258 }
5259 
5260 #if INCLUDE_CDS
5261 void java_lang_InternalError::serialize_offsets(SerializeClosure* f) {
5262   INTERNALERROR_INJECTED_FIELDS(INJECTED_FIELD_SERIALIZE_OFFSET);
5263 }
5264 #endif
5265 
5266 #define BASIC_JAVA_CLASSES_DO_PART1(f) \
5267   f(java_lang_Class) \
5268   f(java_lang_String) \
5269   f(java_lang_ref_Reference) \
5270   //end
5271 
5272 #define BASIC_JAVA_CLASSES_DO_PART2(f) \
5273   f(java_lang_System) \
5274   f(java_lang_ClassLoader) \
5275   f(java_lang_Throwable) \
5276   f(java_lang_Thread) \
5277   f(java_lang_Thread_FieldHolder) \
5278   f(java_lang_Thread_Constants) \
5279   f(java_lang_ThreadGroup) \
5280   f(java_lang_VirtualThread) \
5281   f(java_lang_InternalError) \
5282   f(java_lang_AssertionStatusDirectives) \
5283   f(java_lang_ref_SoftReference) \
5284   f(java_lang_invoke_MethodHandle) \
5285   f(java_lang_invoke_DirectMethodHandle) \
5286   f(java_lang_invoke_MemberName) \
5287   f(java_lang_invoke_ResolvedMethodName) \
5288   f(java_lang_invoke_LambdaForm) \
5289   f(java_lang_invoke_MethodType) \
5290   f(java_lang_invoke_CallSite) \
5291   f(java_lang_invoke_ConstantCallSite) \
5292   f(java_lang_invoke_MethodHandleNatives_CallSiteContext) \
5293   f(java_security_AccessControlContext) \
5294   f(java_lang_reflect_AccessibleObject) \
5295   f(java_lang_reflect_Method) \
5296   f(java_lang_reflect_Constructor) \
5297   f(java_lang_reflect_Field) \
5298   f(java_lang_reflect_RecordComponent) \
5299   f(reflect_ConstantPool) \
5300   f(java_lang_reflect_Parameter) \
5301   f(java_lang_Module) \
5302   f(java_lang_StackTraceElement) \
5303   f(java_lang_ClassFrameInfo) \
5304   f(java_lang_StackFrameInfo) \
5305   f(java_lang_LiveStackFrameInfo) \
5306   f(jdk_internal_vm_ContinuationScope) \
5307   f(jdk_internal_vm_Continuation) \
5308   f(jdk_internal_vm_StackChunk) \
5309   f(java_util_concurrent_locks_AbstractOwnableSynchronizer) \
5310   f(jdk_internal_foreign_abi_NativeEntryPoint) \
5311   f(jdk_internal_foreign_abi_ABIDescriptor) \
5312   f(jdk_internal_foreign_abi_VMStorage) \
5313   f(jdk_internal_foreign_abi_CallConv) \
5314   f(jdk_internal_misc_UnsafeConstants) \
5315   f(java_lang_boxing_object) \
5316   f(vector_VectorPayload) \
5317   //end
5318 
5319 #define BASIC_JAVA_CLASSES_DO(f) \
5320         BASIC_JAVA_CLASSES_DO_PART1(f) \
5321         BASIC_JAVA_CLASSES_DO_PART2(f)
5322 
5323 #define DO_COMPUTE_OFFSETS(k) k::compute_offsets();
5324 
5325 // Compute field offsets of all the classes in this file
5326 void JavaClasses::compute_offsets() {
5327   if (UseSharedSpaces) {
5328     JVMTI_ONLY(assert(JvmtiExport::is_early_phase() && !(JvmtiExport::should_post_class_file_load_hook() &&
5329                                                          JvmtiExport::has_early_class_hook_env()),
5330                       "JavaClasses::compute_offsets() must be called in early JVMTI phase."));
5331     // None of the classes used by the rest of this function can be replaced by
5332     // JVMTI ClassFileLoadHook.
5333     // We are safe to use the archived offsets, which have already been restored
5334     // by JavaClasses::serialize_offsets, without computing the offsets again.
5335     return;
5336   }
5337 
5338   // We have already called the compute_offsets() of the
5339   // BASIC_JAVA_CLASSES_DO_PART1 classes (java_lang_String, java_lang_Class and
5340   // java_lang_ref_Reference) earlier inside vmClasses::resolve_all()
5341   BASIC_JAVA_CLASSES_DO_PART2(DO_COMPUTE_OFFSETS);
5342 }
5343 
5344 #if INCLUDE_CDS
5345 #define DO_SERIALIZE_OFFSETS(k) k::serialize_offsets(soc);
5346 
5347 void JavaClasses::serialize_offsets(SerializeClosure* soc) {
5348   BASIC_JAVA_CLASSES_DO(DO_SERIALIZE_OFFSETS);
5349 }
5350 #endif
5351 
5352 #if INCLUDE_CDS_JAVA_HEAP
5353 bool JavaClasses::is_supported_for_archiving(oop obj) {
5354   Klass* klass = obj->klass();
5355 
5356   if (klass == vmClasses::ClassLoader_klass() ||  // ClassLoader::loader_data is malloc'ed.
5357       // The next 3 classes are used to implement java.lang.invoke, and are not used directly in
5358       // regular Java code. The implementation of java.lang.invoke uses generated hidden classes
5359       // (e.g., as referenced by ResolvedMethodName::vmholder) that are not yet supported by CDS.
5360       // So for now we cannot not support these classes for archiving.
5361       //
5362       // These objects typically are not referenced by static fields, but rather by resolved
5363       // constant pool entries, so excluding them shouldn't affect the archiving of static fields.
5364       klass == vmClasses::ResolvedMethodName_klass() ||
5365       klass == vmClasses::MemberName_klass() ||
5366       klass == vmClasses::Context_klass() ||
5367       // It's problematic to archive Reference objects. One of the reasons is that
5368       // Reference::discovered may pull in unwanted objects (see JDK-8284336)
5369       klass->is_subclass_of(vmClasses::Reference_klass())) {
5370     return false;
5371   }
5372 
5373   return true;
5374 }
5375 #endif
5376 
5377 #ifndef PRODUCT
5378 
5379 // These functions exist to assert the validity of de-serialized offsets in boxing object as a sanity check.
5380 
5381 bool JavaClasses::check_offset(const char *klass_name, int deserialized_offset, const char *field_name,
5382                                const char* field_sig) {
5383   EXCEPTION_MARK;
5384   fieldDescriptor fd;
5385   TempNewSymbol klass_sym = SymbolTable::new_symbol(klass_name);
5386   Klass* k = SystemDictionary::resolve_or_fail(klass_sym, true, CATCH);
5387   InstanceKlass* ik = InstanceKlass::cast(k);
5388   TempNewSymbol f_name = SymbolTable::new_symbol(field_name);
5389   TempNewSymbol f_sig  = SymbolTable::new_symbol(field_sig);
5390   if (!ik->find_local_field(f_name, f_sig, &fd)) {
5391     tty->print_cr("Nonstatic field %s.%s not found", klass_name, field_name);
5392     return false;
5393   }
5394   if (fd.is_static()) {
5395     tty->print_cr("Nonstatic field %s.%s appears to be static", klass_name, field_name);
5396     return false;
5397   }
5398   if (fd.offset() == deserialized_offset ) {
5399     return true;
5400   } else {
5401     tty->print_cr("Offset of nonstatic field %s.%s is deserialized as %d but should really be %d.",
5402                   klass_name, field_name, deserialized_offset, fd.offset());
5403     return false;
5404   }
5405 }
5406 
5407 void JavaClasses::check_offsets() {
5408   bool valid = true;
5409 
5410 #define CHECK_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
5411   valid &= check_offset(klass_name, cpp_klass_name :: _##field_name ## _offset, #field_name, field_sig)
5412 
5413 #define CHECK_LONG_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
5414   valid &= check_offset(klass_name, cpp_klass_name :: _##long_ ## field_name ## _offset, #field_name, field_sig)
5415 
5416   // Boxed primitive objects (java_lang_boxing_object)
5417 
5418   CHECK_OFFSET("java/lang/Boolean",   java_lang_boxing_object, value, "Z");
5419   CHECK_OFFSET("java/lang/Character", java_lang_boxing_object, value, "C");
5420   CHECK_OFFSET("java/lang/Float",     java_lang_boxing_object, value, "F");
5421   CHECK_LONG_OFFSET("java/lang/Double", java_lang_boxing_object, value, "D");
5422   CHECK_OFFSET("java/lang/Byte",      java_lang_boxing_object, value, "B");
5423   CHECK_OFFSET("java/lang/Short",     java_lang_boxing_object, value, "S");
5424   CHECK_OFFSET("java/lang/Integer",   java_lang_boxing_object, value, "I");
5425   CHECK_LONG_OFFSET("java/lang/Long", java_lang_boxing_object, value, "J");
5426 
5427   if (!valid) vm_exit_during_initialization("Field offset verification failed");
5428 }
5429 
5430 #endif // PRODUCT
5431 
5432 int InjectedField::compute_offset() {
5433   InstanceKlass* ik = InstanceKlass::cast(klass());
5434   for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
5435     if (!may_be_java && !fs.field_flags().is_injected()) {
5436       // Only look at injected fields
5437       continue;
5438     }
5439     if (fs.name() == name() && fs.signature() == signature()) {
5440       return fs.offset();
5441     }
5442   }
5443   ResourceMark rm;
5444   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)" : "");
5445 #ifndef PRODUCT
5446   ik->print();
5447   tty->print_cr("all fields:");
5448   for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
5449     tty->print_cr("  name: %s, sig: %s, flags: %08x", fs.name()->as_C_string(), fs.signature()->as_C_string(), fs.access_flags().as_int());
5450   }
5451 #endif //PRODUCT
5452   vm_exit_during_initialization("Invalid layout of well-known class: use -Xlog:class+load=info to see the origin of the problem class");
5453   return -1;
5454 }
5455 
5456 void javaClasses_init() {
5457   JavaClasses::compute_offsets();
5458   JavaClasses::check_offsets();
5459   FilteredFieldsMap::initialize();  // must be done after computing offsets.
5460 }
--- EOF ---