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








4276 
4277 #define STACKTRACEELEMENT_FIELDS_DO(macro) \
4278   macro(declaringClassObject_offset,  k, "declaringClassObject", class_signature, false); \
4279   macro(classLoaderName_offset, k, "classLoaderName", string_signature, false); \
4280   macro(moduleName_offset,      k, "moduleName",      string_signature, false); \
4281   macro(moduleVersion_offset,   k, "moduleVersion",   string_signature, false); \
4282   macro(declaringClass_offset,  k, "declaringClass",  string_signature, false); \
4283   macro(methodName_offset,      k, "methodName",      string_signature, false); \
4284   macro(fileName_offset,        k, "fileName",        string_signature, false); \
4285   macro(lineNumber_offset,      k, "lineNumber",      int_signature,    false)
4286 
4287 // Support for java_lang_StackTraceElement
4288 void java_lang_StackTraceElement::compute_offsets() {
4289   InstanceKlass* k = SystemDictionary::StackTraceElement_klass();
4290   STACKTRACEELEMENT_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4291 }
4292 
4293 #if INCLUDE_CDS
4294 void java_lang_StackTraceElement::serialize(SerializeClosure* f) {
4295   STACKTRACEELEMENT_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4296 }
4297 #endif
4298 
4299 void java_lang_StackTraceElement::set_fileName(oop element, oop value) {
4300   element->obj_field_put(fileName_offset, value);
4301 }
4302 
4303 void java_lang_StackTraceElement::set_declaringClass(oop element, oop value) {
4304   element->obj_field_put(declaringClass_offset, value);
4305 }
4306 
4307 void java_lang_StackTraceElement::set_methodName(oop element, oop value) {
4308   element->obj_field_put(methodName_offset, value);
4309 }
4310 
4311 void java_lang_StackTraceElement::set_lineNumber(oop element, int value) {
4312   element->int_field_put(lineNumber_offset, value);
4313 }
4314 
4315 void java_lang_StackTraceElement::set_moduleName(oop element, oop value) {
4316   element->obj_field_put(moduleName_offset, value);
4317 }
4318 
4319 void java_lang_StackTraceElement::set_moduleVersion(oop element, oop value) {
4320   element->obj_field_put(moduleVersion_offset, value);
4321 }
4322 
4323 void java_lang_StackTraceElement::set_classLoaderName(oop element, oop value) {
4324   element->obj_field_put(classLoaderName_offset, value);
4325 }
4326 
4327 void java_lang_StackTraceElement::set_declaringClassObject(oop element, oop value) {
4328   element->obj_field_put(declaringClassObject_offset, value);
4329 }
4330 
4331 void java_lang_StackFrameInfo::set_version(oop element, short value) {
4332   element->short_field_put(_version_offset, value);
4333 }
4334 
4335 void java_lang_StackFrameInfo::set_bci(oop element, int value) {
4336   element->int_field_put(_bci_offset, value);
4337 }
4338 
4339 void java_lang_LiveStackFrameInfo::set_monitors(oop element, oop value) {
4340   element->obj_field_put(_monitors_offset, value);
4341 }
4342 
4343 void java_lang_LiveStackFrameInfo::set_locals(oop element, oop value) {
4344   element->obj_field_put(_locals_offset, value);
4345 }
4346 
4347 void java_lang_LiveStackFrameInfo::set_operands(oop element, oop value) {
4348   element->obj_field_put(_operands_offset, value);
4349 }
4350 
4351 void java_lang_LiveStackFrameInfo::set_mode(oop element, int value) {
4352   element->int_field_put(_mode_offset, value);
4353 }
4354 
4355 // Support for java Assertions - java_lang_AssertionStatusDirectives.
4356 #define ASSERTIONSTATUSDIRECTIVES_FIELDS_DO(macro) \
4357   macro(classes_offset,        k, "classes",        string_array_signature, false); \
4358   macro(classEnabled_offset,   k, "classEnabled",   bool_array_signature, false); \
4359   macro(packages_offset,       k, "packages",       string_array_signature, false); \
4360   macro(packageEnabled_offset, k, "packageEnabled", bool_array_signature,   false); \
4361   macro(deflt_offset,          k, "deflt",          bool_signature,         false)
4362 
4363 void java_lang_AssertionStatusDirectives::compute_offsets() {
4364   InstanceKlass* k = SystemDictionary::AssertionStatusDirectives_klass();
4365   ASSERTIONSTATUSDIRECTIVES_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4366 }
4367 
4368 #if INCLUDE_CDS
4369 void java_lang_AssertionStatusDirectives::serialize(SerializeClosure* f) {
4370   ASSERTIONSTATUSDIRECTIVES_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4371 }
4372 #endif
4373 
4374 void java_lang_AssertionStatusDirectives::set_classes(oop o, oop val) {
4375   o->obj_field_put(classes_offset, val);
4376 }
4377 
4378 void java_lang_AssertionStatusDirectives::set_classEnabled(oop o, oop val) {
4379   o->obj_field_put(classEnabled_offset, val);
4380 }
4381 
4382 void java_lang_AssertionStatusDirectives::set_packages(oop o, oop val) {
4383   o->obj_field_put(packages_offset, val);
4384 }
4385 
4386 void java_lang_AssertionStatusDirectives::set_packageEnabled(oop o, oop val) {
4387   o->obj_field_put(packageEnabled_offset, val);
4388 }
4389 
4390 void java_lang_AssertionStatusDirectives::set_deflt(oop o, bool val) {
4391   o->bool_field_put(deflt_offset, val);
4392 }
4393 
4394 
4395 // Support for intrinsification of java.nio.Buffer.checkIndex
4396 int java_nio_Buffer::limit_offset() {
4397   return _limit_offset;
4398 }
4399 
4400 #define BUFFER_FIELDS_DO(macro) \
4401   macro(_limit_offset, k, "limit", int_signature, false)
4402 
4403 void java_nio_Buffer::compute_offsets() {
4404   InstanceKlass* k = SystemDictionary::nio_Buffer_klass();
4405   assert(k != NULL, "must be loaded in 1.4+");
4406   BUFFER_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4407 }
4408 
4409 #if INCLUDE_CDS
4410 void java_nio_Buffer::serialize(SerializeClosure* f) {
4411   BUFFER_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4412 }
4413 #endif
4414 
4415 #define AOS_FIELDS_DO(macro) \
4416   macro(_owner_offset, k, "exclusiveOwnerThread", thread_signature, false)
4417 
4418 void java_util_concurrent_locks_AbstractOwnableSynchronizer::compute_offsets() {
4419   InstanceKlass* k = SystemDictionary::java_util_concurrent_locks_AbstractOwnableSynchronizer_klass();
4420   AOS_FIELDS_DO(FIELD_COMPUTE_OFFSET);
4421 }
4422 
4423 oop java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(oop obj) {
4424   assert(_owner_offset != 0, "Must be initialized");
4425   return obj->obj_field(_owner_offset);
4426 }
4427 
4428 #if INCLUDE_CDS
4429 void java_util_concurrent_locks_AbstractOwnableSynchronizer::serialize(SerializeClosure* f) {
4430   AOS_FIELDS_DO(FIELD_SERIALIZE_OFFSET);
4431 }
4432 #endif
4433 
4434 static int member_offset(int hardcoded_offset) {
4435   return (hardcoded_offset * heapOopSize) + instanceOopDesc::base_offset_in_bytes();
4436 }
4437 
















































































4438 // Compute hard-coded offsets
4439 // Invoked before SystemDictionary::initialize, so pre-loaded classes
4440 // are not available to determine the offset_of_static_fields.
4441 void JavaClasses::compute_hard_coded_offsets() {
4442 
4443   // java_lang_boxing_object
4444   java_lang_boxing_object::value_offset      = member_offset(java_lang_boxing_object::hc_value_offset);
4445   java_lang_boxing_object::long_value_offset = align_up(member_offset(java_lang_boxing_object::hc_value_offset), BytesPerLong);
4446 
4447   // java_lang_ref_Reference
4448   java_lang_ref_Reference::referent_offset    = member_offset(java_lang_ref_Reference::hc_referent_offset);
4449   java_lang_ref_Reference::queue_offset       = member_offset(java_lang_ref_Reference::hc_queue_offset);
4450   java_lang_ref_Reference::next_offset        = member_offset(java_lang_ref_Reference::hc_next_offset);
4451   java_lang_ref_Reference::discovered_offset  = member_offset(java_lang_ref_Reference::hc_discovered_offset);
4452 }
4453 
4454 
4455 // Compute non-hard-coded field offsets of all the classes in this file
4456 void JavaClasses::compute_offsets() {
4457   if (UseSharedSpaces) {
4458     return; // field offsets are loaded from archive
4459   }
4460 
4461   // java_lang_Class::compute_offsets was called earlier in bootstrap
4462   java_lang_System::compute_offsets();
4463   java_lang_ClassLoader::compute_offsets();
4464   java_lang_Throwable::compute_offsets();
4465   java_lang_Thread::compute_offsets();
4466   java_lang_ThreadGroup::compute_offsets();
4467   java_lang_AssertionStatusDirectives::compute_offsets();
4468   java_lang_ref_SoftReference::compute_offsets();
4469   java_lang_invoke_MethodHandle::compute_offsets();
4470   java_lang_invoke_DirectMethodHandle::compute_offsets();
4471   java_lang_invoke_MemberName::compute_offsets();
4472   java_lang_invoke_ResolvedMethodName::compute_offsets();
4473   java_lang_invoke_LambdaForm::compute_offsets();
4474   java_lang_invoke_MethodType::compute_offsets();
4475   java_lang_invoke_CallSite::compute_offsets();
4476   java_lang_invoke_MethodHandleNatives_CallSiteContext::compute_offsets();
4477   java_security_AccessControlContext::compute_offsets();
4478   // Initialize reflection classes. The layouts of these classes
4479   // changed with the new reflection implementation in JDK 1.4, and
4480   // since the Universe doesn't know what JDK version it is until this
4481   // point we defer computation of these offsets until now.
4482   java_lang_reflect_AccessibleObject::compute_offsets();
4483   java_lang_reflect_Method::compute_offsets();
4484   java_lang_reflect_Constructor::compute_offsets();
4485   java_lang_reflect_Field::compute_offsets();
4486   java_nio_Buffer::compute_offsets();
4487   reflect_ConstantPool::compute_offsets();
4488   reflect_UnsafeStaticFieldAccessorImpl::compute_offsets();
4489   java_lang_reflect_Parameter::compute_offsets();
4490   java_lang_Module::compute_offsets();
4491   java_lang_StackTraceElement::compute_offsets();
4492   java_lang_StackFrameInfo::compute_offsets();
4493   java_lang_LiveStackFrameInfo::compute_offsets();
4494   java_util_concurrent_locks_AbstractOwnableSynchronizer::compute_offsets();
4495 
4496   // generated interpreter code wants to know about the offsets we just computed:
4497   AbstractAssembler::update_delayed_values();









4498 }
4499 
4500 #ifndef PRODUCT
4501 
4502 // These functions exist to assert the validity of hard-coded field offsets to guard
4503 // against changes in the class files
4504 
4505 bool JavaClasses::check_offset(const char *klass_name, int hardcoded_offset, const char *field_name, const char* field_sig) {
4506   EXCEPTION_MARK;
4507   fieldDescriptor fd;
4508   TempNewSymbol klass_sym = SymbolTable::new_symbol(klass_name, CATCH);
4509   Klass* k = SystemDictionary::resolve_or_fail(klass_sym, true, CATCH);
4510   InstanceKlass* ik = InstanceKlass::cast(k);
4511   TempNewSymbol f_name = SymbolTable::new_symbol(field_name, CATCH);
4512   TempNewSymbol f_sig  = SymbolTable::new_symbol(field_sig, CATCH);
4513   if (!ik->find_local_field(f_name, f_sig, &fd)) {
4514     tty->print_cr("Nonstatic field %s.%s not found", klass_name, field_name);
4515     return false;
4516   }
4517   if (fd.is_static()) {
4518     tty->print_cr("Nonstatic field %s.%s appears to be static", klass_name, field_name);
4519     return false;
4520   }
4521   if (fd.offset() == hardcoded_offset ) {
4522     return true;
4523   } else {
4524     tty->print_cr("Offset of nonstatic field %s.%s is hardcoded as %d but should really be %d.",
4525                   klass_name, field_name, hardcoded_offset, fd.offset());
4526     return false;
4527   }
4528 }
4529 
4530 // Check the hard-coded field offsets of all the classes in this file
4531 
4532 void JavaClasses::check_offsets() {
4533   bool valid = true;
4534 
4535 #define CHECK_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
4536   valid &= check_offset(klass_name, cpp_klass_name :: field_name ## _offset, #field_name, field_sig)
4537 
4538 #define CHECK_LONG_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
4539   valid &= check_offset(klass_name, cpp_klass_name :: long_ ## field_name ## _offset, #field_name, field_sig)
4540 
4541   // Boxed primitive objects (java_lang_boxing_object)
4542 
4543   CHECK_OFFSET("java/lang/Boolean",   java_lang_boxing_object, value, "Z");
4544   CHECK_OFFSET("java/lang/Character", java_lang_boxing_object, value, "C");
4545   CHECK_OFFSET("java/lang/Float",     java_lang_boxing_object, value, "F");
4546   CHECK_LONG_OFFSET("java/lang/Double", java_lang_boxing_object, value, "D");
4547   CHECK_OFFSET("java/lang/Byte",      java_lang_boxing_object, value, "B");
4548   CHECK_OFFSET("java/lang/Short",     java_lang_boxing_object, value, "S");
4549   CHECK_OFFSET("java/lang/Integer",   java_lang_boxing_object, value, "I");
4550   CHECK_LONG_OFFSET("java/lang/Long", java_lang_boxing_object, value, "J");
4551 
4552   // java.lang.ref.Reference
4553 
4554   CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, referent, "Ljava/lang/Object;");
4555   CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, queue, "Ljava/lang/ref/ReferenceQueue;");
4556   CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, next, "Ljava/lang/ref/Reference;");
4557   // Fake field
4558   //CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, discovered, "Ljava/lang/ref/Reference;");
4559 
4560   if (!valid) vm_exit_during_initialization("Hard-coded field offset verification failed");
4561 }
4562 
4563 #endif // PRODUCT
4564 
4565 int InjectedField::compute_offset() {
4566   InstanceKlass* ik = InstanceKlass::cast(klass());
4567   for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
4568     if (!may_be_java && !fs.access_flags().is_internal()) {
4569       // Only look at injected fields
4570       continue;
4571     }
4572     if (fs.name() == name() && fs.signature() == signature()) {
4573       return fs.offset();
4574     }
4575   }
4576   ResourceMark rm;
4577   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)" : "");
4578 #ifndef PRODUCT
4579   ik->print();
4580   tty->print_cr("all fields:");
4581   for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
4582     tty->print_cr("  name: %s, sig: %s, flags: %08x", fs.name()->as_C_string(), fs.signature()->as_C_string(), fs.access_flags().as_int());
4583   }
4584 #endif //PRODUCT
4585   vm_exit_during_initialization("Invalid layout of preloaded class: use -Xlog:class+load=info to see the origin of the problem class");
4586   return -1;
4587 }
4588 
4589 void javaClasses_init() {
4590   JavaClasses::compute_offsets();
4591   JavaClasses::check_offsets();
4592   FilteredFieldsMap::initialize();  // must be done after computing offsets.
4593 }
--- EOF ---