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