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