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