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