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