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