< prev index next >

src/hotspot/share/oops/instanceKlass.cpp

Print this page




  47 #include "logging/logStream.hpp"
  48 #include "memory/allocation.inline.hpp"
  49 #include "memory/heapInspection.hpp"
  50 #include "memory/iterator.inline.hpp"
  51 #include "memory/metadataFactory.hpp"
  52 #include "memory/metaspaceClosure.hpp"
  53 #include "memory/metaspaceShared.hpp"
  54 #include "memory/oopFactory.hpp"
  55 #include "memory/resourceArea.hpp"
  56 #include "memory/universe.hpp"
  57 #include "oops/fieldStreams.hpp"
  58 #include "oops/constantPool.hpp"
  59 #include "oops/instanceClassLoaderKlass.hpp"
  60 #include "oops/instanceKlass.inline.hpp"
  61 #include "oops/instanceMirrorKlass.hpp"
  62 #include "oops/instanceOop.hpp"
  63 #include "oops/klass.inline.hpp"
  64 #include "oops/method.hpp"
  65 #include "oops/oop.inline.hpp"
  66 #include "oops/symbol.hpp"

  67 #include "prims/jvmtiExport.hpp"
  68 #include "prims/jvmtiRedefineClasses.hpp"
  69 #include "prims/jvmtiThreadState.hpp"
  70 #include "prims/methodComparator.hpp"
  71 #include "runtime/atomic.hpp"
  72 #include "runtime/fieldDescriptor.inline.hpp"
  73 #include "runtime/handles.inline.hpp"
  74 #include "runtime/javaCalls.hpp"
  75 #include "runtime/mutexLocker.hpp"
  76 #include "runtime/orderAccess.hpp"
  77 #include "runtime/thread.inline.hpp"
  78 #include "services/classLoadingService.hpp"
  79 #include "services/threadService.hpp"
  80 #include "utilities/dtrace.hpp"
  81 #include "utilities/events.hpp"
  82 #include "utilities/macros.hpp"
  83 #include "utilities/stringUtils.hpp"
  84 #ifdef COMPILER1
  85 #include "c1/c1_Compiler.hpp"
  86 #endif


 355 
 356   bool access = (cur_host == k_nest_host);
 357 
 358   if (log_is_enabled(Trace, class, nestmates)) {
 359     ResourceMark rm(THREAD);
 360     log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
 361                                 this->external_name(),
 362                                 access ? "" : "NOT ",
 363                                 k->external_name());
 364   }
 365 
 366   return access;
 367 }
 368 
 369 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
 370   const int size = InstanceKlass::size(parser.vtable_size(),
 371                                        parser.itable_size(),
 372                                        nonstatic_oop_map_size(parser.total_oop_map_count()),
 373                                        parser.is_interface(),
 374                                        parser.is_unsafe_anonymous(),
 375                                        should_store_fingerprint(parser.is_unsafe_anonymous()));


 376 
 377   const Symbol* const class_name = parser.class_name();
 378   assert(class_name != NULL, "invariant");
 379   ClassLoaderData* loader_data = parser.loader_data();
 380   assert(loader_data != NULL, "invariant");
 381 
 382   InstanceKlass* ik;
 383 
 384   // Allocation
 385   if (REF_NONE == parser.reference_type()) {
 386     if (class_name == vmSymbols::java_lang_Class()) {
 387       // mirror
 388       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
 389     }
 390     else if (is_class_loader(class_name, parser)) {
 391       // class loader
 392       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);



 393     } else {
 394       // normal
 395       ik = new (loader_data, size, THREAD) InstanceKlass(parser, InstanceKlass::_misc_kind_other);
 396     }
 397   } else {
 398     // reference
 399     ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
 400   }
 401 
 402   // Check for pending exception before adding to the loader data and incrementing
 403   // class count.  Can get OOM here.
 404   if (HAS_PENDING_EXCEPTION) {
 405     return NULL;
 406   }
 407 







 408   return ik;
 409 }
 410 























 411 
 412 // copy method ordering from resource area to Metaspace
 413 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
 414   if (m != NULL) {
 415     // allocate a new array and copy contents (memcpy?)
 416     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 417     for (int i = 0; i < m->length(); i++) {
 418       _method_ordering->at_put(i, m->at(i));
 419     }
 420   } else {
 421     _method_ordering = Universe::the_empty_int_array();
 422   }
 423 }
 424 
 425 // create a new array of vtable_indices for default methods
 426 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 427   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 428   assert(default_vtable_indices() == NULL, "only create once");
 429   set_default_vtable_indices(vtable_indices);
 430   return vtable_indices;
 431 }
 432 
 433 InstanceKlass::InstanceKlass(const ClassFileParser& parser, unsigned kind, KlassID id) :
 434   Klass(id),
 435   _nest_members(NULL),
 436   _nest_host_index(0),
 437   _nest_host(NULL),
 438   _static_field_size(parser.static_field_size()),
 439   _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
 440   _itable_len(parser.itable_size()),

 441   _init_thread(NULL),
 442   _init_state(allocated),
 443   _reference_type(parser.reference_type())

 444 {
 445   set_vtable_length(parser.vtable_size());
 446   set_kind(kind);
 447   set_access_flags(parser.access_flags());
 448   set_is_unsafe_anonymous(parser.is_unsafe_anonymous());
 449   set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
 450                                                     false));




 451 
 452   assert(NULL == _methods, "underlying memory not zeroed?");
 453   assert(is_instance_klass(), "is layout incorrect?");
 454   assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
 455 
 456   if (DumpSharedSpaces || DynamicDumpSharedSpaces) {
 457     SystemDictionaryShared::init_dumptime_info(this);
 458   }
 459 }
 460 
 461 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 462                                        Array<Method*>* methods) {
 463   if (methods != NULL && methods != Universe::the_empty_method_array() &&
 464       !methods->is_shared()) {
 465     for (int i = 0; i < methods->length(); i++) {
 466       Method* method = methods->at(i);
 467       if (method == NULL) continue;  // maybe null if error processing
 468       // Only want to delete methods that are not executing for RedefineClasses.
 469       // The previous version will point to them so they're not totally dangling
 470       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 471       MetadataFactory::free_metadata(loader_data, method);
 472     }
 473     MetadataFactory::free_array<Method*>(loader_data, methods);
 474   }
 475 }
 476 
 477 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 478                                           const Klass* super_klass,


 776         vmSymbols::java_lang_IncompatibleClassChangeError(),
 777         "class %s has interface %s as super class",
 778         external_name(),
 779         super_klass->external_name()
 780       );
 781       return false;
 782     }
 783 
 784     InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
 785     ik_super->link_class_impl(CHECK_false);
 786   }
 787 
 788   // link all interfaces implemented by this class before linking this class
 789   Array<InstanceKlass*>* interfaces = local_interfaces();
 790   int num_interfaces = interfaces->length();
 791   for (int index = 0; index < num_interfaces; index++) {
 792     InstanceKlass* interk = interfaces->at(index);
 793     interk->link_class_impl(CHECK_false);
 794   }
 795 





























































 796   // in case the class is linked in the process of linking its superclasses
 797   if (is_linked()) {
 798     return true;
 799   }
 800 
 801   // trace only the link time for this klass that includes
 802   // the verification time
 803   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 804                              ClassLoader::perf_class_link_selftime(),
 805                              ClassLoader::perf_classes_linked(),
 806                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 807                              jt->get_thread_stat()->perf_timers_addr(),
 808                              PerfClassTraceTime::CLASS_LINK);
 809 
 810   // verification & rewriting
 811   {
 812     HandleMark hm(THREAD);
 813     Handle h_init_lock(THREAD, init_lock());
 814     ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
 815     // rewritten will have been set if loader constraint error found


 845       // Initialize the vtable and interface table after
 846       // methods have been rewritten since rewrite may
 847       // fabricate new Method*s.
 848       // also does loader constraint checking
 849       //
 850       // initialize_vtable and initialize_itable need to be rerun for
 851       // a shared class if the class is not loaded by the NULL classloader.
 852       ClassLoaderData * loader_data = class_loader_data();
 853       if (!(is_shared() &&
 854             loader_data->is_the_null_class_loader_data())) {
 855         vtable().initialize_vtable(true, CHECK_false);
 856         itable().initialize_itable(true, CHECK_false);
 857       }
 858 #ifdef ASSERT
 859       else {
 860         vtable().verify(tty, true);
 861         // In case itable verification is ever added.
 862         // itable().verify(tty, true);
 863       }
 864 #endif

 865       set_init_state(linked);
 866       if (JvmtiExport::should_post_class_prepare()) {
 867         Thread *thread = THREAD;
 868         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 869         JvmtiExport::post_class_prepare((JavaThread *) thread, this);
 870       }
 871     }
 872   }
 873   return true;
 874 }
 875 
 876 // Rewrite the byte codes of all of the methods of a class.
 877 // The rewriter must be called exactly once. Rewriting must happen after
 878 // verification but before the first method of the class is executed.
 879 void InstanceKlass::rewrite_class(TRAPS) {
 880   assert(is_loaded(), "must be loaded");
 881   if (is_rewritten()) {
 882     assert(is_shared(), "rewriting an unshared class?");
 883     return;
 884   }


 998     // having a superinterface that declares, non-static, concrete methods
 999     if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1000       initialize_super_interfaces(THREAD);
1001     }
1002 
1003     // If any exceptions, complete abruptly, throwing the same exception as above.
1004     if (HAS_PENDING_EXCEPTION) {
1005       Handle e(THREAD, PENDING_EXCEPTION);
1006       CLEAR_PENDING_EXCEPTION;
1007       {
1008         EXCEPTION_MARK;
1009         // Locks object, set state, and notify all waiting threads
1010         set_initialization_state_and_notify(initialization_error, THREAD);
1011         CLEAR_PENDING_EXCEPTION;
1012       }
1013       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1014       THROW_OOP(e());
1015     }
1016   }
1017 





























1018 
1019   // Look for aot compiled methods for this klass, including class initializer.
1020   AOTLoader::load_for_klass(this, THREAD);
1021 
1022   // Step 8
1023   {
1024     DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1025     // Timer includes any side effects of class initialization (resolution,
1026     // etc), but not recursive entry into call_class_initializer().
1027     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1028                              ClassLoader::perf_class_init_selftime(),
1029                              ClassLoader::perf_classes_inited(),
1030                              jt->get_thread_stat()->perf_recursion_counts_addr(),
1031                              jt->get_thread_stat()->perf_timers_addr(),
1032                              PerfClassTraceTime::CLASS_CLINIT);
1033     call_class_initializer(THREAD);
1034   }
1035 
1036   // Step 9
1037   if (!HAS_PENDING_EXCEPTION) {
1038     set_initialization_state_and_notify(fully_initialized, CHECK);
1039     {
1040       debug_only(vtable().verify(tty, true);)
1041     }
1042   }
1043   else {
1044     // Step 10 and 11
1045     Handle e(THREAD, PENDING_EXCEPTION);
1046     CLEAR_PENDING_EXCEPTION;
1047     // JVMTI has already reported the pending exception
1048     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1049     JvmtiExport::clear_detected_exception(jt);
1050     {
1051       EXCEPTION_MARK;
1052       set_initialization_state_and_notify(initialization_error, THREAD);
1053       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1054       // JVMTI has already reported the pending exception
1055       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1056       JvmtiExport::clear_detected_exception(jt);
1057     }
1058     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1059     if (e->is_a(SystemDictionary::Error_klass())) {
1060       THROW_OOP(e());
1061     } else {
1062       JavaCallArguments args(e);
1063       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1064                 vmSymbols::throwable_void_signature(),


1274   return i;
1275 }
1276 
1277 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1278   return instanceHandle(THREAD, allocate_instance(THREAD));
1279 }
1280 
1281 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1282   if (is_interface() || is_abstract()) {
1283     ResourceMark rm(THREAD);
1284     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1285               : vmSymbols::java_lang_InstantiationException(), external_name());
1286   }
1287   if (this == SystemDictionary::Class_klass()) {
1288     ResourceMark rm(THREAD);
1289     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1290               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1291   }
1292 }
1293 
1294 Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {

1295   // Need load-acquire for lock-free read
1296   if (array_klasses_acquire() == NULL) {
1297     if (or_null) return NULL;
1298 
1299     ResourceMark rm;
1300     JavaThread *jt = (JavaThread *)THREAD;
1301     {
1302       // Atomic creation of array_klasses
1303       MutexLocker ma(MultiArray_lock, THREAD);
1304 
1305       // Check if update has already taken place
1306       if (array_klasses() == NULL) {
1307         Klass*    k = ObjArrayKlass::allocate_objArray_klass(class_loader_data(), 1, this, CHECK_NULL);
1308         // use 'release' to pair with lock-free load
1309         release_set_array_klasses(k);
1310       }
1311     }
1312   }
1313   // _this will always be set at this point
1314   ObjArrayKlass* oak = (ObjArrayKlass*)array_klasses();
1315   if (or_null) {
1316     return oak->array_klass_or_null(n);
1317   }
1318   return oak->array_klass(n, THREAD);
1319 }
1320 
1321 Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
1322   return array_klass_impl(or_null, 1, THREAD);
1323 }
1324 
1325 static int call_class_initializer_counter = 0;   // for debugging
1326 
1327 Method* InstanceKlass::class_initializer() const {
1328   Method* clinit = find_method(
1329       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1330   if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1331     return clinit;
1332   }
1333   return NULL;
1334 }
1335 
1336 void InstanceKlass::call_class_initializer(TRAPS) {
1337   if (ReplayCompiles &&
1338       (ReplaySuppressInitializers == 1 ||
1339        (ReplaySuppressInitializers >= 2 && class_loader() != NULL))) {
1340     // Hide the existence of the initializer for the purpose of replaying the compile
1341     return;
1342   }
1343 
1344   methodHandle h_method(THREAD, class_initializer());
1345   assert(!is_initialized(), "we cannot initialize twice");
1346   LogTarget(Info, class, init) lt;
1347   if (lt.is_enabled()) {
1348     ResourceMark rm;
1349     LogStream ls(lt);
1350     ls.print("%d Initializing ", call_class_initializer_counter++);
1351     name()->print_value_on(&ls);
1352     ls.print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this));
1353   }
1354   if (h_method() != NULL) {
1355     JavaCallArguments args; // No arguments
1356     JavaValue result(T_VOID);
1357     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1358   }
1359 }
1360 
1361 
1362 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1363   InterpreterOopMap* entry_for) {
1364   // Lazily create the _oop_map_cache at first request
1365   // Lock-free access requires load_acquire.
1366   OopMapCache* oop_map_cache = OrderAccess::load_acquire(&_oop_map_cache);
1367   if (oop_map_cache == NULL) {
1368     MutexLocker x(OopMapCacheAlloc_lock);
1369     // Check if _oop_map_cache was allocated while we were waiting for this lock
1370     if ((oop_map_cache = _oop_map_cache) == NULL) {
1371       oop_map_cache = new OopMapCache();
1372       // Ensure _oop_map_cache is stable, since it is examined without a lock
1373       OrderAccess::release_store(&_oop_map_cache, oop_map_cache);
1374     }
1375   }
1376   // _oop_map_cache is constant after init; lookup below does its own locking.
1377   oop_map_cache->lookup(method, bci, entry_for);
1378 }
1379 
1380 
1381 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1382   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1383     Symbol* f_name = fs.name();
1384     Symbol* f_sig  = fs.signature();
1385     if (f_name == name && f_sig == sig) {
1386       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1387       return true;
1388     }


1527     if (!fd.is_static()) {
1528       fields_sorted[j + 0] = fd.offset();
1529       fields_sorted[j + 1] = i;
1530       j += 2;
1531     }
1532   }
1533   if (j > 0) {
1534     length = j;
1535     // _sort_Fn is defined in growableArray.hpp.
1536     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1537     for (int i = 0; i < length; i += 2) {
1538       fd.reinitialize(this, fields_sorted[i + 1]);
1539       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1540       cl->do_field(&fd);
1541     }
1542   }
1543   FREE_C_HEAP_ARRAY(int, fields_sorted);
1544 }
1545 
1546 
1547 void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
1548   if (array_klasses() != NULL)
1549     ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
1550 }
1551 
1552 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1553   if (array_klasses() != NULL)
1554     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1555 }
1556 
1557 #ifdef ASSERT
1558 static int linear_search(const Array<Method*>* methods,
1559                          const Symbol* name,
1560                          const Symbol* signature) {
1561   const int len = methods->length();
1562   for (int index = 0; index < len; index++) {
1563     const Method* const m = methods->at(index);
1564     assert(m->is_method(), "must be method");
1565     if (m->signature() == signature && m->name() == name) {
1566        return index;
1567     }
1568   }
1569   return -1;
1570 }
1571 #endif


1789 }
1790 
1791 // uncached_lookup_method searches both the local class methods array and all
1792 // superclasses methods arrays, skipping any overpass methods in superclasses,
1793 // and possibly skipping private methods.
1794 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
1795                                               const Symbol* signature,
1796                                               OverpassLookupMode overpass_mode,
1797                                               PrivateLookupMode private_mode) const {
1798   OverpassLookupMode overpass_local_mode = overpass_mode;
1799   const Klass* klass = this;
1800   while (klass != NULL) {
1801     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
1802                                                                         signature,
1803                                                                         overpass_local_mode,
1804                                                                         find_static,
1805                                                                         private_mode);
1806     if (method != NULL) {
1807       return method;
1808     }



1809     klass = klass->super();
1810     overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1811   }
1812   return NULL;
1813 }
1814 
1815 #ifdef ASSERT
1816 // search through class hierarchy and return true if this class or
1817 // one of the superclasses was redefined
1818 bool InstanceKlass::has_redefined_this_or_super() const {
1819   const Klass* klass = this;
1820   while (klass != NULL) {
1821     if (InstanceKlass::cast(klass)->has_been_redefined()) {
1822       return true;
1823     }
1824     klass = klass->super();
1825   }
1826   return false;
1827 }
1828 #endif


2529 
2530 #if INCLUDE_JVMTI
2531   // Deallocate breakpoint records
2532   if (breakpoints() != 0x0) {
2533     methods_do(clear_all_breakpoints);
2534     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2535   }
2536 
2537   // deallocate the cached class file
2538   if (_cached_class_file != NULL) {
2539     os::free(_cached_class_file);
2540     _cached_class_file = NULL;
2541   }
2542 #endif
2543 
2544   // Decrement symbol reference counts associated with the unloaded class.
2545   if (_name != NULL) _name->decrement_refcount();
2546   // unreference array name derived from this class name (arrays of an unloaded
2547   // class can't be referenced anymore).
2548   if (_array_name != NULL)  _array_name->decrement_refcount();








2549   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension);
2550 }
2551 
2552 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
2553   if (array == NULL) {
2554     _source_debug_extension = NULL;
2555   } else {
2556     // Adding one to the attribute length in order to store a null terminator
2557     // character could cause an overflow because the attribute length is
2558     // already coded with an u4 in the classfile, but in practice, it's
2559     // unlikely to happen.
2560     assert((length+1) > length, "Overflow checking");
2561     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2562     for (int i = 0; i < length; i++) {
2563       sde[i] = array[i];
2564     }
2565     sde[length] = '\0';
2566     _source_debug_extension = sde;
2567   }
2568 }
2569 
2570 const char* InstanceKlass::signature_name() const {




2571   int hash_len = 0;
2572   char hash_buf[40];
2573 
2574   // If this is an unsafe anonymous class, append a hash to make the name unique
2575   if (is_unsafe_anonymous()) {
2576     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2577     jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash);
2578     hash_len = (int)strlen(hash_buf);
2579   }
2580 
2581   // Get the internal name as a c string
2582   const char* src = (const char*) (name()->as_C_string());
2583   const int src_length = (int)strlen(src);
2584 
2585   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2586 
2587   // Add L as type indicator
2588   int dest_index = 0;
2589   dest[dest_index++] = 'L';
2590 
2591   // Add the actual class name
2592   for (int src_index = 0; src_index < src_length; ) {
2593     dest[dest_index++] = src[src_index++];
2594   }
2595 
2596   // If we have a hash, append it
2597   for (int hash_index = 0; hash_index < hash_len; ) {
2598     dest[dest_index++] = hash_buf[hash_index++];
2599   }
2600 
2601   // Add the semicolon and the NULL
2602   dest[dest_index++] = ';';
2603   dest[dest_index] = '\0';
2604   return dest;
2605 }
2606 
2607 // Used to obtain the package name from a fully qualified class name.
2608 Symbol* InstanceKlass::package_from_name(const Symbol* name, TRAPS) {
2609   if (name == NULL) {


3100   }
3101 
3102   assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");
3103   if (best != NULL && best->comp_level() >= comp_level) {
3104     return best;
3105   }
3106   return NULL;
3107 }
3108 
3109 // -----------------------------------------------------------------------------------------------------
3110 // Printing
3111 
3112 #ifndef PRODUCT
3113 
3114 #define BULLET  " - "
3115 
3116 static const char* state_names[] = {
3117   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3118 };
3119 
3120 static void print_vtable(intptr_t* start, int len, outputStream* st) {



3121   for (int i = 0; i < len; i++) {
3122     intptr_t e = start[i];
3123     st->print("%d : " INTPTR_FORMAT, i, e);





3124     if (MetaspaceObj::is_valid((Metadata*)e)) {
3125       st->print(" ");
3126       ((Metadata*)e)->print_value_on(st);






3127     }
3128     st->cr();
3129   }
3130 }
3131 
3132 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3133   return print_vtable(reinterpret_cast<intptr_t*>(start), len, st);





















3134 }
3135 
3136 void InstanceKlass::print_on(outputStream* st) const {
3137   assert(is_klass(), "must be klass");
3138   Klass::print_on(st);
3139 
3140   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3141   st->print(BULLET"klass size:        %d", size());                               st->cr();
3142   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();

3143   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3144   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3145   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3146   st->print(BULLET"sub:               ");
3147   Klass* sub = subklass();
3148   int n;
3149   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3150     if (n < MaxSubklassPrintSize) {
3151       sub->print_value_on(st);
3152       st->print("   ");
3153     }
3154   }
3155   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3156   st->cr();
3157 
3158   if (is_interface()) {
3159     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3160     if (nof_implementors() == 1) {
3161       st->print_cr(BULLET"implementor:    ");
3162       st->print("   ");
3163       implementor()->print_value_on(st);
3164       st->cr();
3165     }
3166   }
3167 
3168   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3169   st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
3170   if (Verbose || WizardMode) {
3171     Array<Method*>* method_array = methods();
3172     for (int i = 0; i < method_array->length(); i++) {
3173       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3174     }
3175   }
3176   st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
3177   st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
3178   if (Verbose && default_methods() != NULL) {
3179     Array<Method*>* method_array = default_methods();
3180     for (int i = 0; i < method_array->length(); i++) {
3181       st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
3182     }
3183   }
3184   if (default_vtable_indices() != NULL) {
3185     st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
3186   }
3187   st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
3188   st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
3189   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3190   if (class_loader_data() != NULL) {
3191     st->print(BULLET"class loader data:  ");
3192     class_loader_data()->print_value_on(st);
3193     st->cr();
3194   }
3195   st->print(BULLET"unsafe anonymous host class:        "); Metadata::print_value_on_maybe_null(st, unsafe_anonymous_host()); st->cr();
3196   if (source_file_name() != NULL) {
3197     st->print(BULLET"source file:       ");
3198     source_file_name()->print_value_on(st);
3199     st->cr();
3200   }
3201   if (source_debug_extension() != NULL) {
3202     st->print(BULLET"source debug extension:       ");
3203     st->print("%s", source_debug_extension());
3204     st->cr();
3205   }
3206   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3207   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3208   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();


3221     if (have_pv) st->cr();
3222   }
3223 
3224   if (generic_signature() != NULL) {
3225     st->print(BULLET"generic signature: ");
3226     generic_signature()->print_value_on(st);
3227     st->cr();
3228   }
3229   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3230   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3231   if (java_mirror() != NULL) {
3232     st->print(BULLET"java mirror:       ");
3233     java_mirror()->print_value_on(st);
3234     st->cr();
3235   } else {
3236     st->print_cr(BULLET"java mirror:       NULL");
3237   }
3238   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3239   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3240   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3241   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
3242   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3243   FieldPrinter print_static_field(st);
3244   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3245   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3246   FieldPrinter print_nonstatic_field(st);
3247   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3248   ik->do_nonstatic_fields(&print_nonstatic_field);
3249 
3250   st->print(BULLET"non-static oop maps: ");
3251   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3252   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3253   while (map < end_map) {
3254     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3255     map++;
3256   }
3257   st->cr();
3258 }
3259 
3260 #endif //PRODUCT
3261 


4003   if (holder == NULL) {
4004     return NULL; // The version of klass is gone, no method is found
4005   }
4006   Method* method = holder->method_with_orig_idnum(idnum);
4007   return method;
4008 }
4009 
4010 #if INCLUDE_JVMTI
4011 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4012   return _cached_class_file;
4013 }
4014 
4015 jint InstanceKlass::get_cached_class_file_len() {
4016   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4017 }
4018 
4019 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4020   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4021 }
4022 #endif







  47 #include "logging/logStream.hpp"
  48 #include "memory/allocation.inline.hpp"
  49 #include "memory/heapInspection.hpp"
  50 #include "memory/iterator.inline.hpp"
  51 #include "memory/metadataFactory.hpp"
  52 #include "memory/metaspaceClosure.hpp"
  53 #include "memory/metaspaceShared.hpp"
  54 #include "memory/oopFactory.hpp"
  55 #include "memory/resourceArea.hpp"
  56 #include "memory/universe.hpp"
  57 #include "oops/fieldStreams.hpp"
  58 #include "oops/constantPool.hpp"
  59 #include "oops/instanceClassLoaderKlass.hpp"
  60 #include "oops/instanceKlass.inline.hpp"
  61 #include "oops/instanceMirrorKlass.hpp"
  62 #include "oops/instanceOop.hpp"
  63 #include "oops/klass.inline.hpp"
  64 #include "oops/method.hpp"
  65 #include "oops/oop.inline.hpp"
  66 #include "oops/symbol.hpp"
  67 #include "oops/valueKlass.hpp"
  68 #include "prims/jvmtiExport.hpp"
  69 #include "prims/jvmtiRedefineClasses.hpp"
  70 #include "prims/jvmtiThreadState.hpp"
  71 #include "prims/methodComparator.hpp"
  72 #include "runtime/atomic.hpp"
  73 #include "runtime/fieldDescriptor.inline.hpp"
  74 #include "runtime/handles.inline.hpp"
  75 #include "runtime/javaCalls.hpp"
  76 #include "runtime/mutexLocker.hpp"
  77 #include "runtime/orderAccess.hpp"
  78 #include "runtime/thread.inline.hpp"
  79 #include "services/classLoadingService.hpp"
  80 #include "services/threadService.hpp"
  81 #include "utilities/dtrace.hpp"
  82 #include "utilities/events.hpp"
  83 #include "utilities/macros.hpp"
  84 #include "utilities/stringUtils.hpp"
  85 #ifdef COMPILER1
  86 #include "c1/c1_Compiler.hpp"
  87 #endif


 356 
 357   bool access = (cur_host == k_nest_host);
 358 
 359   if (log_is_enabled(Trace, class, nestmates)) {
 360     ResourceMark rm(THREAD);
 361     log_trace(class, nestmates)("Class %s does %shave nestmate access to %s",
 362                                 this->external_name(),
 363                                 access ? "" : "NOT ",
 364                                 k->external_name());
 365   }
 366 
 367   return access;
 368 }
 369 
 370 InstanceKlass* InstanceKlass::allocate_instance_klass(const ClassFileParser& parser, TRAPS) {
 371   const int size = InstanceKlass::size(parser.vtable_size(),
 372                                        parser.itable_size(),
 373                                        nonstatic_oop_map_size(parser.total_oop_map_count()),
 374                                        parser.is_interface(),
 375                                        parser.is_unsafe_anonymous(),
 376                                        should_store_fingerprint(parser.is_unsafe_anonymous()),
 377                                        parser.has_flattenable_fields() ? parser.java_fields_count() : 0,
 378                                        parser.is_value_type());
 379 
 380   const Symbol* const class_name = parser.class_name();
 381   assert(class_name != NULL, "invariant");
 382   ClassLoaderData* loader_data = parser.loader_data();
 383   assert(loader_data != NULL, "invariant");
 384 
 385   InstanceKlass* ik;
 386 
 387   // Allocation
 388   if (REF_NONE == parser.reference_type()) {
 389     if (class_name == vmSymbols::java_lang_Class()) {
 390       // mirror
 391       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(parser);
 392     } else if (is_class_loader(class_name, parser)) {

 393       // class loader
 394       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(parser);
 395     } else if (parser.is_value_type()) {
 396       // value type
 397       ik = new (loader_data, size, THREAD) ValueKlass(parser);
 398     } else {
 399       // normal
 400       ik = new (loader_data, size, THREAD) InstanceKlass(parser, InstanceKlass::_misc_kind_other);
 401     }
 402   } else {
 403     // reference
 404     ik = new (loader_data, size, THREAD) InstanceRefKlass(parser);
 405   }
 406 
 407   // Check for pending exception before adding to the loader data and incrementing
 408   // class count.  Can get OOM here.
 409   if (HAS_PENDING_EXCEPTION) {
 410     return NULL;
 411   }
 412 
 413 #ifdef ASSERT
 414   assert(ik->size() == size, "");
 415   ik->bounds_check((address) ik->start_of_vtable(), false, size);
 416   ik->bounds_check((address) ik->start_of_itable(), false, size);
 417   ik->bounds_check((address) ik->end_of_itable(), true, size);
 418   ik->bounds_check((address) ik->end_of_nonstatic_oop_maps(), true, size);
 419 #endif //ASSERT
 420   return ik;
 421 }
 422 
 423 #ifndef PRODUCT
 424 bool InstanceKlass::bounds_check(address addr, bool edge_ok, intptr_t size_in_bytes) const {
 425   const char* bad = NULL;
 426   address end = NULL;
 427   if (addr < (address)this) {
 428     bad = "before";
 429   } else if (addr == (address)this) {
 430     if (edge_ok)  return true;
 431     bad = "just before";
 432   } else if (addr == (end = (address)this + sizeof(intptr_t) * (size_in_bytes < 0 ? size() : size_in_bytes))) {
 433     if (edge_ok)  return true;
 434     bad = "just after";
 435   } else if (addr > end) {
 436     bad = "after";
 437   } else {
 438     return true;
 439   }
 440   tty->print_cr("%s object bounds: " INTPTR_FORMAT " [" INTPTR_FORMAT ".." INTPTR_FORMAT "]",
 441       bad, (intptr_t)addr, (intptr_t)this, (intptr_t)end);
 442   Verbose = WizardMode = true; this->print(); //@@
 443   return false;
 444 }
 445 #endif //PRODUCT
 446 
 447 // copy method ordering from resource area to Metaspace
 448 void InstanceKlass::copy_method_ordering(const intArray* m, TRAPS) {
 449   if (m != NULL) {
 450     // allocate a new array and copy contents (memcpy?)
 451     _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
 452     for (int i = 0; i < m->length(); i++) {
 453       _method_ordering->at_put(i, m->at(i));
 454     }
 455   } else {
 456     _method_ordering = Universe::the_empty_int_array();
 457   }
 458 }
 459 
 460 // create a new array of vtable_indices for default methods
 461 Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
 462   Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
 463   assert(default_vtable_indices() == NULL, "only create once");
 464   set_default_vtable_indices(vtable_indices);
 465   return vtable_indices;
 466 }
 467 
 468 InstanceKlass::InstanceKlass(const ClassFileParser& parser, unsigned kind, KlassID id) :
 469   Klass(id),
 470   _nest_members(NULL),
 471   _nest_host_index(0),
 472   _nest_host(NULL),
 473   _static_field_size(parser.static_field_size()),
 474   _nonstatic_oop_map_size(nonstatic_oop_map_size(parser.total_oop_map_count())),
 475   _itable_len(parser.itable_size()),
 476   _extra_flags(0),
 477   _init_thread(NULL),
 478   _init_state(allocated),
 479   _reference_type(parser.reference_type()),
 480   _adr_valueklass_fixed_block(NULL)
 481 {
 482   set_vtable_length(parser.vtable_size());
 483   set_kind(kind);
 484   set_access_flags(parser.access_flags());
 485   set_is_unsafe_anonymous(parser.is_unsafe_anonymous());
 486   set_layout_helper(Klass::instance_layout_helper(parser.layout_size(),
 487                                                     false));
 488     if (parser.has_flattenable_fields()) {
 489       set_has_value_fields();
 490     }
 491     _java_fields_count = parser.java_fields_count();
 492 
 493     assert(NULL == _methods, "underlying memory not zeroed?");
 494     assert(is_instance_klass(), "is layout incorrect?");
 495     assert(size_helper() == parser.layout_size(), "incorrect size_helper?");
 496 
 497   if (DumpSharedSpaces || DynamicDumpSharedSpaces) {
 498       SystemDictionaryShared::init_dumptime_info(this);
 499     }
 500 }
 501 
 502 void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
 503                                        Array<Method*>* methods) {
 504   if (methods != NULL && methods != Universe::the_empty_method_array() &&
 505       !methods->is_shared()) {
 506     for (int i = 0; i < methods->length(); i++) {
 507       Method* method = methods->at(i);
 508       if (method == NULL) continue;  // maybe null if error processing
 509       // Only want to delete methods that are not executing for RedefineClasses.
 510       // The previous version will point to them so they're not totally dangling
 511       assert (!method->on_stack(), "shouldn't be called with methods on stack");
 512       MetadataFactory::free_metadata(loader_data, method);
 513     }
 514     MetadataFactory::free_array<Method*>(loader_data, methods);
 515   }
 516 }
 517 
 518 void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
 519                                           const Klass* super_klass,


 817         vmSymbols::java_lang_IncompatibleClassChangeError(),
 818         "class %s has interface %s as super class",
 819         external_name(),
 820         super_klass->external_name()
 821       );
 822       return false;
 823     }
 824 
 825     InstanceKlass* ik_super = InstanceKlass::cast(super_klass);
 826     ik_super->link_class_impl(CHECK_false);
 827   }
 828 
 829   // link all interfaces implemented by this class before linking this class
 830   Array<InstanceKlass*>* interfaces = local_interfaces();
 831   int num_interfaces = interfaces->length();
 832   for (int index = 0; index < num_interfaces; index++) {
 833     InstanceKlass* interk = interfaces->at(index);
 834     interk->link_class_impl(CHECK_false);
 835   }
 836 
 837 
 838   // If a class declares a method that uses a value class as an argument
 839   // type or return value type, this value class must be loaded during the
 840   // linking of this class because size and properties of the value class
 841   // must be known in order to be able to perform value type optimizations.
 842   // The implementation below is an approximation of this rule, the code
 843   // iterates over all methods of the current class (including overridden
 844   // methods), not only the methods declared by this class. This
 845   // approximation makes the code simpler, and doesn't change the semantic
 846   // because classes declaring methods overridden by the current class are
 847   // linked (and have performed their own pre-loading) before the linking
 848   // of the current class.
 849   // This is also the moment to detect potential mismatch between the
 850   // ValueTypes attribute and the kind of the class effectively loaded.
 851 
 852 
 853   // Note:
 854   // Value class types used for flattenable fields are loaded during
 855   // the loading phase (see ClassFileParser::post_process_parsed_stream()).
 856   // Value class types used as element types for array creation
 857   // are not pre-loaded. Their loading is triggered by either anewarray
 858   // or multianewarray bytecodes.
 859 
 860   // Could it be possible to do the following processing only if the
 861   // class uses value types?
 862   {
 863     ResourceMark rm(THREAD);
 864     for (int i = 0; i < methods()->length(); i++) {
 865       Method* m = methods()->at(i);
 866       for (SignatureStream ss(m->signature()); !ss.is_done(); ss.next()) {
 867         Symbol* sig = ss.as_symbol();
 868         if (ss.is_object()) {
 869           Symbol* symb = sig;
 870           if (ss.is_array()) {
 871             int i=0;
 872             while (sig->char_at(i) == '[') i++;
 873             if (i == sig->utf8_length() - 1 ) continue; // primitive array
 874             symb = SymbolTable::new_symbol(sig->as_C_string() + i + 1,
 875                                            sig->utf8_length() - 3);
 876           }
 877           if (ss.type() == T_VALUETYPE) {
 878             oop loader = class_loader();
 879             oop protection_domain = this->protection_domain();
 880             Klass* klass = SystemDictionary::resolve_or_fail(symb,
 881                                                              Handle(THREAD, loader), Handle(THREAD, protection_domain), true,
 882                                                              CHECK_false);
 883             if (symb != sig) {
 884               symb->decrement_refcount();
 885             }
 886             if (klass == NULL) {
 887               THROW_(vmSymbols::java_lang_LinkageError(), false);
 888             }
 889             if (!klass->is_value()) {
 890               THROW_(vmSymbols::java_lang_IncompatibleClassChangeError(), false);
 891             }
 892           }
 893         }
 894       }
 895     }
 896   }
 897 
 898   // in case the class is linked in the process of linking its superclasses
 899   if (is_linked()) {
 900     return true;
 901   }
 902 
 903   // trace only the link time for this klass that includes
 904   // the verification time
 905   PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
 906                              ClassLoader::perf_class_link_selftime(),
 907                              ClassLoader::perf_classes_linked(),
 908                              jt->get_thread_stat()->perf_recursion_counts_addr(),
 909                              jt->get_thread_stat()->perf_timers_addr(),
 910                              PerfClassTraceTime::CLASS_LINK);
 911 
 912   // verification & rewriting
 913   {
 914     HandleMark hm(THREAD);
 915     Handle h_init_lock(THREAD, init_lock());
 916     ObjectLocker ol(h_init_lock, THREAD, h_init_lock() != NULL);
 917     // rewritten will have been set if loader constraint error found


 947       // Initialize the vtable and interface table after
 948       // methods have been rewritten since rewrite may
 949       // fabricate new Method*s.
 950       // also does loader constraint checking
 951       //
 952       // initialize_vtable and initialize_itable need to be rerun for
 953       // a shared class if the class is not loaded by the NULL classloader.
 954       ClassLoaderData * loader_data = class_loader_data();
 955       if (!(is_shared() &&
 956             loader_data->is_the_null_class_loader_data())) {
 957         vtable().initialize_vtable(true, CHECK_false);
 958         itable().initialize_itable(true, CHECK_false);
 959       }
 960 #ifdef ASSERT
 961       else {
 962         vtable().verify(tty, true);
 963         // In case itable verification is ever added.
 964         // itable().verify(tty, true);
 965       }
 966 #endif
 967 
 968       set_init_state(linked);
 969       if (JvmtiExport::should_post_class_prepare()) {
 970         Thread *thread = THREAD;
 971         assert(thread->is_Java_thread(), "thread->is_Java_thread()");
 972         JvmtiExport::post_class_prepare((JavaThread *) thread, this);
 973       }
 974     }
 975   }
 976   return true;
 977 }
 978 
 979 // Rewrite the byte codes of all of the methods of a class.
 980 // The rewriter must be called exactly once. Rewriting must happen after
 981 // verification but before the first method of the class is executed.
 982 void InstanceKlass::rewrite_class(TRAPS) {
 983   assert(is_loaded(), "must be loaded");
 984   if (is_rewritten()) {
 985     assert(is_shared(), "rewriting an unshared class?");
 986     return;
 987   }


1101     // having a superinterface that declares, non-static, concrete methods
1102     if (!HAS_PENDING_EXCEPTION && has_nonstatic_concrete_methods()) {
1103       initialize_super_interfaces(THREAD);
1104     }
1105 
1106     // If any exceptions, complete abruptly, throwing the same exception as above.
1107     if (HAS_PENDING_EXCEPTION) {
1108       Handle e(THREAD, PENDING_EXCEPTION);
1109       CLEAR_PENDING_EXCEPTION;
1110       {
1111         EXCEPTION_MARK;
1112         // Locks object, set state, and notify all waiting threads
1113         set_initialization_state_and_notify(initialization_error, THREAD);
1114         CLEAR_PENDING_EXCEPTION;
1115       }
1116       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, -1, wait);
1117       THROW_OOP(e());
1118     }
1119   }
1120 
1121   // Step 8
1122   // Initialize classes of flattenable fields
1123   {
1124     for (AllFieldStream fs(this); !fs.done(); fs.next()) {
1125       if (fs.is_flattenable()) {
1126         Klass* klass = this->get_value_field_klass_or_null(fs.index());
1127         if (klass == NULL) {
1128           assert(fs.access_flags().is_static() && fs.access_flags().is_flattenable(),
1129               "Otherwise should have been pre-loaded");
1130           klass = SystemDictionary::resolve_or_fail(field_signature(fs.index())->fundamental_name(THREAD),
1131               Handle(THREAD, class_loader()),
1132               Handle(THREAD, protection_domain()),
1133               true, CHECK);
1134           if (klass == NULL) {
1135             THROW(vmSymbols::java_lang_NoClassDefFoundError());
1136           }
1137           if (!klass->is_value()) {
1138             THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
1139           }
1140           this->set_value_field_klass(fs.index(), klass);
1141         }
1142         InstanceKlass::cast(klass)->initialize(CHECK);
1143         if (fs.access_flags().is_static()) {
1144           java_mirror()->obj_field_put(fs.offset(), ValueKlass::cast(klass)->default_value());
1145         }
1146       }
1147     }
1148   }
1149 
1150 
1151   // Look for aot compiled methods for this klass, including class initializer.
1152   AOTLoader::load_for_klass(this, THREAD);
1153 
1154   // Step 9
1155   {
1156     DTRACE_CLASSINIT_PROBE_WAIT(clinit, -1, wait);
1157     // Timer includes any side effects of class initialization (resolution,
1158     // etc), but not recursive entry into call_class_initializer().
1159     PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
1160                              ClassLoader::perf_class_init_selftime(),
1161                              ClassLoader::perf_classes_inited(),
1162                              jt->get_thread_stat()->perf_recursion_counts_addr(),
1163                              jt->get_thread_stat()->perf_timers_addr(),
1164                              PerfClassTraceTime::CLASS_CLINIT);
1165     call_class_initializer(THREAD);
1166   }
1167 
1168   // Step 10
1169   if (!HAS_PENDING_EXCEPTION) {
1170     set_initialization_state_and_notify(fully_initialized, CHECK);
1171     {
1172       debug_only(vtable().verify(tty, true);)
1173     }
1174   }
1175   else {
1176     // Step 11 and 12
1177     Handle e(THREAD, PENDING_EXCEPTION);
1178     CLEAR_PENDING_EXCEPTION;
1179     // JVMTI has already reported the pending exception
1180     // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1181     JvmtiExport::clear_detected_exception(jt);
1182     {
1183       EXCEPTION_MARK;
1184       set_initialization_state_and_notify(initialization_error, THREAD);
1185       CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
1186       // JVMTI has already reported the pending exception
1187       // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
1188       JvmtiExport::clear_detected_exception(jt);
1189     }
1190     DTRACE_CLASSINIT_PROBE_WAIT(error, -1, wait);
1191     if (e->is_a(SystemDictionary::Error_klass())) {
1192       THROW_OOP(e());
1193     } else {
1194       JavaCallArguments args(e);
1195       THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
1196                 vmSymbols::throwable_void_signature(),


1406   return i;
1407 }
1408 
1409 instanceHandle InstanceKlass::allocate_instance_handle(TRAPS) {
1410   return instanceHandle(THREAD, allocate_instance(THREAD));
1411 }
1412 
1413 void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1414   if (is_interface() || is_abstract()) {
1415     ResourceMark rm(THREAD);
1416     THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1417               : vmSymbols::java_lang_InstantiationException(), external_name());
1418   }
1419   if (this == SystemDictionary::Class_klass()) {
1420     ResourceMark rm(THREAD);
1421     THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1422               : vmSymbols::java_lang_IllegalAccessException(), external_name());
1423   }
1424 }
1425 
1426 Klass* InstanceKlass::array_klass_impl(ArrayStorageProperties storage_props, bool or_null, int n, TRAPS) {
1427   assert(storage_props.is_empty(), "Unexpected");
1428   // Need load-acquire for lock-free read
1429   if (array_klasses_acquire() == NULL) {
1430     if (or_null) return NULL;
1431 
1432     ResourceMark rm;

1433     {
1434       // Atomic creation of array_klasses
1435       MutexLocker ma(MultiArray_lock, THREAD);
1436 
1437       // Check if update has already taken place
1438       if (array_klasses() == NULL) {
1439         Klass*    k = ObjArrayKlass::allocate_objArray_klass(storage_props, 1, this, CHECK_NULL);
1440         // use 'release' to pair with lock-free load
1441         release_set_array_klasses(k);
1442       }
1443     }
1444   }
1445   // _this will always be set at this point
1446   ObjArrayKlass* oak = (ObjArrayKlass*)array_klasses();
1447   if (or_null) {
1448     return oak->array_klass_or_null(storage_props, n);
1449   }
1450   return oak->array_klass(storage_props, n, THREAD);
1451 }
1452 
1453 Klass* InstanceKlass::array_klass_impl(ArrayStorageProperties storage_props, bool or_null, TRAPS) {
1454   return array_klass_impl(storage_props, or_null, 1, THREAD);
1455 }
1456 
1457 static int call_class_initializer_counter = 0;   // for debugging
1458 
1459 Method* InstanceKlass::class_initializer() const {
1460   Method* clinit = find_method(
1461       vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1462   if (clinit != NULL && clinit->is_class_initializer()) {
1463     return clinit;
1464   }
1465   return NULL;
1466 }
1467 
1468 void InstanceKlass::call_class_initializer(TRAPS) {
1469   if (ReplayCompiles &&
1470       (ReplaySuppressInitializers == 1 ||
1471        (ReplaySuppressInitializers >= 2 && class_loader() != NULL))) {
1472     // Hide the existence of the initializer for the purpose of replaying the compile
1473     return;
1474   }
1475 
1476   methodHandle h_method(THREAD, class_initializer());
1477   assert(!is_initialized(), "we cannot initialize twice");
1478   LogTarget(Info, class, init) lt;
1479   if (lt.is_enabled()) {
1480     ResourceMark rm;
1481     LogStream ls(lt);
1482     ls.print("%d Initializing ", call_class_initializer_counter++);
1483     name()->print_value_on(&ls);
1484     ls.print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this));
1485   }
1486   if (h_method() != NULL) {
1487     JavaCallArguments args; // No arguments
1488     JavaValue result(T_VOID);
1489     JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1490   }
1491 }
1492 
1493 
1494 void InstanceKlass::mask_for(const methodHandle& method, int bci,
1495   InterpreterOopMap* entry_for) {
1496   // Lazily create the _oop_map_cache at first request
1497   // Lock-free access requires load_acquire.
1498   OopMapCache* oop_map_cache = OrderAccess::load_acquire(&_oop_map_cache);
1499   if (oop_map_cache == NULL) {
1500     MutexLocker x(OopMapCacheAlloc_lock,  Mutex::_no_safepoint_check_flag);
1501     // Check if _oop_map_cache was allocated while we were waiting for this lock
1502     if ((oop_map_cache = _oop_map_cache) == NULL) {
1503       oop_map_cache = new OopMapCache();
1504       // Ensure _oop_map_cache is stable, since it is examined without a lock
1505       OrderAccess::release_store(&_oop_map_cache, oop_map_cache);
1506     }
1507   }
1508   // _oop_map_cache is constant after init; lookup below does its own locking.
1509   oop_map_cache->lookup(method, bci, entry_for);
1510 }
1511 
1512 
1513 bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1514   for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1515     Symbol* f_name = fs.name();
1516     Symbol* f_sig  = fs.signature();
1517     if (f_name == name && f_sig == sig) {
1518       fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1519       return true;
1520     }


1659     if (!fd.is_static()) {
1660       fields_sorted[j + 0] = fd.offset();
1661       fields_sorted[j + 1] = i;
1662       j += 2;
1663     }
1664   }
1665   if (j > 0) {
1666     length = j;
1667     // _sort_Fn is defined in growableArray.hpp.
1668     qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1669     for (int i = 0; i < length; i += 2) {
1670       fd.reinitialize(this, fields_sorted[i + 1]);
1671       assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1672       cl->do_field(&fd);
1673     }
1674   }
1675   FREE_C_HEAP_ARRAY(int, fields_sorted);
1676 }
1677 
1678 





1679 void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1680   if (array_klasses() != NULL)
1681     ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1682 }
1683 
1684 #ifdef ASSERT
1685 static int linear_search(const Array<Method*>* methods,
1686                          const Symbol* name,
1687                          const Symbol* signature) {
1688   const int len = methods->length();
1689   for (int index = 0; index < len; index++) {
1690     const Method* const m = methods->at(index);
1691     assert(m->is_method(), "must be method");
1692     if (m->signature() == signature && m->name() == name) {
1693        return index;
1694     }
1695   }
1696   return -1;
1697 }
1698 #endif


1916 }
1917 
1918 // uncached_lookup_method searches both the local class methods array and all
1919 // superclasses methods arrays, skipping any overpass methods in superclasses,
1920 // and possibly skipping private methods.
1921 Method* InstanceKlass::uncached_lookup_method(const Symbol* name,
1922                                               const Symbol* signature,
1923                                               OverpassLookupMode overpass_mode,
1924                                               PrivateLookupMode private_mode) const {
1925   OverpassLookupMode overpass_local_mode = overpass_mode;
1926   const Klass* klass = this;
1927   while (klass != NULL) {
1928     Method* const method = InstanceKlass::cast(klass)->find_method_impl(name,
1929                                                                         signature,
1930                                                                         overpass_local_mode,
1931                                                                         find_static,
1932                                                                         private_mode);
1933     if (method != NULL) {
1934       return method;
1935     }
1936     if (name == vmSymbols::object_initializer_name()) {
1937       break;  // <init> is never inherited, not even as a static factory
1938     }
1939     klass = klass->super();
1940     overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1941   }
1942   return NULL;
1943 }
1944 
1945 #ifdef ASSERT
1946 // search through class hierarchy and return true if this class or
1947 // one of the superclasses was redefined
1948 bool InstanceKlass::has_redefined_this_or_super() const {
1949   const Klass* klass = this;
1950   while (klass != NULL) {
1951     if (InstanceKlass::cast(klass)->has_been_redefined()) {
1952       return true;
1953     }
1954     klass = klass->super();
1955   }
1956   return false;
1957 }
1958 #endif


2659 
2660 #if INCLUDE_JVMTI
2661   // Deallocate breakpoint records
2662   if (breakpoints() != 0x0) {
2663     methods_do(clear_all_breakpoints);
2664     assert(breakpoints() == 0x0, "should have cleared breakpoints");
2665   }
2666 
2667   // deallocate the cached class file
2668   if (_cached_class_file != NULL) {
2669     os::free(_cached_class_file);
2670     _cached_class_file = NULL;
2671   }
2672 #endif
2673 
2674   // Decrement symbol reference counts associated with the unloaded class.
2675   if (_name != NULL) _name->decrement_refcount();
2676   // unreference array name derived from this class name (arrays of an unloaded
2677   // class can't be referenced anymore).
2678   if (_array_name != NULL)  _array_name->decrement_refcount();
2679   if (_value_types != NULL) {
2680     for (int i = 0; i < _value_types->length(); i++) {
2681       Symbol* s = _value_types->at(i)._class_name;
2682       if (s != NULL) {
2683         s->decrement_refcount();
2684       }
2685     }
2686   }
2687   if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension);
2688 }
2689 
2690 void InstanceKlass::set_source_debug_extension(const char* array, int length) {
2691   if (array == NULL) {
2692     _source_debug_extension = NULL;
2693   } else {
2694     // Adding one to the attribute length in order to store a null terminator
2695     // character could cause an overflow because the attribute length is
2696     // already coded with an u4 in the classfile, but in practice, it's
2697     // unlikely to happen.
2698     assert((length+1) > length, "Overflow checking");
2699     char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2700     for (int i = 0; i < length; i++) {
2701       sde[i] = array[i];
2702     }
2703     sde[length] = '\0';
2704     _source_debug_extension = sde;
2705   }
2706 }
2707 
2708 const char* InstanceKlass::signature_name() const {
2709   return signature_name_of(is_value() ? 'Q' : 'L');
2710 }
2711 
2712 const char* InstanceKlass::signature_name_of(char c) const {
2713   int hash_len = 0;
2714   char hash_buf[40];
2715 
2716   // If this is an unsafe anonymous class, append a hash to make the name unique
2717   if (is_unsafe_anonymous()) {
2718     intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2719     jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash);
2720     hash_len = (int)strlen(hash_buf);
2721   }
2722 
2723   // Get the internal name as a c string
2724   const char* src = (const char*) (name()->as_C_string());
2725   const int src_length = (int)strlen(src);
2726 
2727   char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2728 
2729   // Add L or Q as type indicator
2730   int dest_index = 0;
2731   dest[dest_index++] = c;
2732 
2733   // Add the actual class name
2734   for (int src_index = 0; src_index < src_length; ) {
2735     dest[dest_index++] = src[src_index++];
2736   }
2737 
2738   // If we have a hash, append it
2739   for (int hash_index = 0; hash_index < hash_len; ) {
2740     dest[dest_index++] = hash_buf[hash_index++];
2741   }
2742 
2743   // Add the semicolon and the NULL
2744   dest[dest_index++] = ';';
2745   dest[dest_index] = '\0';
2746   return dest;
2747 }
2748 
2749 // Used to obtain the package name from a fully qualified class name.
2750 Symbol* InstanceKlass::package_from_name(const Symbol* name, TRAPS) {
2751   if (name == NULL) {


3242   }
3243 
3244   assert(match_level == false || best == NULL, "shouldn't pick up anything if match_level is set");
3245   if (best != NULL && best->comp_level() >= comp_level) {
3246     return best;
3247   }
3248   return NULL;
3249 }
3250 
3251 // -----------------------------------------------------------------------------------------------------
3252 // Printing
3253 
3254 #ifndef PRODUCT
3255 
3256 #define BULLET  " - "
3257 
3258 static const char* state_names[] = {
3259   "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
3260 };
3261 
3262 static void print_vtable(address self, intptr_t* start, int len, outputStream* st) {
3263   ResourceMark rm;
3264   int* forward_refs = NEW_RESOURCE_ARRAY(int, len);
3265   for (int i = 0; i < len; i++)  forward_refs[i] = 0;
3266   for (int i = 0; i < len; i++) {
3267     intptr_t e = start[i];
3268     st->print("%d : " INTPTR_FORMAT, i, e);
3269     if (forward_refs[i] != 0) {
3270       int from = forward_refs[i];
3271       int off = (int) start[from];
3272       st->print(" (offset %d <= [%d])", off, from);
3273     }
3274     if (MetaspaceObj::is_valid((Metadata*)e)) {
3275       st->print(" ");
3276       ((Metadata*)e)->print_value_on(st);
3277     } else if (self != NULL && e > 0 && e < 0x10000) {
3278       address location = self + e;
3279       int index = (int)((intptr_t*)location - start);
3280       st->print(" (offset %d => [%d])", (int)e, index);
3281       if (index >= 0 && index < len)
3282         forward_refs[index] = i;
3283     }
3284     st->cr();
3285   }
3286 }
3287 
3288 static void print_vtable(vtableEntry* start, int len, outputStream* st) {
3289   return print_vtable(NULL, reinterpret_cast<intptr_t*>(start), len, st);
3290 }
3291 
3292 template<typename T>
3293  static void print_array_on(outputStream* st, Array<T>* array) {
3294    if (array == NULL) { st->print_cr("NULL"); return; }
3295    array->print_value_on(st); st->cr();
3296    if (Verbose || WizardMode) {
3297      for (int i = 0; i < array->length(); i++) {
3298        st->print("%d : ", i); array->at(i)->print_value_on(st); st->cr();
3299      }
3300    }
3301  }
3302 
3303 static void print_array_on(outputStream* st, Array<int>* array) {
3304   if (array == NULL) { st->print_cr("NULL"); return; }
3305   array->print_value_on(st); st->cr();
3306   if (Verbose || WizardMode) {
3307     for (int i = 0; i < array->length(); i++) {
3308       st->print("%d : %d", i, array->at(i)); st->cr();
3309     }
3310   }
3311 }
3312 
3313 void InstanceKlass::print_on(outputStream* st) const {
3314   assert(is_klass(), "must be klass");
3315   Klass::print_on(st);
3316 
3317   st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
3318   st->print(BULLET"klass size:        %d", size());                               st->cr();
3319   st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
3320   st->print(BULLET"misc flags:        0x%x", _misc_flags);                        st->cr();
3321   st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
3322   st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
3323   st->print(BULLET"super:             "); Metadata::print_value_on_maybe_null(st, super()); st->cr();
3324   st->print(BULLET"sub:               ");
3325   Klass* sub = subklass();
3326   int n;
3327   for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
3328     if (n < MaxSubklassPrintSize) {
3329       sub->print_value_on(st);
3330       st->print("   ");
3331     }
3332   }
3333   if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
3334   st->cr();
3335 
3336   if (is_interface()) {
3337     st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
3338     if (nof_implementors() == 1) {
3339       st->print_cr(BULLET"implementor:    ");
3340       st->print("   ");
3341       implementor()->print_value_on(st);
3342       st->cr();
3343     }
3344   }
3345 
3346   st->print(BULLET"arrays:            "); Metadata::print_value_on_maybe_null(st, array_klasses()); st->cr();
3347   st->print(BULLET"methods:           "); print_array_on(st, methods());
3348   st->print(BULLET"method ordering:   "); print_array_on(st, method_ordering());
3349   st->print(BULLET"default_methods:   "); print_array_on(st, default_methods());












3350   if (default_vtable_indices() != NULL) {
3351     st->print(BULLET"default vtable indices:   "); print_array_on(st, default_vtable_indices());
3352   }
3353   st->print(BULLET"local interfaces:  "); print_array_on(st, local_interfaces());
3354   st->print(BULLET"trans. interfaces: "); print_array_on(st, transitive_interfaces());
3355   st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
3356   if (class_loader_data() != NULL) {
3357     st->print(BULLET"class loader data:  ");
3358     class_loader_data()->print_value_on(st);
3359     st->cr();
3360   }
3361   st->print(BULLET"unsafe anonymous host class:        "); Metadata::print_value_on_maybe_null(st, unsafe_anonymous_host()); st->cr();
3362   if (source_file_name() != NULL) {
3363     st->print(BULLET"source file:       ");
3364     source_file_name()->print_value_on(st);
3365     st->cr();
3366   }
3367   if (source_debug_extension() != NULL) {
3368     st->print(BULLET"source debug extension:       ");
3369     st->print("%s", source_debug_extension());
3370     st->cr();
3371   }
3372   st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
3373   st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
3374   st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();


3387     if (have_pv) st->cr();
3388   }
3389 
3390   if (generic_signature() != NULL) {
3391     st->print(BULLET"generic signature: ");
3392     generic_signature()->print_value_on(st);
3393     st->cr();
3394   }
3395   st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
3396   st->print(BULLET"nest members:     "); nest_members()->print_value_on(st);     st->cr();
3397   if (java_mirror() != NULL) {
3398     st->print(BULLET"java mirror:       ");
3399     java_mirror()->print_value_on(st);
3400     st->cr();
3401   } else {
3402     st->print_cr(BULLET"java mirror:       NULL");
3403   }
3404   st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
3405   if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
3406   st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
3407   if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(NULL, start_of_itable(), itable_length(), st);
3408   st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
3409   FieldPrinter print_static_field(st);
3410   ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
3411   st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
3412   FieldPrinter print_nonstatic_field(st);
3413   InstanceKlass* ik = const_cast<InstanceKlass*>(this);
3414   ik->do_nonstatic_fields(&print_nonstatic_field);
3415 
3416   st->print(BULLET"non-static oop maps: ");
3417   OopMapBlock* map     = start_of_nonstatic_oop_maps();
3418   OopMapBlock* end_map = map + nonstatic_oop_map_count();
3419   while (map < end_map) {
3420     st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
3421     map++;
3422   }
3423   st->cr();
3424 }
3425 
3426 #endif //PRODUCT
3427 


4169   if (holder == NULL) {
4170     return NULL; // The version of klass is gone, no method is found
4171   }
4172   Method* method = holder->method_with_orig_idnum(idnum);
4173   return method;
4174 }
4175 
4176 #if INCLUDE_JVMTI
4177 JvmtiCachedClassFileData* InstanceKlass::get_cached_class_file() {
4178   return _cached_class_file;
4179 }
4180 
4181 jint InstanceKlass::get_cached_class_file_len() {
4182   return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
4183 }
4184 
4185 unsigned char * InstanceKlass::get_cached_class_file_bytes() {
4186   return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
4187 }
4188 #endif
4189 
4190 #define THROW_DVT_ERROR(s) \
4191   Exceptions::fthrow(THREAD_AND_LOCATION, vmSymbols::java_lang_IncompatibleClassChangeError(), \
4192       "ValueCapableClass class '%s' %s", external_name(),(s)); \
4193       return
< prev index next >