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