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