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