1 /*
   2  * Copyright 1997-2007 Sun Microsystems, Inc.  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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20  * CA 95054 USA or visit www.sun.com if you need additional information or
  21  * have any questions.
  22  *
  23  */
  24 
  25 # include "incls/_precompiled.incl"
  26 # include "incls/_javaClasses.cpp.incl"
  27 
  28 // Helpful routine for computing field offsets at run time rather than hardcoding them
  29 static void
  30 compute_offset(int &dest_offset,
  31                klassOop klass_oop, symbolOop name_symbol, symbolOop signature_symbol) {
  32   fieldDescriptor fd;
  33   instanceKlass* ik = instanceKlass::cast(klass_oop);
  34   if (!ik->find_local_field(name_symbol, signature_symbol, &fd)) {
  35     ResourceMark rm;
  36     tty->print_cr("Invalid layout of %s at %s", ik->external_name(), name_symbol->as_C_string());
  37     fatal("Invalid layout of preloaded class");
  38   }
  39   dest_offset = fd.offset();
  40 }
  41 
  42 // Same as above but for "optional" offsets that might not be present in certain JDK versions
  43 static void
  44 compute_optional_offset(int& dest_offset,
  45                         klassOop klass_oop, symbolOop name_symbol, symbolOop signature_symbol) {
  46   fieldDescriptor fd;
  47   instanceKlass* ik = instanceKlass::cast(klass_oop);
  48   if (ik->find_local_field(name_symbol, signature_symbol, &fd)) {
  49     dest_offset = fd.offset();
  50   }
  51 }
  52 
  53 Handle java_lang_String::basic_create(int length, bool tenured, TRAPS) {
  54   // Create the String object first, so there's a chance that the String
  55   // and the char array it points to end up in the same cache line.
  56   oop obj;
  57   if (tenured) {
  58     obj = instanceKlass::cast(SystemDictionary::string_klass())->allocate_permanent_instance(CHECK_NH);
  59   } else {
  60     obj = instanceKlass::cast(SystemDictionary::string_klass())->allocate_instance(CHECK_NH);
  61   }
  62 
  63   // Create the char array.  The String object must be handlized here
  64   // because GC can happen as a result of the allocation attempt.
  65   Handle h_obj(THREAD, obj);
  66   typeArrayOop buffer;
  67   if (tenured) {
  68     buffer = oopFactory::new_permanent_charArray(length, CHECK_NH);
  69   } else {
  70     buffer = oopFactory::new_charArray(length, CHECK_NH);
  71   }
  72 
  73   // Point the String at the char array
  74   obj = h_obj();
  75   set_value(obj, buffer);
  76   // No need to zero the offset, allocation zero'ed the entire String object
  77   assert(offset(obj) == 0, "initial String offset should be zero");
  78 //set_offset(obj, 0);
  79   set_count(obj, length);
  80 
  81   return h_obj;
  82 }
  83 
  84 Handle java_lang_String::basic_create_from_unicode(jchar* unicode, int length, bool tenured, TRAPS) {
  85   Handle h_obj = basic_create(length, tenured, CHECK_NH);
  86   typeArrayOop buffer = value(h_obj());
  87   for (int index = 0; index < length; index++) {
  88     buffer->char_at_put(index, unicode[index]);
  89   }
  90   return h_obj;
  91 }
  92 
  93 Handle java_lang_String::create_from_unicode(jchar* unicode, int length, TRAPS) {
  94   return basic_create_from_unicode(unicode, length, false, CHECK_NH);
  95 }
  96 
  97 Handle java_lang_String::create_tenured_from_unicode(jchar* unicode, int length, TRAPS) {
  98   return basic_create_from_unicode(unicode, length, true, CHECK_NH);
  99 }
 100 
 101 oop java_lang_String::create_oop_from_unicode(jchar* unicode, int length, TRAPS) {
 102   Handle h_obj = basic_create_from_unicode(unicode, length, false, CHECK_0);
 103   return h_obj();
 104 }
 105 
 106 Handle java_lang_String::create_from_str(const char* utf8_str, TRAPS) {
 107   if (utf8_str == NULL) {
 108     return Handle();
 109   }
 110   int length = UTF8::unicode_length(utf8_str);
 111   Handle h_obj = basic_create(length, false, CHECK_NH);
 112   if (length > 0) {
 113     UTF8::convert_to_unicode(utf8_str, value(h_obj())->char_at_addr(0), length);
 114   }
 115   return h_obj;
 116 }
 117 
 118 oop java_lang_String::create_oop_from_str(const char* utf8_str, TRAPS) {
 119   Handle h_obj = create_from_str(utf8_str, CHECK_0);
 120   return h_obj();
 121 }
 122 
 123 Handle java_lang_String::create_from_symbol(symbolHandle symbol, TRAPS) {
 124   int length = UTF8::unicode_length((char*)symbol->bytes(), symbol->utf8_length());
 125   Handle h_obj = basic_create(length, false, CHECK_NH);
 126   if (length > 0) {
 127     UTF8::convert_to_unicode((char*)symbol->bytes(), value(h_obj())->char_at_addr(0), length);
 128   }
 129   return h_obj;
 130 }
 131 
 132 // Converts a C string to a Java String based on current encoding
 133 Handle java_lang_String::create_from_platform_dependent_str(const char* str, TRAPS) {
 134   assert(str != NULL, "bad arguments");
 135 
 136   typedef jstring (*to_java_string_fn_t)(JNIEnv*, const char *);
 137   static to_java_string_fn_t _to_java_string_fn = NULL;
 138 
 139   if (_to_java_string_fn == NULL) {
 140     void *lib_handle = os::native_java_library();
 141     _to_java_string_fn = CAST_TO_FN_PTR(to_java_string_fn_t, hpi::dll_lookup(lib_handle, "NewStringPlatform"));
 142     if (_to_java_string_fn == NULL) {
 143       fatal("NewStringPlatform missing");
 144     }
 145   }
 146 
 147   jstring js = NULL;
 148   { JavaThread* thread = (JavaThread*)THREAD;
 149     assert(thread->is_Java_thread(), "must be java thread");
 150     HandleMark hm(thread);
 151     ThreadToNativeFromVM ttn(thread);
 152     js = (_to_java_string_fn)(thread->jni_environment(), str);
 153   }
 154   return Handle(THREAD, JNIHandles::resolve(js));
 155 }
 156 
 157 // Converts a Java String to a native C string that can be used for
 158 // native OS calls.
 159 char* java_lang_String::as_platform_dependent_str(Handle java_string, TRAPS) {
 160 
 161   typedef char* (*to_platform_string_fn_t)(JNIEnv*, jstring, bool*);
 162   static to_platform_string_fn_t _to_platform_string_fn = NULL;
 163 
 164   if (_to_platform_string_fn == NULL) {
 165     void *lib_handle = os::native_java_library();
 166     _to_platform_string_fn = CAST_TO_FN_PTR(to_platform_string_fn_t, hpi::dll_lookup(lib_handle, "GetStringPlatformChars"));
 167     if (_to_platform_string_fn == NULL) {
 168       fatal("GetStringPlatformChars missing");
 169     }
 170   }
 171 
 172   char *native_platform_string;
 173   { JavaThread* thread = (JavaThread*)THREAD;
 174     assert(thread->is_Java_thread(), "must be java thread");
 175     JNIEnv *env = thread->jni_environment();
 176     jstring js = (jstring) JNIHandles::make_local(env, java_string());
 177     bool is_copy;
 178     HandleMark hm(thread);
 179     ThreadToNativeFromVM ttn(thread);
 180     native_platform_string = (_to_platform_string_fn)(env, js, &is_copy);
 181     assert(is_copy == JNI_TRUE, "is_copy value changed");
 182     JNIHandles::destroy_local(js);
 183   }
 184   return native_platform_string;
 185 }
 186 
 187 Handle java_lang_String::char_converter(Handle java_string, jchar from_char, jchar to_char, TRAPS) {
 188   oop          obj    = java_string();
 189   // Typical usage is to convert all '/' to '.' in string.
 190   typeArrayOop value  = java_lang_String::value(obj);
 191   int          offset = java_lang_String::offset(obj);
 192   int          length = java_lang_String::length(obj);
 193 
 194   // First check if any from_char exist
 195   int index; // Declared outside, used later
 196   for (index = 0; index < length; index++) {
 197     if (value->char_at(index + offset) == from_char) {
 198       break;
 199     }
 200   }
 201   if (index == length) {
 202     // No from_char, so do not copy.
 203     return java_string;
 204   }
 205 
 206   // Create new UNICODE buffer. Must handlize value because GC
 207   // may happen during String and char array creation.
 208   typeArrayHandle h_value(THREAD, value);
 209   Handle string = basic_create(length, false, CHECK_NH);
 210 
 211   typeArrayOop from_buffer = h_value();
 212   typeArrayOop to_buffer   = java_lang_String::value(string());
 213 
 214   // Copy contents
 215   for (index = 0; index < length; index++) {
 216     jchar c = from_buffer->char_at(index + offset);
 217     if (c == from_char) {
 218       c = to_char;
 219     }
 220     to_buffer->char_at_put(index, c);
 221   }
 222   return string;
 223 }
 224 
 225 jchar* java_lang_String::as_unicode_string(oop java_string, int& length) {
 226   typeArrayOop value  = java_lang_String::value(java_string);
 227   int          offset = java_lang_String::offset(java_string);
 228                length = java_lang_String::length(java_string);
 229 
 230   jchar* result = NEW_RESOURCE_ARRAY(jchar, length);
 231   for (int index = 0; index < length; index++) {
 232     result[index] = value->char_at(index + offset);
 233   }
 234   return result;
 235 }
 236 
 237 symbolHandle java_lang_String::as_symbol(Handle java_string, TRAPS) {
 238   oop          obj    = java_string();
 239   typeArrayOop value  = java_lang_String::value(obj);
 240   int          offset = java_lang_String::offset(obj);
 241   int          length = java_lang_String::length(obj);
 242 
 243   ResourceMark rm(THREAD);
 244   symbolHandle result;
 245 
 246   if (length > 0) {
 247     int utf8_length = UNICODE::utf8_length(value->char_at_addr(offset), length);
 248     char* chars = NEW_RESOURCE_ARRAY(char, utf8_length + 1);
 249     UNICODE::convert_to_utf8(value->char_at_addr(offset), length, chars);
 250     // Allocate the symbol
 251     result = oopFactory::new_symbol_handle(chars, utf8_length, CHECK_(symbolHandle()));
 252   } else {
 253     result = oopFactory::new_symbol_handle("", 0, CHECK_(symbolHandle()));
 254   }
 255   return result;
 256 }
 257 
 258 int java_lang_String::utf8_length(oop java_string) {
 259   typeArrayOop value  = java_lang_String::value(java_string);
 260   int          offset = java_lang_String::offset(java_string);
 261   int          length = java_lang_String::length(java_string);
 262   jchar* position = (length == 0) ? NULL : value->char_at_addr(offset);
 263   return UNICODE::utf8_length(position, length);
 264 }
 265 
 266 char* java_lang_String::as_utf8_string(oop java_string) {
 267   typeArrayOop value  = java_lang_String::value(java_string);
 268   int          offset = java_lang_String::offset(java_string);
 269   int          length = java_lang_String::length(java_string);
 270   jchar* position = (length == 0) ? NULL : value->char_at_addr(offset);
 271   return UNICODE::as_utf8(position, length);
 272 }
 273 
 274 char* java_lang_String::as_utf8_string(oop java_string, int start, int len) {
 275   typeArrayOop value  = java_lang_String::value(java_string);
 276   int          offset = java_lang_String::offset(java_string);
 277   int          length = java_lang_String::length(java_string);
 278   assert(start + len <= length, "just checking");
 279   jchar* position = value->char_at_addr(offset + start);
 280   return UNICODE::as_utf8(position, len);
 281 }
 282 
 283 bool java_lang_String::equals(oop java_string, jchar* chars, int len) {
 284   assert(SharedSkipVerify ||
 285          java_string->klass() == SystemDictionary::string_klass(),
 286          "must be java_string");
 287   typeArrayOop value  = java_lang_String::value(java_string);
 288   int          offset = java_lang_String::offset(java_string);
 289   int          length = java_lang_String::length(java_string);
 290   if (length != len) {
 291     return false;
 292   }
 293   for (int i = 0; i < len; i++) {
 294     if (value->char_at(i + offset) != chars[i]) {
 295       return false;
 296     }
 297   }
 298   return true;
 299 }
 300 
 301 void java_lang_String::print(Handle java_string, outputStream* st) {
 302   oop          obj    = java_string();
 303   assert(obj->klass() == SystemDictionary::string_klass(), "must be java_string");
 304   typeArrayOop value  = java_lang_String::value(obj);
 305   int          offset = java_lang_String::offset(obj);
 306   int          length = java_lang_String::length(obj);
 307 
 308   int end = MIN2(length, 100);
 309   if (value == NULL) {
 310     // This can happen if, e.g., printing a String
 311     // object before its initializer has been called
 312     st->print_cr("NULL");
 313   } else {
 314     st->print("\"");
 315     for (int index = 0; index < length; index++) {
 316       st->print("%c", value->char_at(index + offset));
 317     }
 318     st->print("\"");
 319   }
 320 }
 321 
 322 
 323 oop java_lang_Class::create_mirror(KlassHandle k, TRAPS) {
 324   assert(k->java_mirror() == NULL, "should only assign mirror once");
 325   // Use this moment of initialization to cache modifier_flags also,
 326   // to support Class.getModifiers().  Instance classes recalculate
 327   // the cached flags after the class file is parsed, but before the
 328   // class is put into the system dictionary.
 329   int computed_modifiers = k->compute_modifier_flags(CHECK_0);
 330   k->set_modifier_flags(computed_modifiers);
 331   if (SystemDictionary::class_klass_loaded()) {
 332     // Allocate mirror (java.lang.Class instance)
 333     Handle mirror = instanceKlass::cast(SystemDictionary::class_klass())->allocate_permanent_instance(CHECK_0);
 334     // Setup indirections
 335     mirror->obj_field_put(klass_offset,  k());
 336     k->set_java_mirror(mirror());
 337     // It might also have a component mirror.  This mirror must already exist.
 338     if (k->oop_is_javaArray()) {
 339       Handle comp_mirror;
 340       if (k->oop_is_typeArray()) {
 341         BasicType type = typeArrayKlass::cast(k->as_klassOop())->element_type();
 342         comp_mirror = Universe::java_mirror(type);
 343         assert(comp_mirror.not_null(), "must have primitive mirror");
 344       } else if (k->oop_is_objArray()) {
 345         klassOop element_klass = objArrayKlass::cast(k->as_klassOop())->element_klass();
 346         if (element_klass != NULL
 347             && (Klass::cast(element_klass)->oop_is_instance() ||
 348                 Klass::cast(element_klass)->oop_is_javaArray())) {
 349           comp_mirror = Klass::cast(element_klass)->java_mirror();
 350           assert(comp_mirror.not_null(), "must have element mirror");
 351         }
 352         // else some object array internal to the VM, like systemObjArrayKlassObj
 353       }
 354       if (comp_mirror.not_null()) {
 355         // Two-way link between the array klass and its component mirror:
 356         arrayKlass::cast(k->as_klassOop())->set_component_mirror(comp_mirror());
 357         set_array_klass(comp_mirror(), k->as_klassOop());
 358       }
 359     }
 360     return mirror();
 361   } else {
 362     return NULL;
 363   }
 364 }
 365 
 366 
 367 oop java_lang_Class::create_basic_type_mirror(const char* basic_type_name, BasicType type, TRAPS) {
 368   // This should be improved by adding a field at the Java level or by
 369   // introducing a new VM klass (see comment in ClassFileParser)
 370   oop java_class = instanceKlass::cast(SystemDictionary::class_klass())->allocate_permanent_instance(CHECK_0);
 371   if (type != T_VOID) {
 372     klassOop aklass = Universe::typeArrayKlassObj(type);
 373     assert(aklass != NULL, "correct bootstrap");
 374     set_array_klass(java_class, aklass);
 375   }
 376   return java_class;
 377 }
 378 
 379 
 380 klassOop java_lang_Class::as_klassOop(oop java_class) {
 381   //%note memory_2
 382   klassOop k = klassOop(java_class->obj_field(klass_offset));
 383   assert(k == NULL || k->is_klass(), "type check");
 384   return k;
 385 }
 386 
 387 
 388 klassOop java_lang_Class::array_klass(oop java_class) {
 389   klassOop k = klassOop(java_class->obj_field(array_klass_offset));
 390   assert(k == NULL || k->is_klass() && Klass::cast(k)->oop_is_javaArray(), "should be array klass");
 391   return k;
 392 }
 393 
 394 
 395 void java_lang_Class::set_array_klass(oop java_class, klassOop klass) {
 396   assert(klass->is_klass() && Klass::cast(klass)->oop_is_javaArray(), "should be array klass");
 397   java_class->obj_field_put(array_klass_offset, klass);
 398 }
 399 
 400 
 401 methodOop java_lang_Class::resolved_constructor(oop java_class) {
 402   oop constructor = java_class->obj_field(resolved_constructor_offset);
 403   assert(constructor == NULL || constructor->is_method(), "should be method");
 404   return methodOop(constructor);
 405 }
 406 
 407 
 408 void java_lang_Class::set_resolved_constructor(oop java_class, methodOop constructor) {
 409   assert(constructor->is_method(), "should be method");
 410   java_class->obj_field_put(resolved_constructor_offset, constructor);
 411 }
 412 
 413 
 414 bool java_lang_Class::is_primitive(oop java_class) {
 415   klassOop k = klassOop(java_class->obj_field(klass_offset));
 416   return k == NULL;
 417 }
 418 
 419 
 420 BasicType java_lang_Class::primitive_type(oop java_class) {
 421   assert(java_lang_Class::is_primitive(java_class), "just checking");
 422   klassOop ak = klassOop(java_class->obj_field(array_klass_offset));
 423   BasicType type = T_VOID;
 424   if (ak != NULL) {
 425     // Note: create_basic_type_mirror above initializes ak to a non-null value.
 426     type = arrayKlass::cast(ak)->element_type();
 427   } else {
 428     assert(java_class == Universe::void_mirror(), "only valid non-array primitive");
 429   }
 430   assert(Universe::java_mirror(type) == java_class, "must be consistent");
 431   return type;
 432 }
 433 
 434 
 435 oop java_lang_Class::primitive_mirror(BasicType t) {
 436   oop mirror = Universe::java_mirror(t);
 437   assert(mirror != NULL && mirror->is_a(SystemDictionary::class_klass()), "must be a Class");
 438   assert(java_lang_Class::is_primitive(mirror), "must be primitive");
 439   return mirror;
 440 }
 441 
 442 bool java_lang_Class::offsets_computed = false;
 443 int  java_lang_Class::classRedefinedCount_offset = -1;
 444 
 445 void java_lang_Class::compute_offsets() {
 446   assert(!offsets_computed, "offsets should be initialized only once");
 447   offsets_computed = true;
 448 
 449   klassOop k = SystemDictionary::class_klass();
 450   // The classRedefinedCount field is only present starting in 1.5,
 451   // so don't go fatal.
 452   compute_optional_offset(classRedefinedCount_offset,
 453     k, vmSymbols::classRedefinedCount_name(), vmSymbols::int_signature());
 454 }
 455 
 456 int java_lang_Class::classRedefinedCount(oop the_class_mirror) {
 457   if (!JDK_Version::is_gte_jdk15x_version()
 458       || classRedefinedCount_offset == -1) {
 459     // The classRedefinedCount field is only present starting in 1.5.
 460     // If we don't have an offset for it then just return -1 as a marker.
 461     return -1;
 462   }
 463 
 464   return the_class_mirror->int_field(classRedefinedCount_offset);
 465 }
 466 
 467 void java_lang_Class::set_classRedefinedCount(oop the_class_mirror, int value) {
 468   if (!JDK_Version::is_gte_jdk15x_version()
 469       || classRedefinedCount_offset == -1) {
 470     // The classRedefinedCount field is only present starting in 1.5.
 471     // If we don't have an offset for it then nothing to set.
 472     return;
 473   }
 474 
 475   the_class_mirror->int_field_put(classRedefinedCount_offset, value);
 476 }
 477 
 478 
 479 // Note: JDK1.1 and before had a privateInfo_offset field which was used for the
 480 //       platform thread structure, and a eetop offset which was used for thread
 481 //       local storage (and unused by the HotSpot VM). In JDK1.2 the two structures
 482 //       merged, so in the HotSpot VM we just use the eetop field for the thread
 483 //       instead of the privateInfo_offset.
 484 //
 485 // Note: The stackSize field is only present starting in 1.4.
 486 
 487 int java_lang_Thread::_name_offset = 0;
 488 int java_lang_Thread::_group_offset = 0;
 489 int java_lang_Thread::_contextClassLoader_offset = 0;
 490 int java_lang_Thread::_inheritedAccessControlContext_offset = 0;
 491 int java_lang_Thread::_priority_offset = 0;
 492 int java_lang_Thread::_eetop_offset = 0;
 493 int java_lang_Thread::_daemon_offset = 0;
 494 int java_lang_Thread::_stillborn_offset = 0;
 495 int java_lang_Thread::_stackSize_offset = 0;
 496 int java_lang_Thread::_tid_offset = 0;
 497 int java_lang_Thread::_thread_status_offset = 0;
 498 int java_lang_Thread::_park_blocker_offset = 0;
 499 int java_lang_Thread::_park_event_offset = 0 ;
 500 
 501 
 502 void java_lang_Thread::compute_offsets() {
 503   assert(_group_offset == 0, "offsets should be initialized only once");
 504 
 505   klassOop k = SystemDictionary::thread_klass();
 506   compute_offset(_name_offset,      k, vmSymbols::name_name(),      vmSymbols::char_array_signature());
 507   compute_offset(_group_offset,     k, vmSymbols::group_name(),     vmSymbols::threadgroup_signature());
 508   compute_offset(_contextClassLoader_offset, k, vmSymbols::contextClassLoader_name(), vmSymbols::classloader_signature());
 509   compute_offset(_inheritedAccessControlContext_offset, k, vmSymbols::inheritedAccessControlContext_name(), vmSymbols::accesscontrolcontext_signature());
 510   compute_offset(_priority_offset,  k, vmSymbols::priority_name(),  vmSymbols::int_signature());
 511   compute_offset(_daemon_offset,    k, vmSymbols::daemon_name(),    vmSymbols::bool_signature());
 512   compute_offset(_eetop_offset,     k, vmSymbols::eetop_name(),     vmSymbols::long_signature());
 513   compute_offset(_stillborn_offset, k, vmSymbols::stillborn_name(), vmSymbols::bool_signature());
 514   // The stackSize field is only present starting in 1.4, so don't go fatal.
 515   compute_optional_offset(_stackSize_offset, k, vmSymbols::stackSize_name(), vmSymbols::long_signature());
 516   // The tid and thread_status fields are only present starting in 1.5, so don't go fatal.
 517   compute_optional_offset(_tid_offset, k, vmSymbols::thread_id_name(), vmSymbols::long_signature());
 518   compute_optional_offset(_thread_status_offset, k, vmSymbols::thread_status_name(), vmSymbols::int_signature());
 519   // The parkBlocker field is only present starting in 1.6, so don't go fatal.
 520   compute_optional_offset(_park_blocker_offset, k, vmSymbols::park_blocker_name(), vmSymbols::object_signature());
 521   compute_optional_offset(_park_event_offset, k, vmSymbols::park_event_name(),
 522  vmSymbols::long_signature());
 523 }
 524 
 525 
 526 JavaThread* java_lang_Thread::thread(oop java_thread) {
 527   return (JavaThread*)java_thread->address_field(_eetop_offset);
 528 }
 529 
 530 
 531 void java_lang_Thread::set_thread(oop java_thread, JavaThread* thread) {
 532   java_thread->address_field_put(_eetop_offset, (address)thread);
 533 }
 534 
 535 
 536 typeArrayOop java_lang_Thread::name(oop java_thread) {
 537   oop name = java_thread->obj_field(_name_offset);
 538   assert(name == NULL || (name->is_typeArray() && typeArrayKlass::cast(name->klass())->element_type() == T_CHAR), "just checking");
 539   return typeArrayOop(name);
 540 }
 541 
 542 
 543 void java_lang_Thread::set_name(oop java_thread, typeArrayOop name) {
 544   assert(java_thread->obj_field(_name_offset) == NULL, "name should be NULL");
 545   java_thread->obj_field_put(_name_offset, name);
 546 }
 547 
 548 
 549 ThreadPriority java_lang_Thread::priority(oop java_thread) {
 550   return (ThreadPriority)java_thread->int_field(_priority_offset);
 551 }
 552 
 553 
 554 void java_lang_Thread::set_priority(oop java_thread, ThreadPriority priority) {
 555   java_thread->int_field_put(_priority_offset, priority);
 556 }
 557 
 558 
 559 oop java_lang_Thread::threadGroup(oop java_thread) {
 560   return java_thread->obj_field(_group_offset);
 561 }
 562 
 563 
 564 bool java_lang_Thread::is_stillborn(oop java_thread) {
 565   return java_thread->bool_field(_stillborn_offset) != 0;
 566 }
 567 
 568 
 569 // We never have reason to turn the stillborn bit off
 570 void java_lang_Thread::set_stillborn(oop java_thread) {
 571   java_thread->bool_field_put(_stillborn_offset, true);
 572 }
 573 
 574 
 575 bool java_lang_Thread::is_alive(oop java_thread) {
 576   JavaThread* thr = java_lang_Thread::thread(java_thread);
 577   return (thr != NULL);
 578 }
 579 
 580 
 581 bool java_lang_Thread::is_daemon(oop java_thread) {
 582   return java_thread->bool_field(_daemon_offset) != 0;
 583 }
 584 
 585 
 586 void java_lang_Thread::set_daemon(oop java_thread) {
 587   java_thread->bool_field_put(_daemon_offset, true);
 588 }
 589 
 590 oop java_lang_Thread::context_class_loader(oop java_thread) {
 591   return java_thread->obj_field(_contextClassLoader_offset);
 592 }
 593 
 594 oop java_lang_Thread::inherited_access_control_context(oop java_thread) {
 595   return java_thread->obj_field(_inheritedAccessControlContext_offset);
 596 }
 597 
 598 
 599 jlong java_lang_Thread::stackSize(oop java_thread) {
 600   // The stackSize field is only present starting in 1.4
 601   if (_stackSize_offset > 0) {
 602     assert(JDK_Version::is_gte_jdk14x_version(), "sanity check");
 603     return java_thread->long_field(_stackSize_offset);
 604   } else {
 605     return 0;
 606   }
 607 }
 608 
 609 // Write the thread status value to threadStatus field in java.lang.Thread java class.
 610 void java_lang_Thread::set_thread_status(oop java_thread,
 611                                          java_lang_Thread::ThreadStatus status) {
 612   assert(JavaThread::current()->thread_state() == _thread_in_vm, "Java Thread is not running in vm");
 613   // The threadStatus is only present starting in 1.5
 614   if (_thread_status_offset > 0) {
 615     java_thread->int_field_put(_thread_status_offset, status);
 616   }
 617 }
 618 
 619 // Read thread status value from threadStatus field in java.lang.Thread java class.
 620 java_lang_Thread::ThreadStatus java_lang_Thread::get_thread_status(oop java_thread) {
 621   assert(Thread::current()->is_VM_thread() ||
 622          JavaThread::current()->thread_state() == _thread_in_vm,
 623          "Java Thread is not running in vm");
 624   // The threadStatus is only present starting in 1.5
 625   if (_thread_status_offset > 0) {
 626     return (java_lang_Thread::ThreadStatus)java_thread->int_field(_thread_status_offset);
 627   } else {
 628     // All we can easily figure out is if it is alive, but that is
 629     // enough info for a valid unknown status.
 630     // These aren't restricted to valid set ThreadStatus values, so
 631     // use JVMTI values and cast.
 632     JavaThread* thr = java_lang_Thread::thread(java_thread);
 633     if (thr == NULL) {
 634       // the thread hasn't run yet or is in the process of exiting
 635       return NEW;
 636     }
 637     return (java_lang_Thread::ThreadStatus)JVMTI_THREAD_STATE_ALIVE;
 638   }
 639 }
 640 
 641 
 642 jlong java_lang_Thread::thread_id(oop java_thread) {
 643   // The thread ID field is only present starting in 1.5
 644   if (_tid_offset > 0) {
 645     return java_thread->long_field(_tid_offset);
 646   } else {
 647     return 0;
 648   }
 649 }
 650 
 651 oop java_lang_Thread::park_blocker(oop java_thread) {
 652   assert(JDK_Version::supports_thread_park_blocker() && _park_blocker_offset != 0,
 653          "Must support parkBlocker field");
 654 
 655   if (_park_blocker_offset > 0) {
 656     return java_thread->obj_field(_park_blocker_offset);
 657   }
 658 
 659   return NULL;
 660 }
 661 
 662 jlong java_lang_Thread::park_event(oop java_thread) {
 663   if (_park_event_offset > 0) {
 664     return java_thread->long_field(_park_event_offset);
 665   }
 666   return 0;
 667 }
 668 
 669 bool java_lang_Thread::set_park_event(oop java_thread, jlong ptr) {
 670   if (_park_event_offset > 0) {
 671     java_thread->long_field_put(_park_event_offset, ptr);
 672     return true;
 673   }
 674   return false;
 675 }
 676 
 677 
 678 const char* java_lang_Thread::thread_status_name(oop java_thread) {
 679   assert(JDK_Version::is_gte_jdk15x_version() && _thread_status_offset != 0, "Must have thread status");
 680   ThreadStatus status = (java_lang_Thread::ThreadStatus)java_thread->int_field(_thread_status_offset);
 681   switch (status) {
 682     case NEW                      : return "NEW";
 683     case RUNNABLE                 : return "RUNNABLE";
 684     case SLEEPING                 : return "TIMED_WAITING (sleeping)";
 685     case IN_OBJECT_WAIT           : return "WAITING (on object monitor)";
 686     case IN_OBJECT_WAIT_TIMED     : return "TIMED_WAITING (on object monitor)";
 687     case PARKED                   : return "WAITING (parking)";
 688     case PARKED_TIMED             : return "TIMED_WAITING (parking)";
 689     case BLOCKED_ON_MONITOR_ENTER : return "BLOCKED (on object monitor)";
 690     case TERMINATED               : return "TERMINATED";
 691     default                       : return "UNKNOWN";
 692   };
 693 }
 694 int java_lang_ThreadGroup::_parent_offset = 0;
 695 int java_lang_ThreadGroup::_name_offset = 0;
 696 int java_lang_ThreadGroup::_threads_offset = 0;
 697 int java_lang_ThreadGroup::_groups_offset = 0;
 698 int java_lang_ThreadGroup::_maxPriority_offset = 0;
 699 int java_lang_ThreadGroup::_destroyed_offset = 0;
 700 int java_lang_ThreadGroup::_daemon_offset = 0;
 701 int java_lang_ThreadGroup::_vmAllowSuspension_offset = 0;
 702 int java_lang_ThreadGroup::_nthreads_offset = 0;
 703 int java_lang_ThreadGroup::_ngroups_offset = 0;
 704 
 705 oop  java_lang_ThreadGroup::parent(oop java_thread_group) {
 706   assert(java_thread_group->is_oop(), "thread group must be oop");
 707   return java_thread_group->obj_field(_parent_offset);
 708 }
 709 
 710 // ("name as oop" accessor is not necessary)
 711 
 712 typeArrayOop java_lang_ThreadGroup::name(oop java_thread_group) {
 713   oop name = java_thread_group->obj_field(_name_offset);
 714   // ThreadGroup.name can be null
 715   return name == NULL ? (typeArrayOop)NULL : java_lang_String::value(name);
 716 }
 717 
 718 int java_lang_ThreadGroup::nthreads(oop java_thread_group) {
 719   assert(java_thread_group->is_oop(), "thread group must be oop");
 720   return java_thread_group->int_field(_nthreads_offset);
 721 }
 722 
 723 objArrayOop java_lang_ThreadGroup::threads(oop java_thread_group) {
 724   oop threads = java_thread_group->obj_field(_threads_offset);
 725   assert(threads != NULL, "threadgroups should have threads");
 726   assert(threads->is_objArray(), "just checking"); // Todo: Add better type checking code
 727   return objArrayOop(threads);
 728 }
 729 
 730 int java_lang_ThreadGroup::ngroups(oop java_thread_group) {
 731   assert(java_thread_group->is_oop(), "thread group must be oop");
 732   return java_thread_group->int_field(_ngroups_offset);
 733 }
 734 
 735 objArrayOop java_lang_ThreadGroup::groups(oop java_thread_group) {
 736   oop groups = java_thread_group->obj_field(_groups_offset);
 737   assert(groups == NULL || groups->is_objArray(), "just checking"); // Todo: Add better type checking code
 738   return objArrayOop(groups);
 739 }
 740 
 741 ThreadPriority java_lang_ThreadGroup::maxPriority(oop java_thread_group) {
 742   assert(java_thread_group->is_oop(), "thread group must be oop");
 743   return (ThreadPriority) java_thread_group->int_field(_maxPriority_offset);
 744 }
 745 
 746 bool java_lang_ThreadGroup::is_destroyed(oop java_thread_group) {
 747   assert(java_thread_group->is_oop(), "thread group must be oop");
 748   return java_thread_group->bool_field(_destroyed_offset) != 0;
 749 }
 750 
 751 bool java_lang_ThreadGroup::is_daemon(oop java_thread_group) {
 752   assert(java_thread_group->is_oop(), "thread group must be oop");
 753   return java_thread_group->bool_field(_daemon_offset) != 0;
 754 }
 755 
 756 bool java_lang_ThreadGroup::is_vmAllowSuspension(oop java_thread_group) {
 757   assert(java_thread_group->is_oop(), "thread group must be oop");
 758   return java_thread_group->bool_field(_vmAllowSuspension_offset) != 0;
 759 }
 760 
 761 void java_lang_ThreadGroup::compute_offsets() {
 762   assert(_parent_offset == 0, "offsets should be initialized only once");
 763 
 764   klassOop k = SystemDictionary::threadGroup_klass();
 765 
 766   compute_offset(_parent_offset,      k, vmSymbols::parent_name(),      vmSymbols::threadgroup_signature());
 767   compute_offset(_name_offset,        k, vmSymbols::name_name(),        vmSymbols::string_signature());
 768   compute_offset(_threads_offset,     k, vmSymbols::threads_name(),     vmSymbols::thread_array_signature());
 769   compute_offset(_groups_offset,      k, vmSymbols::groups_name(),      vmSymbols::threadgroup_array_signature());
 770   compute_offset(_maxPriority_offset, k, vmSymbols::maxPriority_name(), vmSymbols::int_signature());
 771   compute_offset(_destroyed_offset,   k, vmSymbols::destroyed_name(),   vmSymbols::bool_signature());
 772   compute_offset(_daemon_offset,      k, vmSymbols::daemon_name(),      vmSymbols::bool_signature());
 773   compute_offset(_vmAllowSuspension_offset, k, vmSymbols::vmAllowSuspension_name(), vmSymbols::bool_signature());
 774   compute_offset(_nthreads_offset,    k, vmSymbols::nthreads_name(),    vmSymbols::int_signature());
 775   compute_offset(_ngroups_offset,     k, vmSymbols::ngroups_name(),     vmSymbols::int_signature());
 776 }
 777 
 778 oop java_lang_Throwable::backtrace(oop throwable) {
 779   return throwable->obj_field_acquire(backtrace_offset);
 780 }
 781 
 782 
 783 void java_lang_Throwable::set_backtrace(oop throwable, oop value) {
 784   throwable->release_obj_field_put(backtrace_offset, value);
 785 }
 786 
 787 
 788 oop java_lang_Throwable::message(oop throwable) {
 789   return throwable->obj_field(detailMessage_offset);
 790 }
 791 
 792 
 793 oop java_lang_Throwable::message(Handle throwable) {
 794   return throwable->obj_field(detailMessage_offset);
 795 }
 796 
 797 
 798 void java_lang_Throwable::set_message(oop throwable, oop value) {
 799   throwable->obj_field_put(detailMessage_offset, value);
 800 }
 801 
 802 
 803 void java_lang_Throwable::clear_stacktrace(oop throwable) {
 804   assert(JDK_Version::is_gte_jdk14x_version(), "should only be called in >= 1.4");
 805   throwable->obj_field_put(stackTrace_offset, NULL);
 806 }
 807 
 808 
 809 void java_lang_Throwable::print(oop throwable, outputStream* st) {
 810   ResourceMark rm;
 811   klassOop k = throwable->klass();
 812   assert(k != NULL, "just checking");
 813   st->print("%s", instanceKlass::cast(k)->external_name());
 814   oop msg = message(throwable);
 815   if (msg != NULL) {
 816     st->print(": %s", java_lang_String::as_utf8_string(msg));
 817   }
 818 }
 819 
 820 
 821 void java_lang_Throwable::print(Handle throwable, outputStream* st) {
 822   ResourceMark rm;
 823   klassOop k = throwable->klass();
 824   assert(k != NULL, "just checking");
 825   st->print("%s", instanceKlass::cast(k)->external_name());
 826   oop msg = message(throwable);
 827   if (msg != NULL) {
 828     st->print(": %s", java_lang_String::as_utf8_string(msg));
 829   }
 830 }
 831 
 832 // Print stack trace element to resource allocated buffer
 833 char* java_lang_Throwable::print_stack_element_to_buffer(methodOop method, int bci) {
 834   // Get strings and string lengths
 835   instanceKlass* klass = instanceKlass::cast(method->method_holder());
 836   const char* klass_name  = klass->external_name();
 837   int buf_len = (int)strlen(klass_name);
 838   char* source_file_name;
 839   if (klass->source_file_name() == NULL) {
 840     source_file_name = NULL;
 841   } else {
 842     source_file_name = klass->source_file_name()->as_C_string();
 843     buf_len += (int)strlen(source_file_name);
 844   }
 845   char* method_name = method->name()->as_C_string();
 846   buf_len += (int)strlen(method_name);
 847 
 848   // Allocate temporary buffer with extra space for formatting and line number
 849   char* buf = NEW_RESOURCE_ARRAY(char, buf_len + 64);
 850 
 851   // Print stack trace line in buffer
 852   sprintf(buf, "\tat %s.%s", klass_name, method_name);
 853   if (method->is_native()) {
 854     strcat(buf, "(Native Method)");
 855   } else {
 856     int line_number = method->line_number_from_bci(bci);
 857     if (source_file_name != NULL && (line_number != -1)) {
 858       // Sourcename and linenumber
 859       sprintf(buf + (int)strlen(buf), "(%s:%d)", source_file_name, line_number);
 860     } else if (source_file_name != NULL) {
 861       // Just sourcename
 862       sprintf(buf + (int)strlen(buf), "(%s)", source_file_name);
 863     } else {
 864       // Neither soucename and linenumber
 865       sprintf(buf + (int)strlen(buf), "(Unknown Source)");
 866     }
 867     nmethod* nm = method->code();
 868     if (WizardMode && nm != NULL) {
 869       sprintf(buf + (int)strlen(buf), "(nmethod %#x)", nm);
 870     }
 871   }
 872 
 873   return buf;
 874 }
 875 
 876 
 877 void java_lang_Throwable::print_stack_element(Handle stream, methodOop method, int bci) {
 878   ResourceMark rm;
 879   char* buf = print_stack_element_to_buffer(method, bci);
 880   print_to_stream(stream, buf);
 881 }
 882 
 883 void java_lang_Throwable::print_stack_element(outputStream *st, methodOop method, int bci) {
 884   ResourceMark rm;
 885   char* buf = print_stack_element_to_buffer(method, bci);
 886   st->print_cr("%s", buf);
 887 }
 888 
 889 void java_lang_Throwable::print_to_stream(Handle stream, const char* str) {
 890   if (stream.is_null()) {
 891     tty->print_cr("%s", str);
 892   } else {
 893     EXCEPTION_MARK;
 894     JavaValue result(T_VOID);
 895     Handle arg (THREAD, oopFactory::new_charArray(str, THREAD));
 896     if (!HAS_PENDING_EXCEPTION) {
 897       JavaCalls::call_virtual(&result,
 898                               stream,
 899                               KlassHandle(THREAD, stream->klass()),
 900                               vmSymbolHandles::println_name(),
 901                               vmSymbolHandles::char_array_void_signature(),
 902                               arg,
 903                               THREAD);
 904     }
 905     // Ignore any exceptions. we are in the middle of exception handling. Same as classic VM.
 906     if (HAS_PENDING_EXCEPTION) CLEAR_PENDING_EXCEPTION;
 907   }
 908 
 909 }
 910 
 911 
 912 const char* java_lang_Throwable::no_stack_trace_message() {
 913   return "\t<<no stack trace available>>";
 914 }
 915 
 916 
 917 // Currently used only for exceptions occurring during startup
 918 void java_lang_Throwable::print_stack_trace(oop throwable, outputStream* st) {
 919   Thread *THREAD = Thread::current();
 920   Handle h_throwable(THREAD, throwable);
 921   while (h_throwable.not_null()) {
 922     objArrayHandle result (THREAD, objArrayOop(backtrace(h_throwable())));
 923     if (result.is_null()) {
 924       st->print_cr(no_stack_trace_message());
 925       return;
 926     }
 927 
 928     while (result.not_null()) {
 929       objArrayHandle methods (THREAD,
 930                               objArrayOop(result->obj_at(trace_methods_offset)));
 931       typeArrayHandle bcis (THREAD,
 932                             typeArrayOop(result->obj_at(trace_bcis_offset)));
 933 
 934       if (methods.is_null() || bcis.is_null()) {
 935         st->print_cr(no_stack_trace_message());
 936         return;
 937       }
 938 
 939       int length = methods()->length();
 940       for (int index = 0; index < length; index++) {
 941         methodOop method = methodOop(methods()->obj_at(index));
 942         if (method == NULL) goto handle_cause;
 943         int bci = bcis->ushort_at(index);
 944         print_stack_element(st, method, bci);
 945       }
 946       result = objArrayHandle(THREAD, objArrayOop(result->obj_at(trace_next_offset)));
 947     }
 948   handle_cause:
 949     {
 950       EXCEPTION_MARK;
 951       JavaValue result(T_OBJECT);
 952       JavaCalls::call_virtual(&result,
 953                               h_throwable,
 954                               KlassHandle(THREAD, h_throwable->klass()),
 955                               vmSymbolHandles::getCause_name(),
 956                               vmSymbolHandles::void_throwable_signature(),
 957                               THREAD);
 958       // Ignore any exceptions. we are in the middle of exception handling. Same as classic VM.
 959       if (HAS_PENDING_EXCEPTION) {
 960         CLEAR_PENDING_EXCEPTION;
 961         h_throwable = Handle();
 962       } else {
 963         h_throwable = Handle(THREAD, (oop) result.get_jobject());
 964         if (h_throwable.not_null()) {
 965           st->print("Caused by: ");
 966           print(h_throwable, st);
 967           st->cr();
 968         }
 969       }
 970     }
 971   }
 972 }
 973 
 974 
 975 void java_lang_Throwable::print_stack_trace(oop throwable, oop print_stream) {
 976   // Note: this is no longer used in Merlin, but we support it for compatibility.
 977   Thread *thread = Thread::current();
 978   Handle stream(thread, print_stream);
 979   objArrayHandle result (thread, objArrayOop(backtrace(throwable)));
 980   if (result.is_null()) {
 981     print_to_stream(stream, no_stack_trace_message());
 982     return;
 983   }
 984 
 985   while (result.not_null()) {
 986     objArrayHandle methods (thread,
 987                             objArrayOop(result->obj_at(trace_methods_offset)));
 988     typeArrayHandle bcis (thread,
 989                           typeArrayOop(result->obj_at(trace_bcis_offset)));
 990 
 991     if (methods.is_null() || bcis.is_null()) {
 992       print_to_stream(stream, no_stack_trace_message());
 993       return;
 994     }
 995 
 996     int length = methods()->length();
 997     for (int index = 0; index < length; index++) {
 998       methodOop method = methodOop(methods()->obj_at(index));
 999       if (method == NULL) return;
1000       int bci = bcis->ushort_at(index);
1001       print_stack_element(stream, method, bci);
1002     }
1003     result = objArrayHandle(thread, objArrayOop(result->obj_at(trace_next_offset)));
1004   }
1005 }
1006 
1007 // This class provides a simple wrapper over the internal structure of
1008 // exception backtrace to insulate users of the backtrace from needing
1009 // to know what it looks like.
1010 class BacktraceBuilder: public StackObj {
1011  private:
1012   Handle          _backtrace;
1013   objArrayOop     _head;
1014   objArrayOop     _methods;
1015   typeArrayOop    _bcis;
1016   int             _index;
1017   bool            _dirty;
1018   No_Safepoint_Verifier _nsv;
1019 
1020  public:
1021 
1022   enum {
1023     trace_methods_offset = java_lang_Throwable::trace_methods_offset,
1024     trace_bcis_offset    = java_lang_Throwable::trace_bcis_offset,
1025     trace_next_offset    = java_lang_Throwable::trace_next_offset,
1026     trace_size           = java_lang_Throwable::trace_size,
1027     trace_chunk_size     = java_lang_Throwable::trace_chunk_size
1028   };
1029 
1030   // constructor for new backtrace
1031   BacktraceBuilder(TRAPS): _methods(NULL), _bcis(NULL), _head(NULL), _dirty(false) {
1032     expand(CHECK);
1033     _backtrace = _head;
1034     _index = 0;
1035   }
1036 
1037   void flush() {
1038     if (_dirty && _methods != NULL) {
1039       BarrierSet* bs = Universe::heap()->barrier_set();
1040       assert(bs->has_write_ref_array_opt(), "Barrier set must have ref array opt");
1041       bs->write_ref_array(MemRegion((HeapWord*)_methods->base(),
1042                                     _methods->array_size()));
1043       _dirty = false;
1044     }
1045   }
1046 
1047   void expand(TRAPS) {
1048     flush();
1049 
1050     objArrayHandle old_head(THREAD, _head);
1051     Pause_No_Safepoint_Verifier pnsv(&_nsv);
1052 
1053     objArrayOop head = oopFactory::new_objectArray(trace_size, CHECK);
1054     objArrayHandle new_head(THREAD, head);
1055 
1056     objArrayOop methods = oopFactory::new_objectArray(trace_chunk_size, CHECK);
1057     objArrayHandle new_methods(THREAD, methods);
1058 
1059     typeArrayOop bcis = oopFactory::new_shortArray(trace_chunk_size, CHECK);
1060     typeArrayHandle new_bcis(THREAD, bcis);
1061 
1062     if (!old_head.is_null()) {
1063       old_head->obj_at_put(trace_next_offset, new_head());
1064     }
1065     new_head->obj_at_put(trace_methods_offset, new_methods());
1066     new_head->obj_at_put(trace_bcis_offset, new_bcis());
1067 
1068     _head    = new_head();
1069     _methods = new_methods();
1070     _bcis    = new_bcis();
1071     _index = 0;
1072   }
1073 
1074   oop backtrace() {
1075     flush();
1076     return _backtrace();
1077   }
1078 
1079   inline void push(methodOop method, short bci, TRAPS) {
1080     if (_index >= trace_chunk_size) {
1081       methodHandle mhandle(THREAD, method);
1082       expand(CHECK);
1083       method = mhandle();
1084     }
1085 
1086      _methods->obj_at_put(_index, method);
1087     // bad for UseCompressedOops
1088     // *_methods->obj_at_addr(_index) = method;
1089     _bcis->ushort_at_put(_index, bci);
1090     _index++;
1091     _dirty = true;
1092   }
1093 
1094   methodOop current_method() {
1095     assert(_index >= 0 && _index < trace_chunk_size, "out of range");
1096     return methodOop(_methods->obj_at(_index));
1097   }
1098 
1099   jushort current_bci() {
1100     assert(_index >= 0 && _index < trace_chunk_size, "out of range");
1101     return _bcis->ushort_at(_index);
1102   }
1103 };
1104 
1105 
1106 void java_lang_Throwable::fill_in_stack_trace(Handle throwable, TRAPS) {
1107   if (!StackTraceInThrowable) return;
1108   ResourceMark rm(THREAD);
1109 
1110   // Start out by clearing the backtrace for this object, in case the VM
1111   // runs out of memory while allocating the stack trace
1112   set_backtrace(throwable(), NULL);
1113   if (JDK_Version::is_gte_jdk14x_version()) {
1114     // New since 1.4, clear lazily constructed Java level stacktrace if
1115     // refilling occurs
1116     clear_stacktrace(throwable());
1117   }
1118 
1119   int max_depth = MaxJavaStackTraceDepth;
1120   JavaThread* thread = (JavaThread*)THREAD;
1121   BacktraceBuilder bt(CHECK);
1122 
1123   // Instead of using vframe directly, this version of fill_in_stack_trace
1124   // basically handles everything by hand. This significantly improved the
1125   // speed of this method call up to 28.5% on Solaris sparc. 27.1% on Windows.
1126   // See bug 6333838 for  more details.
1127   // The "ASSERT" here is to verify this method generates the exactly same stack
1128   // trace as utilizing vframe.
1129 #ifdef ASSERT
1130   vframeStream st(thread);
1131   methodHandle st_method(THREAD, st.method());
1132 #endif
1133   int total_count = 0;
1134   RegisterMap map(thread, false);
1135   int decode_offset = 0;
1136   nmethod* nm = NULL;
1137   bool skip_fillInStackTrace_check = false;
1138   bool skip_throwableInit_check = false;
1139 
1140   for (frame fr = thread->last_frame(); max_depth != total_count;) {
1141     methodOop method = NULL;
1142     int bci = 0;
1143 
1144     // Compiled java method case.
1145     if (decode_offset != 0) {
1146       DebugInfoReadStream stream(nm, decode_offset);
1147       decode_offset = stream.read_int();
1148       method = (methodOop)nm->oop_at(stream.read_int());
1149       bci = stream.read_bci();
1150     } else {
1151       if (fr.is_first_frame()) break;
1152       address pc = fr.pc();
1153       if (fr.is_interpreted_frame()) {
1154         intptr_t bcx = fr.interpreter_frame_bcx();
1155         method = fr.interpreter_frame_method();
1156         bci =  fr.is_bci(bcx) ? bcx : method->bci_from((address)bcx);
1157         fr = fr.sender(&map);
1158       } else {
1159         CodeBlob* cb = fr.cb();
1160         // HMMM QQQ might be nice to have frame return nm as NULL if cb is non-NULL
1161         // but non nmethod
1162         fr = fr.sender(&map);
1163         if (cb == NULL || !cb->is_nmethod()) {
1164           continue;
1165         }
1166         nm = (nmethod*)cb;
1167         if (nm->method()->is_native()) {
1168           method = nm->method();
1169           bci = 0;
1170         } else {
1171           PcDesc* pd = nm->pc_desc_at(pc);
1172           decode_offset = pd->scope_decode_offset();
1173           // if decode_offset is not equal to 0, it will execute the
1174           // "compiled java method case" at the beginning of the loop.
1175           continue;
1176         }
1177       }
1178     }
1179 #ifdef ASSERT
1180   assert(st_method() == method && st.bci() == bci,
1181          "Wrong stack trace");
1182   st.next();
1183   // vframeStream::method isn't GC-safe so store off a copy
1184   // of the methodOop in case we GC.
1185   if (!st.at_end()) {
1186     st_method = st.method();
1187   }
1188 #endif
1189     if (!skip_fillInStackTrace_check) {
1190       // check "fillInStackTrace" only once, so we negate the flag
1191       // after the first time check.
1192       skip_fillInStackTrace_check = true;
1193       if (method->name() == vmSymbols::fillInStackTrace_name()) {
1194         continue;
1195       }
1196     }
1197     // skip <init> methods of the exceptions klass. If there is <init> methods
1198     // that belongs to a superclass of the exception  we are going to skipping
1199     // them in stack trace. This is simlar to classic VM.
1200     if (!skip_throwableInit_check) {
1201       if (method->name() == vmSymbols::object_initializer_name() &&
1202           throwable->is_a(method->method_holder())) {
1203         continue;
1204       } else {
1205         // if no "Throwable.init()" method found, we stop checking it next time.
1206         skip_throwableInit_check = true;
1207       }
1208     }
1209     bt.push(method, bci, CHECK);
1210     total_count++;
1211   }
1212 
1213   // Put completed stack trace into throwable object
1214   set_backtrace(throwable(), bt.backtrace());
1215 }
1216 
1217 void java_lang_Throwable::fill_in_stack_trace(Handle throwable) {
1218   // No-op if stack trace is disabled
1219   if (!StackTraceInThrowable) {
1220     return;
1221   }
1222 
1223   // Disable stack traces for some preallocated out of memory errors
1224   if (!Universe::should_fill_in_stack_trace(throwable)) {
1225     return;
1226   }
1227 
1228   PRESERVE_EXCEPTION_MARK;
1229 
1230   JavaThread* thread = JavaThread::active();
1231   fill_in_stack_trace(throwable, thread);
1232   // ignore exceptions thrown during stack trace filling
1233   CLEAR_PENDING_EXCEPTION;
1234 }
1235 
1236 void java_lang_Throwable::allocate_backtrace(Handle throwable, TRAPS) {
1237   // Allocate stack trace - backtrace is created but not filled in
1238 
1239   // No-op if stack trace is disabled
1240   if (!StackTraceInThrowable) return;
1241 
1242   objArrayOop h_oop = oopFactory::new_objectArray(trace_size, CHECK);
1243   objArrayHandle backtrace  (THREAD, h_oop);
1244   objArrayOop m_oop = oopFactory::new_objectArray(trace_chunk_size, CHECK);
1245   objArrayHandle methods (THREAD, m_oop);
1246   typeArrayOop b = oopFactory::new_shortArray(trace_chunk_size, CHECK);
1247   typeArrayHandle bcis(THREAD, b);
1248 
1249   // backtrace has space for one chunk (next is NULL)
1250   backtrace->obj_at_put(trace_methods_offset, methods());
1251   backtrace->obj_at_put(trace_bcis_offset, bcis());
1252   set_backtrace(throwable(), backtrace());
1253 }
1254 
1255 
1256 void java_lang_Throwable::fill_in_stack_trace_of_preallocated_backtrace(Handle throwable) {
1257   // Fill in stack trace into preallocated backtrace (no GC)
1258 
1259   // No-op if stack trace is disabled
1260   if (!StackTraceInThrowable) return;
1261 
1262   assert(throwable->is_a(SystemDictionary::throwable_klass()), "sanity check");
1263 
1264   oop backtrace = java_lang_Throwable::backtrace(throwable());
1265   assert(backtrace != NULL, "backtrace not preallocated");
1266 
1267   oop m = objArrayOop(backtrace)->obj_at(trace_methods_offset);
1268   objArrayOop methods = objArrayOop(m);
1269   assert(methods != NULL && methods->length() > 0, "method array not preallocated");
1270 
1271   oop b = objArrayOop(backtrace)->obj_at(trace_bcis_offset);
1272   typeArrayOop bcis = typeArrayOop(b);
1273   assert(bcis != NULL, "bci array not preallocated");
1274 
1275   assert(methods->length() == bcis->length(), "method and bci arrays should match");
1276 
1277   JavaThread* thread = JavaThread::current();
1278   ResourceMark rm(thread);
1279   vframeStream st(thread);
1280 
1281   // Unlike fill_in_stack_trace we do not skip fillInStackTrace or throwable init
1282   // methods as preallocated errors aren't created by "java" code.
1283 
1284   // fill in as much stack trace as possible
1285   int max_chunks = MIN2(methods->length(), (int)MaxJavaStackTraceDepth);
1286   int chunk_count = 0;
1287 
1288   for (;!st.at_end(); st.next()) {
1289     // add element
1290     bcis->ushort_at_put(chunk_count, st.bci());
1291     methods->obj_at_put(chunk_count, st.method());
1292 
1293     chunk_count++;
1294 
1295     // Bail-out for deep stacks
1296     if (chunk_count >= max_chunks) break;
1297   }
1298 }
1299 
1300 
1301 int java_lang_Throwable::get_stack_trace_depth(oop throwable, TRAPS) {
1302   if (throwable == NULL) {
1303     THROW_0(vmSymbols::java_lang_NullPointerException());
1304   }
1305   objArrayOop chunk = objArrayOop(backtrace(throwable));
1306   int depth = 0;
1307   if (chunk != NULL) {
1308     // Iterate over chunks and count full ones
1309     while (true) {
1310       objArrayOop next = objArrayOop(chunk->obj_at(trace_next_offset));
1311       if (next == NULL) break;
1312       depth += trace_chunk_size;
1313       chunk = next;
1314     }
1315     assert(chunk != NULL && chunk->obj_at(trace_next_offset) == NULL, "sanity check");
1316     // Count element in remaining partial chunk
1317     objArrayOop methods = objArrayOop(chunk->obj_at(trace_methods_offset));
1318     typeArrayOop bcis = typeArrayOop(chunk->obj_at(trace_bcis_offset));
1319     assert(methods != NULL && bcis != NULL, "sanity check");
1320     for (int i = 0; i < methods->length(); i++) {
1321       if (methods->obj_at(i) == NULL) break;
1322       depth++;
1323     }
1324   }
1325   return depth;
1326 }
1327 
1328 
1329 oop java_lang_Throwable::get_stack_trace_element(oop throwable, int index, TRAPS) {
1330   if (throwable == NULL) {
1331     THROW_0(vmSymbols::java_lang_NullPointerException());
1332   }
1333   if (index < 0) {
1334     THROW_(vmSymbols::java_lang_IndexOutOfBoundsException(), NULL);
1335   }
1336   // Compute how many chunks to skip and index into actual chunk
1337   objArrayOop chunk = objArrayOop(backtrace(throwable));
1338   int skip_chunks = index / trace_chunk_size;
1339   int chunk_index = index % trace_chunk_size;
1340   while (chunk != NULL && skip_chunks > 0) {
1341     chunk = objArrayOop(chunk->obj_at(trace_next_offset));
1342         skip_chunks--;
1343   }
1344   if (chunk == NULL) {
1345     THROW_(vmSymbols::java_lang_IndexOutOfBoundsException(), NULL);
1346   }
1347   // Get method,bci from chunk
1348   objArrayOop methods = objArrayOop(chunk->obj_at(trace_methods_offset));
1349   typeArrayOop bcis = typeArrayOop(chunk->obj_at(trace_bcis_offset));
1350   assert(methods != NULL && bcis != NULL, "sanity check");
1351   methodHandle method(THREAD, methodOop(methods->obj_at(chunk_index)));
1352   int bci = bcis->ushort_at(chunk_index);
1353   // Chunk can be partial full
1354   if (method.is_null()) {
1355     THROW_(vmSymbols::java_lang_IndexOutOfBoundsException(), NULL);
1356   }
1357 
1358   oop element = java_lang_StackTraceElement::create(method, bci, CHECK_0);
1359   return element;
1360 }
1361 
1362 oop java_lang_StackTraceElement::create(methodHandle method, int bci, TRAPS) {
1363   // SystemDictionary::stackTraceElement_klass() will be null for pre-1.4 JDKs
1364   assert(JDK_Version::is_gte_jdk14x_version(), "should only be called in >= 1.4");
1365 
1366   // Allocate java.lang.StackTraceElement instance
1367   klassOop k = SystemDictionary::stackTraceElement_klass();
1368   assert(k != NULL, "must be loaded in 1.4+");
1369   instanceKlassHandle ik (THREAD, k);
1370   if (ik->should_be_initialized()) {
1371     ik->initialize(CHECK_0);
1372   }
1373 
1374   Handle element = ik->allocate_instance_handle(CHECK_0);
1375   // Fill in class name
1376   ResourceMark rm(THREAD);
1377   const char* str = instanceKlass::cast(method->method_holder())->external_name();
1378   oop classname = StringTable::intern((char*) str, CHECK_0);
1379   java_lang_StackTraceElement::set_declaringClass(element(), classname);
1380   // Fill in method name
1381   oop methodname = StringTable::intern(method->name(), CHECK_0);
1382   java_lang_StackTraceElement::set_methodName(element(), methodname);
1383   // Fill in source file name
1384   symbolOop source = instanceKlass::cast(method->method_holder())->source_file_name();
1385   oop filename = StringTable::intern(source, CHECK_0);
1386   java_lang_StackTraceElement::set_fileName(element(), filename);
1387   // File in source line number
1388   int line_number;
1389   if (method->is_native()) {
1390     // Negative value different from -1 below, enabling Java code in
1391     // class java.lang.StackTraceElement to distinguish "native" from
1392     // "no LineNumberTable".
1393     line_number = -2;
1394   } else {
1395     // Returns -1 if no LineNumberTable, and otherwise actual line number
1396     line_number = method->line_number_from_bci(bci);
1397   }
1398   java_lang_StackTraceElement::set_lineNumber(element(), line_number);
1399 
1400   return element();
1401 }
1402 
1403 
1404 void java_lang_reflect_AccessibleObject::compute_offsets() {
1405   klassOop k = SystemDictionary::reflect_accessible_object_klass();
1406   compute_offset(override_offset, k, vmSymbols::override_name(), vmSymbols::bool_signature());
1407 }
1408 
1409 jboolean java_lang_reflect_AccessibleObject::override(oop reflect) {
1410   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1411   return (jboolean) reflect->bool_field(override_offset);
1412 }
1413 
1414 void java_lang_reflect_AccessibleObject::set_override(oop reflect, jboolean value) {
1415   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1416   reflect->bool_field_put(override_offset, (int) value);
1417 }
1418 
1419 void java_lang_reflect_Method::compute_offsets() {
1420   klassOop k = SystemDictionary::reflect_method_klass();
1421   compute_offset(clazz_offset,          k, vmSymbols::clazz_name(),          vmSymbols::class_signature());
1422   compute_offset(name_offset,           k, vmSymbols::name_name(),           vmSymbols::string_signature());
1423   compute_offset(returnType_offset,     k, vmSymbols::returnType_name(),     vmSymbols::class_signature());
1424   compute_offset(parameterTypes_offset, k, vmSymbols::parameterTypes_name(), vmSymbols::class_array_signature());
1425   compute_offset(exceptionTypes_offset, k, vmSymbols::exceptionTypes_name(), vmSymbols::class_array_signature());
1426   compute_offset(slot_offset,           k, vmSymbols::slot_name(),           vmSymbols::int_signature());
1427   compute_offset(modifiers_offset,      k, vmSymbols::modifiers_name(),      vmSymbols::int_signature());
1428   // The generic signature and annotations fields are only present in 1.5
1429   signature_offset = -1;
1430   annotations_offset = -1;
1431   parameter_annotations_offset = -1;
1432   annotation_default_offset = -1;
1433   compute_optional_offset(signature_offset,             k, vmSymbols::signature_name(),             vmSymbols::string_signature());
1434   compute_optional_offset(annotations_offset,           k, vmSymbols::annotations_name(),           vmSymbols::byte_array_signature());
1435   compute_optional_offset(parameter_annotations_offset, k, vmSymbols::parameter_annotations_name(), vmSymbols::byte_array_signature());
1436   compute_optional_offset(annotation_default_offset,    k, vmSymbols::annotation_default_name(),    vmSymbols::byte_array_signature());
1437 }
1438 
1439 Handle java_lang_reflect_Method::create(TRAPS) {
1440   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1441   klassOop klass = SystemDictionary::reflect_method_klass();
1442   // This class is eagerly initialized during VM initialization, since we keep a refence
1443   // to one of the methods
1444   assert(instanceKlass::cast(klass)->is_initialized(), "must be initialized");
1445   return instanceKlass::cast(klass)->allocate_instance_handle(CHECK_NH);
1446 }
1447 
1448 oop java_lang_reflect_Method::clazz(oop reflect) {
1449   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1450   return reflect->obj_field(clazz_offset);
1451 }
1452 
1453 void java_lang_reflect_Method::set_clazz(oop reflect, oop value) {
1454   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1455    reflect->obj_field_put(clazz_offset, value);
1456 }
1457 
1458 int java_lang_reflect_Method::slot(oop reflect) {
1459   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1460   return reflect->int_field(slot_offset);
1461 }
1462 
1463 void java_lang_reflect_Method::set_slot(oop reflect, int value) {
1464   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1465   reflect->int_field_put(slot_offset, value);
1466 }
1467 
1468 oop java_lang_reflect_Method::name(oop method) {
1469   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1470   return method->obj_field(name_offset);
1471 }
1472 
1473 void java_lang_reflect_Method::set_name(oop method, oop value) {
1474   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1475   method->obj_field_put(name_offset, value);
1476 }
1477 
1478 oop java_lang_reflect_Method::return_type(oop method) {
1479   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1480   return method->obj_field(returnType_offset);
1481 }
1482 
1483 void java_lang_reflect_Method::set_return_type(oop method, oop value) {
1484   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1485   method->obj_field_put(returnType_offset, value);
1486 }
1487 
1488 oop java_lang_reflect_Method::parameter_types(oop method) {
1489   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1490   return method->obj_field(parameterTypes_offset);
1491 }
1492 
1493 void java_lang_reflect_Method::set_parameter_types(oop method, oop value) {
1494   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1495   method->obj_field_put(parameterTypes_offset, value);
1496 }
1497 
1498 oop java_lang_reflect_Method::exception_types(oop method) {
1499   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1500   return method->obj_field(exceptionTypes_offset);
1501 }
1502 
1503 void java_lang_reflect_Method::set_exception_types(oop method, oop value) {
1504   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1505   method->obj_field_put(exceptionTypes_offset, value);
1506 }
1507 
1508 int java_lang_reflect_Method::modifiers(oop method) {
1509   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1510   return method->int_field(modifiers_offset);
1511 }
1512 
1513 void java_lang_reflect_Method::set_modifiers(oop method, int value) {
1514   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1515   method->int_field_put(modifiers_offset, value);
1516 }
1517 
1518 bool java_lang_reflect_Method::has_signature_field() {
1519   return (signature_offset >= 0);
1520 }
1521 
1522 oop java_lang_reflect_Method::signature(oop method) {
1523   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1524   assert(has_signature_field(), "signature field must be present");
1525   return method->obj_field(signature_offset);
1526 }
1527 
1528 void java_lang_reflect_Method::set_signature(oop method, oop value) {
1529   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1530   assert(has_signature_field(), "signature field must be present");
1531   method->obj_field_put(signature_offset, value);
1532 }
1533 
1534 bool java_lang_reflect_Method::has_annotations_field() {
1535   return (annotations_offset >= 0);
1536 }
1537 
1538 oop java_lang_reflect_Method::annotations(oop method) {
1539   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1540   assert(has_annotations_field(), "annotations field must be present");
1541   return method->obj_field(annotations_offset);
1542 }
1543 
1544 void java_lang_reflect_Method::set_annotations(oop method, oop value) {
1545   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1546   assert(has_annotations_field(), "annotations field must be present");
1547   method->obj_field_put(annotations_offset, value);
1548 }
1549 
1550 bool java_lang_reflect_Method::has_parameter_annotations_field() {
1551   return (parameter_annotations_offset >= 0);
1552 }
1553 
1554 oop java_lang_reflect_Method::parameter_annotations(oop method) {
1555   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1556   assert(has_parameter_annotations_field(), "parameter annotations field must be present");
1557   return method->obj_field(parameter_annotations_offset);
1558 }
1559 
1560 void java_lang_reflect_Method::set_parameter_annotations(oop method, oop value) {
1561   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1562   assert(has_parameter_annotations_field(), "parameter annotations field must be present");
1563   method->obj_field_put(parameter_annotations_offset, value);
1564 }
1565 
1566 bool java_lang_reflect_Method::has_annotation_default_field() {
1567   return (annotation_default_offset >= 0);
1568 }
1569 
1570 oop java_lang_reflect_Method::annotation_default(oop method) {
1571   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1572   assert(has_annotation_default_field(), "annotation default field must be present");
1573   return method->obj_field(annotation_default_offset);
1574 }
1575 
1576 void java_lang_reflect_Method::set_annotation_default(oop method, oop value) {
1577   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1578   assert(has_annotation_default_field(), "annotation default field must be present");
1579   method->obj_field_put(annotation_default_offset, value);
1580 }
1581 
1582 void java_lang_reflect_Constructor::compute_offsets() {
1583   klassOop k = SystemDictionary::reflect_constructor_klass();
1584   compute_offset(clazz_offset,          k, vmSymbols::clazz_name(),          vmSymbols::class_signature());
1585   compute_offset(parameterTypes_offset, k, vmSymbols::parameterTypes_name(), vmSymbols::class_array_signature());
1586   compute_offset(exceptionTypes_offset, k, vmSymbols::exceptionTypes_name(), vmSymbols::class_array_signature());
1587   compute_offset(slot_offset,           k, vmSymbols::slot_name(),           vmSymbols::int_signature());
1588   compute_offset(modifiers_offset,      k, vmSymbols::modifiers_name(),      vmSymbols::int_signature());
1589   // The generic signature and annotations fields are only present in 1.5
1590   signature_offset = -1;
1591   annotations_offset = -1;
1592   parameter_annotations_offset = -1;
1593   compute_optional_offset(signature_offset,             k, vmSymbols::signature_name(),             vmSymbols::string_signature());
1594   compute_optional_offset(annotations_offset,           k, vmSymbols::annotations_name(),           vmSymbols::byte_array_signature());
1595   compute_optional_offset(parameter_annotations_offset, k, vmSymbols::parameter_annotations_name(), vmSymbols::byte_array_signature());
1596 }
1597 
1598 Handle java_lang_reflect_Constructor::create(TRAPS) {
1599   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1600   symbolHandle name = vmSymbolHandles::java_lang_reflect_Constructor();
1601   klassOop k = SystemDictionary::resolve_or_fail(name, true, CHECK_NH);
1602   instanceKlassHandle klass (THREAD, k);
1603   // Ensure it is initialized
1604   klass->initialize(CHECK_NH);
1605   return klass->allocate_instance_handle(CHECK_NH);
1606 }
1607 
1608 oop java_lang_reflect_Constructor::clazz(oop reflect) {
1609   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1610   return reflect->obj_field(clazz_offset);
1611 }
1612 
1613 void java_lang_reflect_Constructor::set_clazz(oop reflect, oop value) {
1614   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1615    reflect->obj_field_put(clazz_offset, value);
1616 }
1617 
1618 oop java_lang_reflect_Constructor::parameter_types(oop constructor) {
1619   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1620   return constructor->obj_field(parameterTypes_offset);
1621 }
1622 
1623 void java_lang_reflect_Constructor::set_parameter_types(oop constructor, oop value) {
1624   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1625   constructor->obj_field_put(parameterTypes_offset, value);
1626 }
1627 
1628 oop java_lang_reflect_Constructor::exception_types(oop constructor) {
1629   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1630   return constructor->obj_field(exceptionTypes_offset);
1631 }
1632 
1633 void java_lang_reflect_Constructor::set_exception_types(oop constructor, oop value) {
1634   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1635   constructor->obj_field_put(exceptionTypes_offset, value);
1636 }
1637 
1638 int java_lang_reflect_Constructor::slot(oop reflect) {
1639   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1640   return reflect->int_field(slot_offset);
1641 }
1642 
1643 void java_lang_reflect_Constructor::set_slot(oop reflect, int value) {
1644   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1645   reflect->int_field_put(slot_offset, value);
1646 }
1647 
1648 int java_lang_reflect_Constructor::modifiers(oop constructor) {
1649   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1650   return constructor->int_field(modifiers_offset);
1651 }
1652 
1653 void java_lang_reflect_Constructor::set_modifiers(oop constructor, int value) {
1654   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1655   constructor->int_field_put(modifiers_offset, value);
1656 }
1657 
1658 bool java_lang_reflect_Constructor::has_signature_field() {
1659   return (signature_offset >= 0);
1660 }
1661 
1662 oop java_lang_reflect_Constructor::signature(oop constructor) {
1663   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1664   assert(has_signature_field(), "signature field must be present");
1665   return constructor->obj_field(signature_offset);
1666 }
1667 
1668 void java_lang_reflect_Constructor::set_signature(oop constructor, oop value) {
1669   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1670   assert(has_signature_field(), "signature field must be present");
1671   constructor->obj_field_put(signature_offset, value);
1672 }
1673 
1674 bool java_lang_reflect_Constructor::has_annotations_field() {
1675   return (annotations_offset >= 0);
1676 }
1677 
1678 oop java_lang_reflect_Constructor::annotations(oop constructor) {
1679   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1680   assert(has_annotations_field(), "annotations field must be present");
1681   return constructor->obj_field(annotations_offset);
1682 }
1683 
1684 void java_lang_reflect_Constructor::set_annotations(oop constructor, oop value) {
1685   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1686   assert(has_annotations_field(), "annotations field must be present");
1687   constructor->obj_field_put(annotations_offset, value);
1688 }
1689 
1690 bool java_lang_reflect_Constructor::has_parameter_annotations_field() {
1691   return (parameter_annotations_offset >= 0);
1692 }
1693 
1694 oop java_lang_reflect_Constructor::parameter_annotations(oop method) {
1695   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1696   assert(has_parameter_annotations_field(), "parameter annotations field must be present");
1697   return method->obj_field(parameter_annotations_offset);
1698 }
1699 
1700 void java_lang_reflect_Constructor::set_parameter_annotations(oop method, oop value) {
1701   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1702   assert(has_parameter_annotations_field(), "parameter annotations field must be present");
1703   method->obj_field_put(parameter_annotations_offset, value);
1704 }
1705 
1706 void java_lang_reflect_Field::compute_offsets() {
1707   klassOop k = SystemDictionary::reflect_field_klass();
1708   compute_offset(clazz_offset,     k, vmSymbols::clazz_name(),     vmSymbols::class_signature());
1709   compute_offset(name_offset,      k, vmSymbols::name_name(),      vmSymbols::string_signature());
1710   compute_offset(type_offset,      k, vmSymbols::type_name(),      vmSymbols::class_signature());
1711   compute_offset(slot_offset,      k, vmSymbols::slot_name(),      vmSymbols::int_signature());
1712   compute_offset(modifiers_offset, k, vmSymbols::modifiers_name(), vmSymbols::int_signature());
1713   // The generic signature and annotations fields are only present in 1.5
1714   signature_offset = -1;
1715   annotations_offset = -1;
1716   compute_optional_offset(signature_offset, k, vmSymbols::signature_name(), vmSymbols::string_signature());
1717   compute_optional_offset(annotations_offset,  k, vmSymbols::annotations_name(),  vmSymbols::byte_array_signature());
1718 }
1719 
1720 Handle java_lang_reflect_Field::create(TRAPS) {
1721   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1722   symbolHandle name = vmSymbolHandles::java_lang_reflect_Field();
1723   klassOop k = SystemDictionary::resolve_or_fail(name, true, CHECK_NH);
1724   instanceKlassHandle klass (THREAD, k);
1725   // Ensure it is initialized
1726   klass->initialize(CHECK_NH);
1727   return klass->allocate_instance_handle(CHECK_NH);
1728 }
1729 
1730 oop java_lang_reflect_Field::clazz(oop reflect) {
1731   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1732   return reflect->obj_field(clazz_offset);
1733 }
1734 
1735 void java_lang_reflect_Field::set_clazz(oop reflect, oop value) {
1736   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1737    reflect->obj_field_put(clazz_offset, value);
1738 }
1739 
1740 oop java_lang_reflect_Field::name(oop field) {
1741   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1742   return field->obj_field(name_offset);
1743 }
1744 
1745 void java_lang_reflect_Field::set_name(oop field, oop value) {
1746   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1747   field->obj_field_put(name_offset, value);
1748 }
1749 
1750 oop java_lang_reflect_Field::type(oop field) {
1751   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1752   return field->obj_field(type_offset);
1753 }
1754 
1755 void java_lang_reflect_Field::set_type(oop field, oop value) {
1756   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1757   field->obj_field_put(type_offset, value);
1758 }
1759 
1760 int java_lang_reflect_Field::slot(oop reflect) {
1761   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1762   return reflect->int_field(slot_offset);
1763 }
1764 
1765 void java_lang_reflect_Field::set_slot(oop reflect, int value) {
1766   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1767   reflect->int_field_put(slot_offset, value);
1768 }
1769 
1770 int java_lang_reflect_Field::modifiers(oop field) {
1771   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1772   return field->int_field(modifiers_offset);
1773 }
1774 
1775 void java_lang_reflect_Field::set_modifiers(oop field, int value) {
1776   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1777   field->int_field_put(modifiers_offset, value);
1778 }
1779 
1780 bool java_lang_reflect_Field::has_signature_field() {
1781   return (signature_offset >= 0);
1782 }
1783 
1784 oop java_lang_reflect_Field::signature(oop field) {
1785   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1786   assert(has_signature_field(), "signature field must be present");
1787   return field->obj_field(signature_offset);
1788 }
1789 
1790 void java_lang_reflect_Field::set_signature(oop field, oop value) {
1791   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1792   assert(has_signature_field(), "signature field must be present");
1793   field->obj_field_put(signature_offset, value);
1794 }
1795 
1796 bool java_lang_reflect_Field::has_annotations_field() {
1797   return (annotations_offset >= 0);
1798 }
1799 
1800 oop java_lang_reflect_Field::annotations(oop field) {
1801   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1802   assert(has_annotations_field(), "annotations field must be present");
1803   return field->obj_field(annotations_offset);
1804 }
1805 
1806 void java_lang_reflect_Field::set_annotations(oop field, oop value) {
1807   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1808   assert(has_annotations_field(), "annotations field must be present");
1809   field->obj_field_put(annotations_offset, value);
1810 }
1811 
1812 
1813 void sun_reflect_ConstantPool::compute_offsets() {
1814   klassOop k = SystemDictionary::reflect_constant_pool_klass();
1815   // This null test can be removed post beta
1816   if (k != NULL) {
1817     compute_offset(_cp_oop_offset, k, vmSymbols::constantPoolOop_name(), vmSymbols::object_signature());
1818   }
1819 }
1820 
1821 
1822 Handle sun_reflect_ConstantPool::create(TRAPS) {
1823   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1824   klassOop k = SystemDictionary::reflect_constant_pool_klass();
1825   instanceKlassHandle klass (THREAD, k);
1826   // Ensure it is initialized
1827   klass->initialize(CHECK_NH);
1828   return klass->allocate_instance_handle(CHECK_NH);
1829 }
1830 
1831 
1832 oop sun_reflect_ConstantPool::cp_oop(oop reflect) {
1833   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1834   return reflect->obj_field(_cp_oop_offset);
1835 }
1836 
1837 
1838 void sun_reflect_ConstantPool::set_cp_oop(oop reflect, oop value) {
1839   assert(Universe::is_fully_initialized(), "Need to find another solution to the reflection problem");
1840   reflect->obj_field_put(_cp_oop_offset, value);
1841 }
1842 
1843 void sun_reflect_UnsafeStaticFieldAccessorImpl::compute_offsets() {
1844   klassOop k = SystemDictionary::reflect_unsafe_static_field_accessor_impl_klass();
1845   // This null test can be removed post beta
1846   if (k != NULL) {
1847     compute_offset(_base_offset, k,
1848                    vmSymbols::base_name(), vmSymbols::object_signature());
1849   }
1850 }
1851 
1852 oop java_lang_boxing_object::initialize_and_allocate(BasicType type, TRAPS) {
1853   klassOop k = SystemDictionary::box_klass(type);
1854   if (k == NULL)  return NULL;
1855   instanceKlassHandle h (THREAD, k);
1856   if (!h->is_initialized())  h->initialize(CHECK_0);
1857   return h->allocate_instance(THREAD);
1858 }
1859 
1860 
1861 oop java_lang_boxing_object::create(BasicType type, jvalue* value, TRAPS) {
1862   oop box = initialize_and_allocate(type, CHECK_0);
1863   if (box == NULL)  return NULL;
1864   switch (type) {
1865     case T_BOOLEAN:
1866       box->bool_field_put(value_offset, value->z);
1867       break;
1868     case T_CHAR:
1869       box->char_field_put(value_offset, value->c);
1870       break;
1871     case T_FLOAT:
1872       box->float_field_put(value_offset, value->f);
1873       break;
1874     case T_DOUBLE:
1875       box->double_field_put(long_value_offset, value->d);
1876       break;
1877     case T_BYTE:
1878       box->byte_field_put(value_offset, value->b);
1879       break;
1880     case T_SHORT:
1881       box->short_field_put(value_offset, value->s);
1882       break;
1883     case T_INT:
1884       box->int_field_put(value_offset, value->i);
1885       break;
1886     case T_LONG:
1887       box->long_field_put(long_value_offset, value->j);
1888       break;
1889     default:
1890       return NULL;
1891   }
1892   return box;
1893 }
1894 
1895 
1896 BasicType java_lang_boxing_object::basic_type(oop box) {
1897   if (box == NULL)  return T_ILLEGAL;
1898   BasicType type = SystemDictionary::box_klass_type(box->klass());
1899   if (type == T_OBJECT)         // 'unknown' value returned by SD::bkt
1900     return T_ILLEGAL;
1901   return type;
1902 }
1903 
1904 
1905 BasicType java_lang_boxing_object::get_value(oop box, jvalue* value) {
1906   BasicType type = SystemDictionary::box_klass_type(box->klass());
1907   switch (type) {
1908   case T_BOOLEAN:
1909     value->z = box->bool_field(value_offset);
1910     break;
1911   case T_CHAR:
1912     value->c = box->char_field(value_offset);
1913     break;
1914   case T_FLOAT:
1915     value->f = box->float_field(value_offset);
1916     break;
1917   case T_DOUBLE:
1918     value->d = box->double_field(long_value_offset);
1919     break;
1920   case T_BYTE:
1921     value->b = box->byte_field(value_offset);
1922     break;
1923   case T_SHORT:
1924     value->s = box->short_field(value_offset);
1925     break;
1926   case T_INT:
1927     value->i = box->int_field(value_offset);
1928     break;
1929   case T_LONG:
1930     value->j = box->long_field(long_value_offset);
1931     break;
1932   default:
1933     return T_ILLEGAL;
1934   } // end switch
1935   return type;
1936 }
1937 
1938 
1939 BasicType java_lang_boxing_object::set_value(oop box, jvalue* value) {
1940   BasicType type = SystemDictionary::box_klass_type(box->klass());
1941   switch (type) {
1942   case T_BOOLEAN:
1943     box->bool_field_put(value_offset, value->z);
1944     break;
1945   case T_CHAR:
1946     box->char_field_put(value_offset, value->c);
1947     break;
1948   case T_FLOAT:
1949     box->float_field_put(value_offset, value->f);
1950     break;
1951   case T_DOUBLE:
1952     box->double_field_put(long_value_offset, value->d);
1953     break;
1954   case T_BYTE:
1955     box->byte_field_put(value_offset, value->b);
1956     break;
1957   case T_SHORT:
1958     box->short_field_put(value_offset, value->s);
1959     break;
1960   case T_INT:
1961     box->int_field_put(value_offset, value->i);
1962     break;
1963   case T_LONG:
1964     box->long_field_put(long_value_offset, value->j);
1965     break;
1966   default:
1967     return T_ILLEGAL;
1968   } // end switch
1969   return type;
1970 }
1971 
1972 
1973 // Support for java_lang_ref_Reference
1974 oop java_lang_ref_Reference::pending_list_lock() {
1975   instanceKlass* ik = instanceKlass::cast(SystemDictionary::reference_klass());
1976   char *addr = (((char *)ik->start_of_static_fields()) + static_lock_offset);
1977   if (UseCompressedOops) {
1978     return oopDesc::load_decode_heap_oop((narrowOop *)addr);
1979   } else {
1980     return oopDesc::load_decode_heap_oop((oop*)addr);
1981   }
1982 }
1983 
1984 HeapWord *java_lang_ref_Reference::pending_list_addr() {
1985   instanceKlass* ik = instanceKlass::cast(SystemDictionary::reference_klass());
1986   char *addr = (((char *)ik->start_of_static_fields()) + static_pending_offset);
1987   // XXX This might not be HeapWord aligned, almost rather be char *.
1988   return (HeapWord*)addr;
1989 }
1990 
1991 oop java_lang_ref_Reference::pending_list() {
1992   char *addr = (char *)pending_list_addr();
1993   if (UseCompressedOops) {
1994     return oopDesc::load_decode_heap_oop((narrowOop *)addr);
1995   } else {
1996     return oopDesc::load_decode_heap_oop((oop*)addr);
1997   }
1998 }
1999 
2000 
2001 // Support for java_lang_ref_SoftReference
2002 
2003 jlong java_lang_ref_SoftReference::timestamp(oop ref) {
2004   return ref->long_field(timestamp_offset);
2005 }
2006 
2007 jlong java_lang_ref_SoftReference::clock() {
2008   instanceKlass* ik = instanceKlass::cast(SystemDictionary::soft_reference_klass());
2009   int offset = ik->offset_of_static_fields() + static_clock_offset;
2010 
2011   return SystemDictionary::soft_reference_klass()->long_field(offset);
2012 }
2013 
2014 void java_lang_ref_SoftReference::set_clock(jlong value) {
2015   instanceKlass* ik = instanceKlass::cast(SystemDictionary::soft_reference_klass());
2016   int offset = ik->offset_of_static_fields() + static_clock_offset;
2017 
2018   SystemDictionary::soft_reference_klass()->long_field_put(offset, value);
2019 }
2020 
2021 
2022 // Support for java_security_AccessControlContext
2023 
2024 int java_security_AccessControlContext::_context_offset = 0;
2025 int java_security_AccessControlContext::_privilegedContext_offset = 0;
2026 int java_security_AccessControlContext::_isPrivileged_offset = 0;
2027 
2028 
2029 void java_security_AccessControlContext::compute_offsets() {
2030   assert(_isPrivileged_offset == 0, "offsets should be initialized only once");
2031   fieldDescriptor fd;
2032   instanceKlass* ik = instanceKlass::cast(SystemDictionary::AccessControlContext_klass());
2033 
2034   if (!ik->find_local_field(vmSymbols::context_name(), vmSymbols::protectiondomain_signature(), &fd)) {
2035     fatal("Invalid layout of java.security.AccessControlContext");
2036   }
2037   _context_offset = fd.offset();
2038 
2039   if (!ik->find_local_field(vmSymbols::privilegedContext_name(), vmSymbols::accesscontrolcontext_signature(), &fd)) {
2040     fatal("Invalid layout of java.security.AccessControlContext");
2041   }
2042   _privilegedContext_offset = fd.offset();
2043 
2044   if (!ik->find_local_field(vmSymbols::isPrivileged_name(), vmSymbols::bool_signature(), &fd)) {
2045     fatal("Invalid layout of java.security.AccessControlContext");
2046   }
2047   _isPrivileged_offset = fd.offset();
2048 }
2049 
2050 
2051 oop java_security_AccessControlContext::create(objArrayHandle context, bool isPrivileged, Handle privileged_context, TRAPS) {
2052   assert(_isPrivileged_offset != 0, "offsets should have been initialized");
2053   // Ensure klass is initialized
2054   instanceKlass::cast(SystemDictionary::AccessControlContext_klass())->initialize(CHECK_0);
2055   // Allocate result
2056   oop result = instanceKlass::cast(SystemDictionary::AccessControlContext_klass())->allocate_instance(CHECK_0);
2057   // Fill in values
2058   result->obj_field_put(_context_offset, context());
2059   result->obj_field_put(_privilegedContext_offset, privileged_context());
2060   result->bool_field_put(_isPrivileged_offset, isPrivileged);
2061   return result;
2062 }
2063 
2064 
2065 // Support for java_lang_ClassLoader
2066 
2067 oop java_lang_ClassLoader::parent(oop loader) {
2068   assert(loader->is_oop(), "loader must be oop");
2069   return loader->obj_field(parent_offset);
2070 }
2071 
2072 
2073 bool java_lang_ClassLoader::is_trusted_loader(oop loader) {
2074   // Fix for 4474172; see evaluation for more details
2075   loader = non_reflection_class_loader(loader);
2076 
2077   oop cl = SystemDictionary::java_system_loader();
2078   while(cl != NULL) {
2079     if (cl == loader) return true;
2080     cl = parent(cl);
2081   }
2082   return false;
2083 }
2084 
2085 oop java_lang_ClassLoader::non_reflection_class_loader(oop loader) {
2086   if (loader != NULL) {
2087     // See whether this is one of the class loaders associated with
2088     // the generated bytecodes for reflection, and if so, "magically"
2089     // delegate to its parent to prevent class loading from occurring
2090     // in places where applications using reflection didn't expect it.
2091     klassOop delegating_cl_class = SystemDictionary::reflect_delegating_classloader_klass();
2092     // This might be null in non-1.4 JDKs
2093     if (delegating_cl_class != NULL && loader->is_a(delegating_cl_class)) {
2094       return parent(loader);
2095     }
2096   }
2097   return loader;
2098 }
2099 
2100 
2101 // Support for java_lang_System
2102 
2103 void java_lang_System::compute_offsets() {
2104   assert(offset_of_static_fields == 0, "offsets should be initialized only once");
2105 
2106   instanceKlass* ik = instanceKlass::cast(SystemDictionary::system_klass());
2107   offset_of_static_fields = ik->offset_of_static_fields();
2108 }
2109 
2110 int java_lang_System::in_offset_in_bytes() {
2111   return (offset_of_static_fields + static_in_offset);
2112 }
2113 
2114 
2115 int java_lang_System::out_offset_in_bytes() {
2116   return (offset_of_static_fields + static_out_offset);
2117 }
2118 
2119 
2120 int java_lang_System::err_offset_in_bytes() {
2121   return (offset_of_static_fields + static_err_offset);
2122 }
2123 
2124 
2125 
2126 int java_lang_String::value_offset;
2127 int java_lang_String::offset_offset;
2128 int java_lang_String::count_offset;
2129 int java_lang_String::hash_offset;
2130 int java_lang_Class::klass_offset;
2131 int java_lang_Class::array_klass_offset;
2132 int java_lang_Class::resolved_constructor_offset;
2133 int java_lang_Class::number_of_fake_oop_fields;
2134 int java_lang_Throwable::backtrace_offset;
2135 int java_lang_Throwable::detailMessage_offset;
2136 int java_lang_Throwable::cause_offset;
2137 int java_lang_Throwable::stackTrace_offset;
2138 int java_lang_reflect_AccessibleObject::override_offset;
2139 int java_lang_reflect_Method::clazz_offset;
2140 int java_lang_reflect_Method::name_offset;
2141 int java_lang_reflect_Method::returnType_offset;
2142 int java_lang_reflect_Method::parameterTypes_offset;
2143 int java_lang_reflect_Method::exceptionTypes_offset;
2144 int java_lang_reflect_Method::slot_offset;
2145 int java_lang_reflect_Method::modifiers_offset;
2146 int java_lang_reflect_Method::signature_offset;
2147 int java_lang_reflect_Method::annotations_offset;
2148 int java_lang_reflect_Method::parameter_annotations_offset;
2149 int java_lang_reflect_Method::annotation_default_offset;
2150 int java_lang_reflect_Constructor::clazz_offset;
2151 int java_lang_reflect_Constructor::parameterTypes_offset;
2152 int java_lang_reflect_Constructor::exceptionTypes_offset;
2153 int java_lang_reflect_Constructor::slot_offset;
2154 int java_lang_reflect_Constructor::modifiers_offset;
2155 int java_lang_reflect_Constructor::signature_offset;
2156 int java_lang_reflect_Constructor::annotations_offset;
2157 int java_lang_reflect_Constructor::parameter_annotations_offset;
2158 int java_lang_reflect_Field::clazz_offset;
2159 int java_lang_reflect_Field::name_offset;
2160 int java_lang_reflect_Field::type_offset;
2161 int java_lang_reflect_Field::slot_offset;
2162 int java_lang_reflect_Field::modifiers_offset;
2163 int java_lang_reflect_Field::signature_offset;
2164 int java_lang_reflect_Field::annotations_offset;
2165 int java_lang_boxing_object::value_offset;
2166 int java_lang_boxing_object::long_value_offset;
2167 int java_lang_ref_Reference::referent_offset;
2168 int java_lang_ref_Reference::queue_offset;
2169 int java_lang_ref_Reference::next_offset;
2170 int java_lang_ref_Reference::discovered_offset;
2171 int java_lang_ref_Reference::static_lock_offset;
2172 int java_lang_ref_Reference::static_pending_offset;
2173 int java_lang_ref_Reference::number_of_fake_oop_fields;
2174 int java_lang_ref_SoftReference::timestamp_offset;
2175 int java_lang_ref_SoftReference::static_clock_offset;
2176 int java_lang_ClassLoader::parent_offset;
2177 int java_lang_System::offset_of_static_fields;
2178 int java_lang_System::static_in_offset;
2179 int java_lang_System::static_out_offset;
2180 int java_lang_System::static_err_offset;
2181 int java_lang_StackTraceElement::declaringClass_offset;
2182 int java_lang_StackTraceElement::methodName_offset;
2183 int java_lang_StackTraceElement::fileName_offset;
2184 int java_lang_StackTraceElement::lineNumber_offset;
2185 int java_lang_AssertionStatusDirectives::classes_offset;
2186 int java_lang_AssertionStatusDirectives::classEnabled_offset;
2187 int java_lang_AssertionStatusDirectives::packages_offset;
2188 int java_lang_AssertionStatusDirectives::packageEnabled_offset;
2189 int java_lang_AssertionStatusDirectives::deflt_offset;
2190 int java_nio_Buffer::_limit_offset;
2191 int sun_misc_AtomicLongCSImpl::_value_offset;
2192 int java_util_concurrent_locks_AbstractOwnableSynchronizer::_owner_offset = 0;
2193 int sun_reflect_ConstantPool::_cp_oop_offset;
2194 int sun_reflect_UnsafeStaticFieldAccessorImpl::_base_offset;
2195 
2196 
2197 // Support for java_lang_StackTraceElement
2198 
2199 void java_lang_StackTraceElement::set_fileName(oop element, oop value) {
2200   element->obj_field_put(fileName_offset, value);
2201 }
2202 
2203 void java_lang_StackTraceElement::set_declaringClass(oop element, oop value) {
2204   element->obj_field_put(declaringClass_offset, value);
2205 }
2206 
2207 void java_lang_StackTraceElement::set_methodName(oop element, oop value) {
2208   element->obj_field_put(methodName_offset, value);
2209 }
2210 
2211 void java_lang_StackTraceElement::set_lineNumber(oop element, int value) {
2212   element->int_field_put(lineNumber_offset, value);
2213 }
2214 
2215 
2216 // Support for java Assertions - java_lang_AssertionStatusDirectives.
2217 
2218 void java_lang_AssertionStatusDirectives::set_classes(oop o, oop val) {
2219   o->obj_field_put(classes_offset, val);
2220 }
2221 
2222 void java_lang_AssertionStatusDirectives::set_classEnabled(oop o, oop val) {
2223   o->obj_field_put(classEnabled_offset, val);
2224 }
2225 
2226 void java_lang_AssertionStatusDirectives::set_packages(oop o, oop val) {
2227   o->obj_field_put(packages_offset, val);
2228 }
2229 
2230 void java_lang_AssertionStatusDirectives::set_packageEnabled(oop o, oop val) {
2231   o->obj_field_put(packageEnabled_offset, val);
2232 }
2233 
2234 void java_lang_AssertionStatusDirectives::set_deflt(oop o, bool val) {
2235   o->bool_field_put(deflt_offset, val);
2236 }
2237 
2238 
2239 // Support for intrinsification of java.nio.Buffer.checkIndex
2240 int java_nio_Buffer::limit_offset() {
2241   return _limit_offset;
2242 }
2243 
2244 
2245 void java_nio_Buffer::compute_offsets() {
2246   klassOop k = SystemDictionary::java_nio_Buffer_klass();
2247   assert(k != NULL, "must be loaded in 1.4+");
2248   compute_offset(_limit_offset, k, vmSymbols::limit_name(), vmSymbols::int_signature());
2249 }
2250 
2251 // Support for intrinsification of sun.misc.AtomicLongCSImpl.attemptUpdate
2252 int sun_misc_AtomicLongCSImpl::value_offset() {
2253   assert(SystemDictionary::sun_misc_AtomicLongCSImpl_klass() != NULL, "can't call this");
2254   return _value_offset;
2255 }
2256 
2257 
2258 void sun_misc_AtomicLongCSImpl::compute_offsets() {
2259   klassOop k = SystemDictionary::sun_misc_AtomicLongCSImpl_klass();
2260   // If this class is not present, its value field offset won't be referenced.
2261   if (k != NULL) {
2262     compute_offset(_value_offset, k, vmSymbols::value_name(), vmSymbols::long_signature());
2263   }
2264 }
2265 
2266 void java_util_concurrent_locks_AbstractOwnableSynchronizer::initialize(TRAPS) {
2267   if (_owner_offset != 0) return;
2268 
2269   assert(JDK_Version::is_gte_jdk16x_version(), "Must be JDK 1.6 or later");
2270   SystemDictionary::load_abstract_ownable_synchronizer_klass(CHECK);
2271   klassOop k = SystemDictionary::abstract_ownable_synchronizer_klass();
2272   compute_offset(_owner_offset, k,
2273                  vmSymbols::exclusive_owner_thread_name(), vmSymbols::thread_signature());
2274 }
2275 
2276 oop java_util_concurrent_locks_AbstractOwnableSynchronizer::get_owner_threadObj(oop obj) {
2277   assert(_owner_offset != 0, "Must be initialized");
2278   return obj->obj_field(_owner_offset);
2279 }
2280 
2281 // Compute hard-coded offsets
2282 // Invoked before SystemDictionary::initialize, so pre-loaded classes
2283 // are not available to determine the offset_of_static_fields.
2284 void JavaClasses::compute_hard_coded_offsets() {
2285   const int x = heapOopSize;
2286   const int header = instanceOopDesc::base_offset_in_bytes();
2287 
2288   // Do the String Class
2289   java_lang_String::value_offset  = java_lang_String::hc_value_offset  * x + header;
2290   java_lang_String::offset_offset = java_lang_String::hc_offset_offset * x + header;
2291   java_lang_String::count_offset  = java_lang_String::offset_offset + sizeof (jint);
2292   java_lang_String::hash_offset   = java_lang_String::count_offset + sizeof (jint);
2293 
2294   // Do the Class Class
2295   java_lang_Class::klass_offset = java_lang_Class::hc_klass_offset * x + header;
2296   java_lang_Class::array_klass_offset = java_lang_Class::hc_array_klass_offset * x + header;
2297   java_lang_Class::resolved_constructor_offset = java_lang_Class::hc_resolved_constructor_offset * x + header;
2298 
2299   // This is NOT an offset
2300   java_lang_Class::number_of_fake_oop_fields = java_lang_Class::hc_number_of_fake_oop_fields;
2301 
2302   // Throwable Class
2303   java_lang_Throwable::backtrace_offset  = java_lang_Throwable::hc_backtrace_offset  * x + header;
2304   java_lang_Throwable::detailMessage_offset = java_lang_Throwable::hc_detailMessage_offset * x + header;
2305   java_lang_Throwable::cause_offset      = java_lang_Throwable::hc_cause_offset      * x + header;
2306   java_lang_Throwable::stackTrace_offset = java_lang_Throwable::hc_stackTrace_offset * x + header;
2307 
2308   // java_lang_boxing_object
2309   java_lang_boxing_object::value_offset = java_lang_boxing_object::hc_value_offset + header;
2310   java_lang_boxing_object::long_value_offset = align_size_up((java_lang_boxing_object::hc_value_offset + header), BytesPerLong);
2311 
2312   // java_lang_ref_Reference:
2313   java_lang_ref_Reference::referent_offset = java_lang_ref_Reference::hc_referent_offset * x + header;
2314   java_lang_ref_Reference::queue_offset = java_lang_ref_Reference::hc_queue_offset * x + header;
2315   java_lang_ref_Reference::next_offset  = java_lang_ref_Reference::hc_next_offset * x + header;
2316   java_lang_ref_Reference::discovered_offset  = java_lang_ref_Reference::hc_discovered_offset * x + header;
2317   java_lang_ref_Reference::static_lock_offset = java_lang_ref_Reference::hc_static_lock_offset *  x;
2318   java_lang_ref_Reference::static_pending_offset = java_lang_ref_Reference::hc_static_pending_offset * x;
2319   // Artificial fields for java_lang_ref_Reference
2320   // The first field is for the discovered field added in 1.4
2321   java_lang_ref_Reference::number_of_fake_oop_fields = 1;
2322 
2323   // java_lang_ref_SoftReference Class
2324   java_lang_ref_SoftReference::timestamp_offset = align_size_up((java_lang_ref_SoftReference::hc_timestamp_offset * x + header), BytesPerLong);
2325   // Don't multiply static fields because they are always in wordSize units
2326   java_lang_ref_SoftReference::static_clock_offset = java_lang_ref_SoftReference::hc_static_clock_offset * x;
2327 
2328   // java_lang_ClassLoader
2329   java_lang_ClassLoader::parent_offset = java_lang_ClassLoader::hc_parent_offset * x + header;
2330 
2331   // java_lang_System
2332   java_lang_System::static_in_offset  = java_lang_System::hc_static_in_offset  * x;
2333   java_lang_System::static_out_offset = java_lang_System::hc_static_out_offset * x;
2334   java_lang_System::static_err_offset = java_lang_System::hc_static_err_offset * x;
2335 
2336   // java_lang_StackTraceElement
2337   java_lang_StackTraceElement::declaringClass_offset = java_lang_StackTraceElement::hc_declaringClass_offset  * x + header;
2338   java_lang_StackTraceElement::methodName_offset = java_lang_StackTraceElement::hc_methodName_offset * x + header;
2339   java_lang_StackTraceElement::fileName_offset   = java_lang_StackTraceElement::hc_fileName_offset   * x + header;
2340   java_lang_StackTraceElement::lineNumber_offset = java_lang_StackTraceElement::hc_lineNumber_offset * x + header;
2341   java_lang_AssertionStatusDirectives::classes_offset = java_lang_AssertionStatusDirectives::hc_classes_offset * x + header;
2342   java_lang_AssertionStatusDirectives::classEnabled_offset = java_lang_AssertionStatusDirectives::hc_classEnabled_offset * x + header;
2343   java_lang_AssertionStatusDirectives::packages_offset = java_lang_AssertionStatusDirectives::hc_packages_offset * x + header;
2344   java_lang_AssertionStatusDirectives::packageEnabled_offset = java_lang_AssertionStatusDirectives::hc_packageEnabled_offset * x + header;
2345   java_lang_AssertionStatusDirectives::deflt_offset = java_lang_AssertionStatusDirectives::hc_deflt_offset * x + header;
2346 
2347 }
2348 
2349 
2350 // Compute non-hard-coded field offsets of all the classes in this file
2351 void JavaClasses::compute_offsets() {
2352 
2353   java_lang_Class::compute_offsets();
2354   java_lang_System::compute_offsets();
2355   java_lang_Thread::compute_offsets();
2356   java_lang_ThreadGroup::compute_offsets();
2357   java_security_AccessControlContext::compute_offsets();
2358   // Initialize reflection classes. The layouts of these classes
2359   // changed with the new reflection implementation in JDK 1.4, and
2360   // since the Universe doesn't know what JDK version it is until this
2361   // point we defer computation of these offsets until now.
2362   java_lang_reflect_AccessibleObject::compute_offsets();
2363   java_lang_reflect_Method::compute_offsets();
2364   java_lang_reflect_Constructor::compute_offsets();
2365   java_lang_reflect_Field::compute_offsets();
2366   if (JDK_Version::is_gte_jdk14x_version()) {
2367     java_nio_Buffer::compute_offsets();
2368   }
2369   if (JDK_Version::is_gte_jdk15x_version()) {
2370     sun_reflect_ConstantPool::compute_offsets();
2371     sun_reflect_UnsafeStaticFieldAccessorImpl::compute_offsets();
2372   }
2373   sun_misc_AtomicLongCSImpl::compute_offsets();
2374 }
2375 
2376 #ifndef PRODUCT
2377 
2378 // These functions exist to assert the validity of hard-coded field offsets to guard
2379 // against changes in the class files
2380 
2381 bool JavaClasses::check_offset(const char *klass_name, int hardcoded_offset, const char *field_name, const char* field_sig) {
2382   EXCEPTION_MARK;
2383   fieldDescriptor fd;
2384   symbolHandle klass_sym = oopFactory::new_symbol_handle(klass_name, CATCH);
2385   klassOop k = SystemDictionary::resolve_or_fail(klass_sym, true, CATCH);
2386   instanceKlassHandle h_klass (THREAD, k);
2387   //instanceKlassHandle h_klass(klass);
2388   symbolHandle f_name = oopFactory::new_symbol_handle(field_name, CATCH);
2389   symbolHandle f_sig  = oopFactory::new_symbol_handle(field_sig, CATCH);
2390   if (!h_klass->find_local_field(f_name(), f_sig(), &fd)) {
2391     tty->print_cr("Nonstatic field %s.%s not found", klass_name, field_name);
2392     return false;
2393   }
2394   if (fd.is_static()) {
2395     tty->print_cr("Nonstatic field %s.%s appears to be static", klass_name, field_name);
2396     return false;
2397   }
2398   if (fd.offset() == hardcoded_offset ) {
2399     return true;
2400   } else {
2401     tty->print_cr("Offset of nonstatic field %s.%s is hardcoded as %d but should really be %d.",
2402                   klass_name, field_name, hardcoded_offset, fd.offset());
2403     return false;
2404   }
2405 }
2406 
2407 
2408 bool JavaClasses::check_static_offset(const char *klass_name, int hardcoded_offset, const char *field_name, const char* field_sig) {
2409   EXCEPTION_MARK;
2410   fieldDescriptor fd;
2411   symbolHandle klass_sym = oopFactory::new_symbol_handle(klass_name, CATCH);
2412   klassOop k = SystemDictionary::resolve_or_fail(klass_sym, true, CATCH);
2413   instanceKlassHandle h_klass (THREAD, k);
2414   symbolHandle f_name = oopFactory::new_symbol_handle(field_name, CATCH);
2415   symbolHandle f_sig  = oopFactory::new_symbol_handle(field_sig, CATCH);
2416   if (!h_klass->find_local_field(f_name(), f_sig(), &fd)) {
2417     tty->print_cr("Static field %s.%s not found", klass_name, field_name);
2418     return false;
2419   }
2420   if (!fd.is_static()) {
2421     tty->print_cr("Static field %s.%s appears to be nonstatic", klass_name, field_name);
2422     return false;
2423   }
2424   if (fd.offset() == hardcoded_offset + h_klass->offset_of_static_fields()) {
2425     return true;
2426   } else {
2427     tty->print_cr("Offset of static field %s.%s is hardcoded as %d but should really be %d.", klass_name, field_name, hardcoded_offset, fd.offset() - h_klass->offset_of_static_fields());
2428     return false;
2429   }
2430 }
2431 
2432 
2433 bool JavaClasses::check_constant(const char *klass_name, int hardcoded_constant, const char *field_name, const char* field_sig) {
2434   EXCEPTION_MARK;
2435   fieldDescriptor fd;
2436   symbolHandle klass_sym = oopFactory::new_symbol_handle(klass_name, CATCH);
2437   klassOop k = SystemDictionary::resolve_or_fail(klass_sym, true, CATCH);
2438   instanceKlassHandle h_klass (THREAD, k);
2439   symbolHandle f_name = oopFactory::new_symbol_handle(field_name, CATCH);
2440   symbolHandle f_sig  = oopFactory::new_symbol_handle(field_sig, CATCH);
2441   if (!h_klass->find_local_field(f_name(), f_sig(), &fd)) {
2442     tty->print_cr("Static field %s.%s not found", klass_name, field_name);
2443     return false;
2444   }
2445   if (!fd.is_static() || !fd.has_initial_value()) {
2446     tty->print_cr("Static field %s.%s appears to be non-constant", klass_name, field_name);
2447     return false;
2448   }
2449   if (!fd.initial_value_tag().is_int()) {
2450     tty->print_cr("Static field %s.%s is not an int", klass_name, field_name);
2451     return false;
2452   }
2453   jint field_value = fd.int_initial_value();
2454   if (field_value == hardcoded_constant) {
2455     return true;
2456   } else {
2457     tty->print_cr("Constant value of static field %s.%s is hardcoded as %d but should really be %d.", klass_name, field_name, hardcoded_constant, field_value);
2458     return false;
2459   }
2460 }
2461 
2462 
2463 // Check the hard-coded field offsets of all the classes in this file
2464 
2465 void JavaClasses::check_offsets() {
2466   bool valid = true;
2467 
2468 #define CHECK_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
2469   valid &= check_offset(klass_name, cpp_klass_name :: field_name ## _offset, #field_name, field_sig)
2470 
2471 #define CHECK_LONG_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
2472   valid &= check_offset(klass_name, cpp_klass_name :: long_ ## field_name ## _offset, #field_name, field_sig)
2473 
2474 #define CHECK_STATIC_OFFSET(klass_name, cpp_klass_name, field_name, field_sig) \
2475   valid &= check_static_offset(klass_name, cpp_klass_name :: static_ ## field_name ## _offset, #field_name, field_sig)
2476 
2477 #define CHECK_CONSTANT(klass_name, cpp_klass_name, field_name, field_sig) \
2478   valid &= check_constant(klass_name, cpp_klass_name :: field_name, #field_name, field_sig)
2479 
2480   // java.lang.String
2481 
2482   CHECK_OFFSET("java/lang/String", java_lang_String, value, "[C");
2483   CHECK_OFFSET("java/lang/String", java_lang_String, offset, "I");
2484   CHECK_OFFSET("java/lang/String", java_lang_String, count, "I");
2485   CHECK_OFFSET("java/lang/String", java_lang_String, hash, "I");
2486 
2487   // java.lang.Class
2488 
2489   // Fake fields
2490   // CHECK_OFFSET("java/lang/Class", java_lang_Class, klass); // %%% this needs to be checked
2491   // CHECK_OFFSET("java/lang/Class", java_lang_Class, array_klass); // %%% this needs to be checked
2492   // CHECK_OFFSET("java/lang/Class", java_lang_Class, resolved_constructor); // %%% this needs to be checked
2493 
2494   // java.lang.Throwable
2495 
2496   CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, backtrace, "Ljava/lang/Object;");
2497   CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, detailMessage, "Ljava/lang/String;");
2498   CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, cause, "Ljava/lang/Throwable;");
2499   CHECK_OFFSET("java/lang/Throwable", java_lang_Throwable, stackTrace, "[Ljava/lang/StackTraceElement;");
2500 
2501   // Boxed primitive objects (java_lang_boxing_object)
2502 
2503   CHECK_OFFSET("java/lang/Boolean",   java_lang_boxing_object, value, "Z");
2504   CHECK_OFFSET("java/lang/Character", java_lang_boxing_object, value, "C");
2505   CHECK_OFFSET("java/lang/Float",     java_lang_boxing_object, value, "F");
2506   CHECK_LONG_OFFSET("java/lang/Double", java_lang_boxing_object, value, "D");
2507   CHECK_OFFSET("java/lang/Byte",      java_lang_boxing_object, value, "B");
2508   CHECK_OFFSET("java/lang/Short",     java_lang_boxing_object, value, "S");
2509   CHECK_OFFSET("java/lang/Integer",   java_lang_boxing_object, value, "I");
2510   CHECK_LONG_OFFSET("java/lang/Long", java_lang_boxing_object, value, "J");
2511 
2512   // java.lang.ClassLoader
2513 
2514   CHECK_OFFSET("java/lang/ClassLoader", java_lang_ClassLoader, parent,      "Ljava/lang/ClassLoader;");
2515 
2516   // java.lang.System
2517 
2518   CHECK_STATIC_OFFSET("java/lang/System", java_lang_System,  in, "Ljava/io/InputStream;");
2519   CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, out, "Ljava/io/PrintStream;");
2520   CHECK_STATIC_OFFSET("java/lang/System", java_lang_System, err, "Ljava/io/PrintStream;");
2521 
2522   // java.lang.StackTraceElement
2523 
2524   CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, declaringClass, "Ljava/lang/String;");
2525   CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, methodName, "Ljava/lang/String;");
2526   CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement,   fileName, "Ljava/lang/String;");
2527   CHECK_OFFSET("java/lang/StackTraceElement", java_lang_StackTraceElement, lineNumber, "I");
2528 
2529   // java.lang.ref.Reference
2530 
2531   CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, referent, "Ljava/lang/Object;");
2532   CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, queue, "Ljava/lang/ref/ReferenceQueue;");
2533   CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, next, "Ljava/lang/ref/Reference;");
2534   // Fake field
2535   //CHECK_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, discovered, "Ljava/lang/ref/Reference;");
2536   CHECK_STATIC_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, lock, "Ljava/lang/ref/Reference$Lock;");
2537   CHECK_STATIC_OFFSET("java/lang/ref/Reference", java_lang_ref_Reference, pending, "Ljava/lang/ref/Reference;");
2538 
2539   // java.lang.ref.SoftReference
2540 
2541   CHECK_OFFSET("java/lang/ref/SoftReference", java_lang_ref_SoftReference, timestamp, "J");
2542   CHECK_STATIC_OFFSET("java/lang/ref/SoftReference", java_lang_ref_SoftReference, clock, "J");
2543 
2544   // java.lang.AssertionStatusDirectives
2545   //
2546   // The CheckAssertionStatusDirectives boolean can be removed from here and
2547   // globals.hpp after the AssertionStatusDirectives class has been integrated
2548   // into merlin "for some time."  Without it, the vm will fail with early
2549   // merlin builds.
2550 
2551   if (CheckAssertionStatusDirectives && JDK_Version::is_gte_jdk14x_version()) {
2552     const char* nm = "java/lang/AssertionStatusDirectives";
2553     const char* sig = "[Ljava/lang/String;";
2554     CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, classes, sig);
2555     CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, classEnabled, "[Z");
2556     CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, packages, sig);
2557     CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, packageEnabled, "[Z");
2558     CHECK_OFFSET(nm, java_lang_AssertionStatusDirectives, deflt, "Z");
2559   }
2560 
2561   if (!valid) vm_exit_during_initialization("Hard-coded field offset verification failed");
2562 }
2563 
2564 #endif // PRODUCT
2565 
2566 void javaClasses_init() {
2567   JavaClasses::compute_offsets();
2568   JavaClasses::check_offsets();
2569   FilteredFieldsMap::initialize();  // must be done after computing offsets.
2570 }