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