instanceKlass.cpp revision 9248:6ab7e19c9220
119370Spst/*
298948Sobrien * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
3130809Smarcel * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
419370Spst *
519370Spst * This code is free software; you can redistribute it and/or modify it
698948Sobrien * under the terms of the GNU General Public License version 2 only, as
719370Spst * published by the Free Software Foundation.
819370Spst *
919370Spst * This code is distributed in the hope that it will be useful, but WITHOUT
1019370Spst * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1119370Spst * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
1219370Spst * version 2 for more details (a copy is included in the LICENSE file that
1319370Spst * accompanied this code).
1419370Spst *
1519370Spst * You should have received a copy of the GNU General Public License version
1619370Spst * 2 along with this work; if not, write to the Free Software Foundation,
1719370Spst * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1819370Spst *
1919370Spst * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2019370Spst * or visit www.oracle.com if you need additional information or have any
2119370Spst * questions.
2219370Spst *
2319370Spst */
2419370Spst
2598948Sobrien#include "precompiled.hpp"
2698948Sobrien#include "classfile/javaClasses.hpp"
2719370Spst#include "classfile/systemDictionary.hpp"
2898948Sobrien#include "classfile/verifier.hpp"
2919370Spst#include "classfile/vmSymbols.hpp"
3019370Spst#include "compiler/compileBroker.hpp"
31130809Smarcel#include "gc/shared/collectedHeap.inline.hpp"
3298948Sobrien#include "gc/shared/specialized_oop_closures.hpp"
3319370Spst#include "interpreter/oopMapCache.hpp"
34130809Smarcel#include "interpreter/rewriter.hpp"
35130809Smarcel#include "jvmtifiles/jvmti.h"
3619370Spst#include "memory/heapInspection.hpp"
3798948Sobrien#include "memory/iterator.inline.hpp"
3819370Spst#include "memory/metadataFactory.hpp"
3919370Spst#include "memory/oopFactory.hpp"
4098948Sobrien#include "oops/fieldStreams.hpp"
41130809Smarcel#include "oops/instanceClassLoaderKlass.hpp"
4298948Sobrien#include "oops/instanceKlass.inline.hpp"
43130809Smarcel#include "oops/instanceMirrorKlass.hpp"
4498948Sobrien#include "oops/instanceOop.hpp"
4598948Sobrien#include "oops/klass.inline.hpp"
4619370Spst#include "oops/method.hpp"
4719370Spst#include "oops/oop.inline.hpp"
4819370Spst#include "oops/symbol.hpp"
4919370Spst#include "prims/jvmtiExport.hpp"
50130809Smarcel#include "prims/jvmtiRedefineClasses.hpp"
51130809Smarcel#include "prims/jvmtiRedefineClassesTrace.hpp"
52130809Smarcel#include "prims/jvmtiThreadState.hpp"
5319370Spst#include "prims/methodComparator.hpp"
5498948Sobrien#include "runtime/atomic.inline.hpp"
55130809Smarcel#include "runtime/fieldDescriptor.hpp"
5619370Spst#include "runtime/handles.inline.hpp"
5798948Sobrien#include "runtime/javaCalls.hpp"
5898948Sobrien#include "runtime/mutexLocker.hpp"
5998948Sobrien#include "runtime/orderAccess.inline.hpp"
6098948Sobrien#include "runtime/thread.inline.hpp"
6198948Sobrien#include "services/classLoadingService.hpp"
6298948Sobrien#include "services/threadService.hpp"
6319370Spst#include "utilities/dtrace.hpp"
6498948Sobrien#include "utilities/macros.hpp"
6598948Sobrien#ifdef COMPILER1
6698948Sobrien#include "c1/c1_Compiler.hpp"
6798948Sobrien#endif
6819370Spst
6919370Spst#ifdef DTRACE_ENABLED
7019370Spst
7119370Spst
7219370Spst#define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
7319370Spst#define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
7446289Sdfr#define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
7598948Sobrien#define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
7619370Spst#define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
7719370Spst#define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
7819370Spst#define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
7998948Sobrien#define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
8019370Spst#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
8119370Spst  {                                                              \
8219370Spst    char* data = NULL;                                           \
8319370Spst    int len = 0;                                                 \
8419370Spst    Symbol* name = (clss)->name();                               \
8519370Spst    if (name != NULL) {                                          \
8698948Sobrien      data = (char*)name->bytes();                               \
87130809Smarcel      len = name->utf8_length();                                 \
8819370Spst    }                                                            \
8919370Spst    HOTSPOT_CLASS_INITIALIZATION_##type(                         \
9019370Spst      data, len, (clss)->class_loader(), thread_type);           \
9119370Spst  }
9298948Sobrien
9319370Spst#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
9498948Sobrien  {                                                              \
9598948Sobrien    char* data = NULL;                                           \
9698948Sobrien    int len = 0;                                                 \
9798948Sobrien    Symbol* name = (clss)->name();                               \
9898948Sobrien    if (name != NULL) {                                          \
9998948Sobrien      data = (char*)name->bytes();                               \
10019370Spst      len = name->utf8_length();                                 \
10198948Sobrien    }                                                            \
10298948Sobrien    HOTSPOT_CLASS_INITIALIZATION_##type(                         \
10398948Sobrien      data, len, (clss)->class_loader(), thread_type, wait);     \
10498948Sobrien  }
10519370Spst
10619370Spst#else //  ndef DTRACE_ENABLED
10719370Spst
10898948Sobrien#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
10946289Sdfr#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
11098948Sobrien
11119370Spst#endif //  ndef DTRACE_ENABLED
11219370Spst
11319370Spstvolatile int InstanceKlass::_total_instanceKlass_count = 0;
11419370Spst
115130809SmarcelInstanceKlass* InstanceKlass::allocate_instance_klass(
11619370Spst                                              ClassLoaderData* loader_data,
11719370Spst                                              int vtable_len,
118130809Smarcel                                              int itable_len,
11998948Sobrien                                              int static_field_size,
12019370Spst                                              int nonstatic_oop_map_size,
12119370Spst                                              ReferenceType rt,
12219370Spst                                              AccessFlags access_flags,
12319370Spst                                              Symbol* name,
12419370Spst                                              Klass* super_klass,
12519370Spst                                              bool is_anonymous,
12619370Spst                                              TRAPS) {
12719370Spst
12819370Spst  int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
12919370Spst                                 access_flags.is_interface(), is_anonymous);
13019370Spst
131130809Smarcel  // Allocation
13298948Sobrien  InstanceKlass* ik;
13398948Sobrien  if (rt == REF_NONE) {
13498948Sobrien    if (name == vmSymbols::java_lang_Class()) {
13519370Spst      ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
13646289Sdfr        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
13719370Spst        access_flags, is_anonymous);
13819370Spst    } else if (name == vmSymbols::java_lang_ClassLoader() ||
13919370Spst          (SystemDictionary::ClassLoader_klass_loaded() &&
14019370Spst          super_klass != NULL &&
14198948Sobrien          super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
14298948Sobrien      ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
14319370Spst        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
14419370Spst        access_flags, is_anonymous);
14598948Sobrien    } else {
146130809Smarcel      // normal class
14719370Spst      ik = new (loader_data, size, THREAD) InstanceKlass(
14898948Sobrien        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size,
14998948Sobrien        InstanceKlass::_misc_kind_other, rt, access_flags, is_anonymous);
15019370Spst    }
15119370Spst  } else {
15219370Spst    // reference klass
15346289Sdfr    ik = new (loader_data, size, THREAD) InstanceRefKlass(
15446289Sdfr        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
15546289Sdfr        access_flags, is_anonymous);
15619370Spst  }
15798948Sobrien
15898948Sobrien  // Check for pending exception before adding to the loader data and incrementing
159130809Smarcel  // class count.  Can get OOM here.
16098948Sobrien  if (HAS_PENDING_EXCEPTION) {
16198948Sobrien    return NULL;
16298948Sobrien  }
16346289Sdfr
16498948Sobrien  // Add all classes to our internal class loader list here,
16546289Sdfr  // including classes in the bootstrap (NULL) class loader.
16698948Sobrien  loader_data->add_class(ik);
16746289Sdfr
16898948Sobrien  Atomic::inc(&_total_instanceKlass_count);
16946289Sdfr  return ik;
17098948Sobrien}
17119370Spst
17219370Spst
17319370Spst// copy method ordering from resource area to Metaspace
17419370Spstvoid InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
17519370Spst  if (m != NULL) {
17619370Spst    // allocate a new array and copy contents (memcpy?)
17719370Spst    _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
17819370Spst    for (int i = 0; i < m->length(); i++) {
17919370Spst      _method_ordering->at_put(i, m->at(i));
18019370Spst    }
18119370Spst  } else {
18219370Spst    _method_ordering = Universe::the_empty_int_array();
18319370Spst  }
18419370Spst}
18519370Spst
18619370Spst// create a new array of vtable_indices for default methods
18719370SpstArray<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
18819370Spst  Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
18919370Spst  assert(default_vtable_indices() == NULL, "only create once");
19019370Spst  set_default_vtable_indices(vtable_indices);
19119370Spst  return vtable_indices;
19219370Spst}
19319370Spst
19419370SpstInstanceKlass::InstanceKlass(int vtable_len,
195130809Smarcel                             int itable_len,
19619370Spst                             int static_field_size,
19719370Spst                             int nonstatic_oop_map_size,
19819370Spst                             unsigned kind,
19998948Sobrien                             ReferenceType rt,
200130809Smarcel                             AccessFlags access_flags,
201130809Smarcel                             bool is_anonymous) {
20219370Spst  No_Safepoint_Verifier no_safepoint; // until k becomes parsable
20398948Sobrien
20498948Sobrien  int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
20598948Sobrien                                   access_flags.is_interface(), is_anonymous);
20698948Sobrien
20798948Sobrien  set_vtable_length(vtable_len);
20819370Spst  set_itable_length(itable_len);
20919370Spst  set_static_field_size(static_field_size);
21019370Spst  set_nonstatic_oop_map_size(nonstatic_oop_map_size);
21198948Sobrien  set_access_flags(access_flags);
21298948Sobrien  _misc_flags = 0;  // initialize to zero
21319370Spst  set_kind(kind);
214130809Smarcel  set_is_anonymous(is_anonymous);
215130809Smarcel  assert(size() == iksize, "wrong size for object");
216130809Smarcel
21719370Spst  set_array_klasses(NULL);
21819370Spst  set_methods(NULL);
21919370Spst  set_method_ordering(NULL);
22019370Spst  set_default_methods(NULL);
22119370Spst  set_default_vtable_indices(NULL);
22298948Sobrien  set_local_interfaces(NULL);
22319370Spst  set_transitive_interfaces(NULL);
22419370Spst  init_implementor();
22598948Sobrien  set_fields(NULL, 0);
22619370Spst  set_constants(NULL);
22719370Spst  set_class_loader_data(NULL);
22819370Spst  set_source_file_name_index(0);
22919370Spst  set_source_debug_extension(NULL, 0);
23019370Spst  set_array_name(NULL);
23119370Spst  set_inner_classes(NULL);
23219370Spst  set_static_oop_field_count(0);
23319370Spst  set_nonstatic_field_size(0);
23419370Spst  set_is_marked_dependent(false);
23519370Spst  set_has_unloaded_dependent(false);
23619370Spst  set_init_state(InstanceKlass::allocated);
23719370Spst  set_init_thread(NULL);
23898948Sobrien  set_reference_type(rt);
23919370Spst  set_oop_map_cache(NULL);
24098948Sobrien  set_jni_ids(NULL);
24198948Sobrien  set_osr_nmethods_head(NULL);
24298948Sobrien  set_breakpoints(NULL);
24398948Sobrien  init_previous_versions();
24498948Sobrien  set_generic_signature_index(0);
24598948Sobrien  release_set_methods_jmethod_ids(NULL);
24698948Sobrien  set_annotations(NULL);
24798948Sobrien  set_jvmti_cached_class_field_map(NULL);
24898948Sobrien  set_initial_method_idnum(0);
24998948Sobrien  _dependencies = NULL;
25098948Sobrien  set_jvmti_cached_class_field_map(NULL);
25198948Sobrien  set_cached_class_file(NULL);
25298948Sobrien  set_initial_method_idnum(0);
25398948Sobrien  set_minor_version(0);
25498948Sobrien  set_major_version(0);
25598948Sobrien  NOT_PRODUCT(_verify_count = 0;)
25698948Sobrien
25798948Sobrien  // initialize the non-header words to zero
25898948Sobrien  intptr_t* p = (intptr_t*)this;
25998948Sobrien  for (int index = InstanceKlass::header_size(); index < iksize; index++) {
26098948Sobrien    p[index] = NULL_WORD;
26198948Sobrien  }
26298948Sobrien
26398948Sobrien  // Set temporary value until parseClassFile updates it with the real instance
26498948Sobrien  // size.
26598948Sobrien  set_layout_helper(Klass::instance_layout_helper(0, true));
26698948Sobrien}
26798948Sobrien
26898948Sobrien
26998948Sobrienvoid InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
27098948Sobrien                                       Array<Method*>* methods) {
27198948Sobrien  if (methods != NULL && methods != Universe::the_empty_method_array() &&
27298948Sobrien      !methods->is_shared()) {
27398948Sobrien    for (int i = 0; i < methods->length(); i++) {
27498948Sobrien      Method* method = methods->at(i);
27598948Sobrien      if (method == NULL) continue;  // maybe null if error processing
27698948Sobrien      // Only want to delete methods that are not executing for RedefineClasses.
27798948Sobrien      // The previous version will point to them so they're not totally dangling
27898948Sobrien      assert (!method->on_stack(), "shouldn't be called with methods on stack");
27998948Sobrien      MetadataFactory::free_metadata(loader_data, method);
28098948Sobrien    }
28198948Sobrien    MetadataFactory::free_array<Method*>(loader_data, methods);
28298948Sobrien  }
28398948Sobrien}
28498948Sobrien
28598948Sobrienvoid InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
28698948Sobrien                                          Klass* super_klass,
28798948Sobrien                                          Array<Klass*>* local_interfaces,
28898948Sobrien                                          Array<Klass*>* transitive_interfaces) {
28998948Sobrien  // Only deallocate transitive interfaces if not empty, same as super class
29098948Sobrien  // or same as local interfaces.  See code in parseClassFile.
29198948Sobrien  Array<Klass*>* ti = transitive_interfaces;
29298948Sobrien  if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
29398948Sobrien    // check that the interfaces don't come from super class
29498948Sobrien    Array<Klass*>* sti = (super_klass == NULL) ? NULL :
29598948Sobrien                    InstanceKlass::cast(super_klass)->transitive_interfaces();
29698948Sobrien    if (ti != sti && ti != NULL && !ti->is_shared()) {
29798948Sobrien      MetadataFactory::free_array<Klass*>(loader_data, ti);
29898948Sobrien    }
29998948Sobrien  }
30098948Sobrien
30198948Sobrien  // local interfaces can be empty
30298948Sobrien  if (local_interfaces != Universe::the_empty_klass_array() &&
30398948Sobrien      local_interfaces != NULL && !local_interfaces->is_shared()) {
30498948Sobrien    MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
30598948Sobrien  }
30698948Sobrien}
30798948Sobrien
30898948Sobrien// This function deallocates the metadata and C heap pointers that the
30998948Sobrien// InstanceKlass points to.
31098948Sobrienvoid InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
31198948Sobrien
31298948Sobrien  // Orphan the mirror first, CMS thinks it's still live.
31398948Sobrien  if (java_mirror() != NULL) {
31498948Sobrien    java_lang_Class::set_klass(java_mirror(), NULL);
31598948Sobrien  }
31698948Sobrien
31798948Sobrien  // Need to take this class off the class loader data list.
31898948Sobrien  loader_data->remove_class(this);
31998948Sobrien
32098948Sobrien  // The array_klass for this class is created later, after error handling.
32198948Sobrien  // For class redefinition, we keep the original class so this scratch class
32298948Sobrien  // doesn't have an array class.  Either way, assert that there is nothing
32398948Sobrien  // to deallocate.
32498948Sobrien  assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
32598948Sobrien
32698948Sobrien  // Release C heap allocated data that this might point to, which includes
32798948Sobrien  // reference counting symbol names.
32898948Sobrien  release_C_heap_structures();
32998948Sobrien
33098948Sobrien  deallocate_methods(loader_data, methods());
33198948Sobrien  set_methods(NULL);
33298948Sobrien
33398948Sobrien  if (method_ordering() != NULL &&
33498948Sobrien      method_ordering() != Universe::the_empty_int_array() &&
33598948Sobrien      !method_ordering()->is_shared()) {
33698948Sobrien    MetadataFactory::free_array<int>(loader_data, method_ordering());
33746289Sdfr  }
33819370Spst  set_method_ordering(NULL);
33919370Spst
34019370Spst  // default methods can be empty
34119370Spst  if (default_methods() != NULL &&
34219370Spst      default_methods() != Universe::the_empty_method_array() &&
34319370Spst      !default_methods()->is_shared()) {
34419370Spst    MetadataFactory::free_array<Method*>(loader_data, default_methods());
34519370Spst  }
34619370Spst  // Do NOT deallocate the default methods, they are owned by superinterfaces.
34746289Sdfr  set_default_methods(NULL);
34846289Sdfr
34946289Sdfr  // default methods vtable indices can be empty
350130809Smarcel  if (default_vtable_indices() != NULL &&
35146289Sdfr      !default_vtable_indices()->is_shared()) {
35246289Sdfr    MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
35346289Sdfr  }
35446289Sdfr  set_default_vtable_indices(NULL);
35546289Sdfr
35619370Spst
35719370Spst  // This array is in Klass, but remove it with the InstanceKlass since
35819370Spst  // this place would be the only caller and it can share memory with transitive
35919370Spst  // interfaces.
36019370Spst  if (secondary_supers() != NULL &&
36119370Spst      secondary_supers() != Universe::the_empty_klass_array() &&
36219370Spst      secondary_supers() != transitive_interfaces() &&
36398948Sobrien      !secondary_supers()->is_shared()) {
36498948Sobrien    MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
36598948Sobrien  }
36698948Sobrien  set_secondary_supers(NULL);
36798948Sobrien
36819370Spst  deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
36998948Sobrien  set_transitive_interfaces(NULL);
37019370Spst  set_local_interfaces(NULL);
37119370Spst
37219370Spst  if (fields() != NULL && !fields()->is_shared()) {
37319370Spst    MetadataFactory::free_array<jushort>(loader_data, fields());
37419370Spst  }
37519370Spst  set_fields(NULL, 0);
376130809Smarcel
37746289Sdfr  // If a method from a redefined class is using this constant pool, don't
37819370Spst  // delete it, yet.  The new class's previous version will point to this.
37919370Spst  if (constants() != NULL) {
38019370Spst    assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
38119370Spst    if (!constants()->is_shared()) {
38219370Spst      MetadataFactory::free_metadata(loader_data, constants());
38319370Spst    }
38419370Spst    // Delete any cached resolution errors for the constant pool
38519370Spst    SystemDictionary::delete_resolution_error(constants());
38619370Spst
38719370Spst    set_constants(NULL);
38819370Spst  }
38919370Spst
39019370Spst  if (inner_classes() != NULL &&
39119370Spst      inner_classes() != Universe::the_empty_short_array() &&
39219370Spst      !inner_classes()->is_shared()) {
39319370Spst    MetadataFactory::free_array<jushort>(loader_data, inner_classes());
39419370Spst  }
39519370Spst  set_inner_classes(NULL);
396130809Smarcel
39719370Spst  // We should deallocate the Annotations instance if it's not in shared spaces.
398130809Smarcel  if (annotations() != NULL && !annotations()->is_shared()) {
39946289Sdfr    MetadataFactory::free_metadata(loader_data, annotations());
40019370Spst  }
40119370Spst  set_annotations(NULL);
40219370Spst}
40346289Sdfr
40446289Sdfrbool InstanceKlass::should_be_initialized() const {
40519370Spst  return !is_initialized();
40646289Sdfr}
40746289Sdfr
40846289SdfrklassVtable* InstanceKlass::vtable() const {
40946289Sdfr  return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
41019370Spst}
41119370Spst
41219370SpstklassItable* InstanceKlass::itable() const {
41319370Spst  return new klassItable(instanceKlassHandle(this));
41498948Sobrien}
41598948Sobrien
41619370Spstvoid InstanceKlass::eager_initialize(Thread *thread) {
41798948Sobrien  if (!EagerInitialization) return;
41898948Sobrien
41919370Spst  if (this->is_not_initialized()) {
42019370Spst    // abort if the the class has a class initializer
421130809Smarcel    if (this->class_initializer() != NULL) return;
422130809Smarcel
42319370Spst    // abort if it is java.lang.Object (initialization is handled in genesis)
42446289Sdfr    Klass* super = this->super();
42546289Sdfr    if (super == NULL) return;
426130809Smarcel
427130809Smarcel    // abort if the super class should be initialized
42846289Sdfr    if (!InstanceKlass::cast(super)->is_initialized()) return;
42946289Sdfr
43046289Sdfr    // call body to expose the this pointer
43146289Sdfr    instanceKlassHandle this_k(thread, this);
43246289Sdfr    eager_initialize_impl(this_k);
43398948Sobrien  }
43446289Sdfr}
43519370Spst
43619370Spst// JVMTI spec thinks there are signers and protection domain in the
43719370Spst// instanceKlass.  These accessors pretend these fields are there.
43846289Sdfr// The hprof specification also thinks these fields are in InstanceKlass.
43946289Sdfroop InstanceKlass::protection_domain() const {
44019370Spst  // return the protection_domain from the mirror
44119370Spst  return java_lang_Class::protection_domain(java_mirror());
44219370Spst}
44398948Sobrien
44419370Spst// To remove these from requires an incompatible change and CCC request.
44546289SdfrobjArrayOop InstanceKlass::signers() const {
44646289Sdfr  // return the signers from the mirror
44798948Sobrien  return java_lang_Class::signers(java_mirror());
448130809Smarcel}
449130809Smarcel
450130809Smarceloop InstanceKlass::init_lock() const {
451130809Smarcel  // return the init lock from the mirror
45246289Sdfr  oop lock = java_lang_Class::init_lock(java_mirror());
45398948Sobrien  // Prevent reordering with any access of initialization state
45498948Sobrien  OrderAccess::loadload();
45546289Sdfr  assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
45698948Sobrien         "only fully initialized state can have a null lock");
45798948Sobrien  return lock;
45898948Sobrien}
45998948Sobrien
46098948Sobrien// Set the initialization lock to null so the object can be GC'ed.  Any racing
46198948Sobrien// threads to get this lock will see a null lock and will not lock.
46298948Sobrien// That's okay because they all check for initialized state after getting
46398948Sobrien// the lock and return.
46498948Sobrienvoid InstanceKlass::fence_and_clear_init_lock() {
46598948Sobrien  // make sure previous stores are all done, notably the init_state.
46698948Sobrien  OrderAccess::storestore();
46798948Sobrien  java_lang_Class::set_init_lock(java_mirror(), NULL);
46898948Sobrien  assert(!is_not_initialized(), "class must be initialized now");
46998948Sobrien}
47098948Sobrien
47146289Sdfrvoid InstanceKlass::eager_initialize_impl(instanceKlassHandle this_k) {
472130809Smarcel  EXCEPTION_MARK;
473130809Smarcel  oop init_lock = this_k->init_lock();
47498948Sobrien  ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
47598948Sobrien
47619370Spst  // abort if someone beat us to the initialization
47719370Spst  if (!this_k->is_not_initialized()) return;  // note: not equivalent to is_initialized()
47819370Spst
47919370Spst  ClassState old_state = this_k->init_state();
48019370Spst  link_class_impl(this_k, true, THREAD);
48119370Spst  if (HAS_PENDING_EXCEPTION) {
48219370Spst    CLEAR_PENDING_EXCEPTION;
48319370Spst    // Abort if linking the class throws an exception.
48419370Spst
48519370Spst    // Use a test to avoid redundantly resetting the state if there's
48619370Spst    // no change.  Set_init_state() asserts that state changes make
48719370Spst    // progress, whereas here we might just be spinning in place.
48819370Spst    if( old_state != this_k->_init_state )
48919370Spst      this_k->set_init_state (old_state);
49019370Spst  } else {
49119370Spst    // linking successfull, mark class as initialized
49219370Spst    this_k->set_init_state (fully_initialized);
49319370Spst    this_k->fence_and_clear_init_lock();
49419370Spst    // trace
49519370Spst    if (TraceClassInitialization) {
49619370Spst      ResourceMark rm(THREAD);
49719370Spst      tty->print_cr("[Initialized %s without side effects]", this_k->external_name());
49819370Spst    }
49919370Spst  }
50019370Spst}
50119370Spst
50219370Spst
50319370Spst// See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
50419370Spst// process. The step comments refers to the procedure described in that section.
50519370Spst// Note: implementation moved to static method to expose the this pointer.
50619370Spstvoid InstanceKlass::initialize(TRAPS) {
50719370Spst  if (this->should_be_initialized()) {
50819370Spst    HandleMark hm(THREAD);
50919370Spst    instanceKlassHandle this_k(THREAD, this);
51019370Spst    initialize_impl(this_k, CHECK);
51119370Spst    // Note: at this point the class may be initialized
51219370Spst    //       OR it may be in the state of being initialized
51319370Spst    //       in case of recursive initialization!
51419370Spst  } else {
51519370Spst    assert(is_initialized(), "sanity check");
51619370Spst  }
51719370Spst}
51819370Spst
51919370Spst
52019370Spstbool InstanceKlass::verify_code(
52119370Spst    instanceKlassHandle this_k, bool throw_verifyerror, TRAPS) {
52219370Spst  // 1) Verify the bytecodes
52319370Spst  Verifier::Mode mode =
52419370Spst    throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
52519370Spst  return Verifier::verify(this_k, mode, this_k->should_verify_class(), THREAD);
52619370Spst}
52798948Sobrien
52819370Spst
52998948Sobrien// Used exclusively by the shared spaces dump mechanism to prevent
53019370Spst// classes mapped into the shared regions in new VMs from appearing linked.
53119370Spst
53246289Sdfrvoid InstanceKlass::unlink_class() {
53319370Spst  assert(is_linked(), "must be linked");
53419370Spst  _init_state = loaded;
53519370Spst}
53619370Spst
53719370Spstvoid InstanceKlass::link_class(TRAPS) {
53819370Spst  assert(is_loaded(), "must be loaded");
53919370Spst  if (!is_linked()) {
54019370Spst    HandleMark hm(THREAD);
54119370Spst    instanceKlassHandle this_k(THREAD, this);
54219370Spst    link_class_impl(this_k, true, CHECK);
54319370Spst  }
54419370Spst}
54519370Spst
54619370Spst// Called to verify that a class can link during initialization, without
54719370Spst// throwing a VerifyError.
54819370Spstbool InstanceKlass::link_class_or_fail(TRAPS) {
54919370Spst  assert(is_loaded(), "must be loaded");
55019370Spst  if (!is_linked()) {
55119370Spst    HandleMark hm(THREAD);
55219370Spst    instanceKlassHandle this_k(THREAD, this);
55319370Spst    link_class_impl(this_k, false, CHECK_false);
55419370Spst  }
55519370Spst  return is_linked();
55619370Spst}
55719370Spst
55819370Spstbool InstanceKlass::link_class_impl(
55919370Spst    instanceKlassHandle this_k, bool throw_verifyerror, TRAPS) {
56019370Spst  // check for error state
56119370Spst  if (this_k->is_in_error_state()) {
56219370Spst    ResourceMark rm(THREAD);
56319370Spst    THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
56419370Spst               this_k->external_name(), false);
56519370Spst  }
56619370Spst  // return if already verified
56719370Spst  if (this_k->is_linked()) {
56819370Spst    return true;
56919370Spst  }
57019370Spst
57119370Spst  // Timing
57219370Spst  // timer handles recursion
57319370Spst  assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
57419370Spst  JavaThread* jt = (JavaThread*)THREAD;
57519370Spst
57619370Spst  // link super class before linking this class
57719370Spst  instanceKlassHandle super(THREAD, this_k->super());
57819370Spst  if (super.not_null()) {
57998948Sobrien    if (super->is_interface()) {  // check if super class is an interface
58019370Spst      ResourceMark rm(THREAD);
58119370Spst      Exceptions::fthrow(
58219370Spst        THREAD_AND_LOCATION,
58319370Spst        vmSymbols::java_lang_IncompatibleClassChangeError(),
58419370Spst        "class %s has interface %s as super class",
58519370Spst        this_k->external_name(),
58619370Spst        super->external_name()
58719370Spst      );
58819370Spst      return false;
58919370Spst    }
59019370Spst
59119370Spst    link_class_impl(super, throw_verifyerror, CHECK_false);
59219370Spst  }
59319370Spst
59419370Spst  // link all interfaces implemented by this class before linking this class
59519370Spst  Array<Klass*>* interfaces = this_k->local_interfaces();
59619370Spst  int num_interfaces = interfaces->length();
59719370Spst  for (int index = 0; index < num_interfaces; index++) {
59819370Spst    HandleMark hm(THREAD);
59919370Spst    instanceKlassHandle ih(THREAD, interfaces->at(index));
60019370Spst    link_class_impl(ih, throw_verifyerror, CHECK_false);
60119370Spst  }
60219370Spst
60319370Spst  // in case the class is linked in the process of linking its superclasses
60419370Spst  if (this_k->is_linked()) {
60519370Spst    return true;
60619370Spst  }
60719370Spst
60819370Spst  // trace only the link time for this klass that includes
60919370Spst  // the verification time
61019370Spst  PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
61119370Spst                             ClassLoader::perf_class_link_selftime(),
61219370Spst                             ClassLoader::perf_classes_linked(),
61319370Spst                             jt->get_thread_stat()->perf_recursion_counts_addr(),
61419370Spst                             jt->get_thread_stat()->perf_timers_addr(),
61519370Spst                             PerfClassTraceTime::CLASS_LINK);
61619370Spst
61719370Spst  // verification & rewriting
61819370Spst  {
61998948Sobrien    oop init_lock = this_k->init_lock();
62019370Spst    ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
62119370Spst    // rewritten will have been set if loader constraint error found
62219370Spst    // on an earlier link attempt
62319370Spst    // don't verify or rewrite if already rewritten
62419370Spst
62519370Spst    if (!this_k->is_linked()) {
62619370Spst      if (!this_k->is_rewritten()) {
62719370Spst        {
62819370Spst          bool verify_ok = verify_code(this_k, throw_verifyerror, THREAD);
62919370Spst          if (!verify_ok) {
63019370Spst            return false;
63119370Spst          }
63219370Spst        }
63319370Spst
63419370Spst        // Just in case a side-effect of verify linked this class already
63519370Spst        // (which can sometimes happen since the verifier loads classes
63619370Spst        // using custom class loaders, which are free to initialize things)
63719370Spst        if (this_k->is_linked()) {
63819370Spst          return true;
63919370Spst        }
64019370Spst
64119370Spst        // also sets rewritten
64219370Spst        this_k->rewrite_class(CHECK_false);
64319370Spst      }
64419370Spst
64519370Spst      // relocate jsrs and link methods after they are all rewritten
64619370Spst      this_k->link_methods(CHECK_false);
64719370Spst
64819370Spst      // Initialize the vtable and interface table after
64919370Spst      // methods have been rewritten since rewrite may
65019370Spst      // fabricate new Method*s.
65119370Spst      // also does loader constraint checking
65219370Spst      if (!this_k()->is_shared()) {
65319370Spst        ResourceMark rm(THREAD);
65419370Spst        this_k->vtable()->initialize_vtable(true, CHECK_false);
65519370Spst        this_k->itable()->initialize_itable(true, CHECK_false);
65619370Spst      }
65719370Spst#ifdef ASSERT
65819370Spst      else {
65919370Spst        ResourceMark rm(THREAD);
66019370Spst        this_k->vtable()->verify(tty, true);
66119370Spst        // In case itable verification is ever added.
66219370Spst        // this_k->itable()->verify(tty, true);
66319370Spst      }
66419370Spst#endif
66519370Spst      this_k->set_init_state(linked);
66619370Spst      if (JvmtiExport::should_post_class_prepare()) {
66719370Spst        Thread *thread = THREAD;
66819370Spst        assert(thread->is_Java_thread(), "thread->is_Java_thread()");
66919370Spst        JvmtiExport::post_class_prepare((JavaThread *) thread, this_k());
67019370Spst      }
67119370Spst    }
67219370Spst  }
67319370Spst  return true;
67419370Spst}
67519370Spst
67619370Spst
67719370Spst// Rewrite the byte codes of all of the methods of a class.
67819370Spst// The rewriter must be called exactly once. Rewriting must happen after
67919370Spst// verification but before the first method of the class is executed.
68019370Spstvoid InstanceKlass::rewrite_class(TRAPS) {
68119370Spst  assert(is_loaded(), "must be loaded");
68219370Spst  instanceKlassHandle this_k(THREAD, this);
68319370Spst  if (this_k->is_rewritten()) {
68419370Spst    assert(this_k()->is_shared(), "rewriting an unshared class?");
68519370Spst    return;
68619370Spst  }
68719370Spst  Rewriter::rewrite(this_k, CHECK);
68819370Spst  this_k->set_rewritten();
68919370Spst}
69019370Spst
69119370Spst// Now relocate and link method entry points after class is rewritten.
69219370Spst// This is outside is_rewritten flag. In case of an exception, it can be
69319370Spst// executed more than once.
69419370Spstvoid InstanceKlass::link_methods(TRAPS) {
69519370Spst  int len = methods()->length();
69619370Spst  for (int i = len-1; i >= 0; i--) {
69719370Spst    methodHandle m(THREAD, methods()->at(i));
69819370Spst
69919370Spst    // Set up method entry points for compiler and interpreter    .
70019370Spst    m->link_method(m, CHECK);
70119370Spst  }
70219370Spst}
70319370Spst
70419370Spst// Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
70519370Spstvoid InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_k, TRAPS) {
70619370Spst  if (this_k->has_default_methods()) {
70719370Spst    for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {
70819370Spst      Klass* iface = this_k->local_interfaces()->at(i);
70919370Spst      InstanceKlass* ik = InstanceKlass::cast(iface);
71019370Spst      if (ik->should_be_initialized()) {
71119370Spst        if (ik->has_default_methods()) {
71219370Spst          ik->initialize_super_interfaces(ik, THREAD);
71319370Spst        }
71419370Spst        // Only initialize() interfaces that "declare" concrete methods.
71519370Spst        // has_default_methods drives searching superinterfaces since it
71619370Spst        // means has_default_methods in its superinterface hierarchy
71719370Spst        if (!HAS_PENDING_EXCEPTION && ik->declares_default_methods()) {
71819370Spst          ik->initialize(THREAD);
71919370Spst        }
72019370Spst        if (HAS_PENDING_EXCEPTION) {
72119370Spst          Handle e(THREAD, PENDING_EXCEPTION);
72219370Spst          CLEAR_PENDING_EXCEPTION;
72319370Spst          {
72419370Spst            EXCEPTION_MARK;
72519370Spst            // Locks object, set state, and notify all waiting threads
72619370Spst            this_k->set_initialization_state_and_notify(
72719370Spst                initialization_error, THREAD);
72819370Spst
72919370Spst            // ignore any exception thrown, superclass initialization error is
73019370Spst            // thrown below
73119370Spst            CLEAR_PENDING_EXCEPTION;
73219370Spst          }
73319370Spst          THROW_OOP(e());
73419370Spst        }
73519370Spst      }
73619370Spst    }
73719370Spst  }
73819370Spst}
73919370Spst
74019370Spstvoid InstanceKlass::initialize_impl(instanceKlassHandle this_k, TRAPS) {
74119370Spst  // Make sure klass is linked (verified) before initialization
74219370Spst  // A class could already be verified, since it has been reflected upon.
74319370Spst  this_k->link_class(CHECK);
74419370Spst
74598948Sobrien  DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_k()), -1);
74619370Spst
74719370Spst  bool wait = false;
74819370Spst
74998948Sobrien  // refer to the JVM book page 47 for description of steps
75019370Spst  // Step 1
75198948Sobrien  {
75298948Sobrien    oop init_lock = this_k->init_lock();
75398948Sobrien    ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
75419370Spst
75519370Spst    Thread *self = THREAD; // it's passed the current thread
75619370Spst
75719370Spst    // Step 2
75819370Spst    // If we were to use wait() instead of waitInterruptibly() then
75946289Sdfr    // we might end up throwing IE from link/symbol resolution sites
76019370Spst    // that aren't expected to throw.  This would wreak havoc.  See 6320309.
761130809Smarcel    while(this_k->is_being_initialized() && !this_k->is_reentrant_initialization(self)) {
76219370Spst        wait = true;
76319370Spst      ol.waitUninterruptibly(CHECK);
76498948Sobrien    }
76519370Spst
76619370Spst    // Step 3
76719370Spst    if (this_k->is_being_initialized() && this_k->is_reentrant_initialization(self)) {
76819370Spst      DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_k()), -1,wait);
76919370Spst      return;
77019370Spst    }
77119370Spst
77219370Spst    // Step 4
77319370Spst    if (this_k->is_initialized()) {
77419370Spst      DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_k()), -1,wait);
77598948Sobrien      return;
77619370Spst    }
77719370Spst
77819370Spst    // Step 5
77919370Spst    if (this_k->is_in_error_state()) {
780130809Smarcel      DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_k()), -1,wait);
78119370Spst      ResourceMark rm(THREAD);
782130809Smarcel      const char* desc = "Could not initialize class ";
78319370Spst      const char* className = this_k->external_name();
78419370Spst      size_t msglen = strlen(desc) + strlen(className) + 1;
78519370Spst      char* message = NEW_RESOURCE_ARRAY(char, msglen);
78619370Spst      if (NULL == message) {
78719370Spst        // Out of memory: can't create detailed error message
788130809Smarcel        THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
78919370Spst      } else {
790130809Smarcel        jio_snprintf(message, msglen, "%s%s", desc, className);
79119370Spst        THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
79219370Spst      }
79319370Spst    }
79419370Spst
795130809Smarcel    // Step 6
79619370Spst    this_k->set_init_state(being_initialized);
797130809Smarcel    this_k->set_init_thread(self);
79819370Spst  }
79919370Spst
80019370Spst  // Step 7
80119370Spst  Klass* super_klass = this_k->super();
80219370Spst  if (super_klass != NULL && !this_k->is_interface() && super_klass->should_be_initialized()) {
80319370Spst    super_klass->initialize(THREAD);
80498948Sobrien
80598948Sobrien    if (HAS_PENDING_EXCEPTION) {
80698948Sobrien      Handle e(THREAD, PENDING_EXCEPTION);
80798948Sobrien      CLEAR_PENDING_EXCEPTION;
80819370Spst      {
80998948Sobrien        EXCEPTION_MARK;
81098948Sobrien        this_k->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
81198948Sobrien        CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
812130809Smarcel      }
81398948Sobrien      DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_k()), -1,wait);
814130809Smarcel      THROW_OOP(e());
81598948Sobrien    }
81698948Sobrien  }
81798948Sobrien
81898948Sobrien  // Recursively initialize any superinterfaces that declare default methods
81919370Spst  // Only need to recurse if has_default_methods which includes declaring and
82019370Spst  // inheriting default methods
82119370Spst  if (this_k->has_default_methods()) {
82246289Sdfr    this_k->initialize_super_interfaces(this_k, CHECK);
82319370Spst  }
82419370Spst
82519370Spst  // Step 8
82619370Spst  {
82719370Spst    assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
82819370Spst    JavaThread* jt = (JavaThread*)THREAD;
82919370Spst    DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_k()), -1,wait);
83019370Spst    // Timer includes any side effects of class initialization (resolution,
83119370Spst    // etc), but not recursive entry into call_class_initializer().
832130809Smarcel    PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
83319370Spst                             ClassLoader::perf_class_init_selftime(),
834130809Smarcel                             ClassLoader::perf_classes_inited(),
83519370Spst                             jt->get_thread_stat()->perf_recursion_counts_addr(),
83619370Spst                             jt->get_thread_stat()->perf_timers_addr(),
83719370Spst                             PerfClassTraceTime::CLASS_CLINIT);
83819370Spst    this_k->call_class_initializer(THREAD);
83919370Spst  }
84019370Spst
84119370Spst  // Step 9
84219370Spst  if (!HAS_PENDING_EXCEPTION) {
84319370Spst    this_k->set_initialization_state_and_notify(fully_initialized, CHECK);
84419370Spst    { ResourceMark rm(THREAD);
84519370Spst      debug_only(this_k->vtable()->verify(tty, true);)
84619370Spst    }
84719370Spst  }
84819370Spst  else {
84919370Spst    // Step 10 and 11
85019370Spst    Handle e(THREAD, PENDING_EXCEPTION);
85119370Spst    CLEAR_PENDING_EXCEPTION;
85219370Spst    // JVMTI has already reported the pending exception
85319370Spst    // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
85419370Spst    JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
85519370Spst    {
85698948Sobrien      EXCEPTION_MARK;
85798948Sobrien      this_k->set_initialization_state_and_notify(initialization_error, THREAD);
85898948Sobrien      CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
85998948Sobrien      // JVMTI has already reported the pending exception
86098948Sobrien      // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
86198948Sobrien      JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
86298948Sobrien    }
86398948Sobrien    DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_k()), -1,wait);
864130809Smarcel    if (e->is_a(SystemDictionary::Error_klass())) {
86598948Sobrien      THROW_OOP(e());
86619370Spst    } else {
86798948Sobrien      JavaCallArguments args(e);
86898948Sobrien      THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
86998948Sobrien                vmSymbols::throwable_void_signature(),
87098948Sobrien                &args);
87119370Spst    }
87219370Spst  }
87319370Spst  DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_k()), -1,wait);
87419370Spst}
87519370Spst
87619370Spst
87798948Sobrien// Note: implementation moved to static method to expose the this pointer.
87898948Sobrienvoid InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
87998948Sobrien  instanceKlassHandle kh(THREAD, this);
88098948Sobrien  set_initialization_state_and_notify_impl(kh, state, CHECK);
88119370Spst}
88219370Spst
88319370Spstvoid InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_k, ClassState state, TRAPS) {
88498948Sobrien  oop init_lock = this_k->init_lock();
88598948Sobrien  ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
88619370Spst  this_k->set_init_state(state);
88719370Spst  this_k->fence_and_clear_init_lock();
88819370Spst  ol.notify_all(CHECK);
88919370Spst}
89098948Sobrien
89198948Sobrien// The embedded _implementor field can only record one implementor.
89298948Sobrien// When there are more than one implementors, the _implementor field
89398948Sobrien// is set to the interface Klass* itself. Following are the possible
89419370Spst// values for the _implementor field:
89519370Spst//   NULL                  - no implementor
89698948Sobrien//   implementor Klass*    - one implementor
89719370Spst//   self                  - more than one implementor
89819370Spst//
89919370Spst// The _implementor field only exists for interfaces.
90019370Spstvoid InstanceKlass::add_implementor(Klass* k) {
90119370Spst  assert(Compile_lock->owned_by_self(), "");
90298948Sobrien  assert(is_interface(), "not interface");
90398948Sobrien  // Filter out my subinterfaces.
904130809Smarcel  // (Note: Interfaces are never on the subklass list.)
90519370Spst  if (InstanceKlass::cast(k)->is_interface()) return;
90619370Spst
90798948Sobrien  // Filter out subclasses whose supers already implement me.
90898948Sobrien  // (Note: CHA must walk subclasses of direct implementors
90998948Sobrien  // in order to locate indirect implementors.)
91098948Sobrien  Klass* sk = InstanceKlass::cast(k)->super();
91198948Sobrien  if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
91298948Sobrien    // We only need to check one immediate superclass, since the
91398948Sobrien    // implements_interface query looks at transitive_interfaces.
91419370Spst    // Any supers of the super have the same (or fewer) transitive_interfaces.
91519370Spst    return;
91619370Spst
91798948Sobrien  Klass* ik = implementor();
91898948Sobrien  if (ik == NULL) {
91919370Spst    set_implementor(k);
92019370Spst  } else if (ik != this) {
92119370Spst    // There is already an implementor. Use itself as an indicator of
92219370Spst    // more than one implementors.
92319370Spst    set_implementor(this);
92498948Sobrien  }
92598948Sobrien
92619370Spst  // The implementor also implements the transitive_interfaces
92719370Spst  for (int index = 0; index < local_interfaces()->length(); index++) {
92819370Spst    InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
92919370Spst  }
93098948Sobrien}
93198948Sobrien
93219370Spstvoid InstanceKlass::init_implementor() {
93319370Spst  if (is_interface()) {
93419370Spst    set_implementor(NULL);
93598948Sobrien  }
93619370Spst}
93719370Spst
93898948Sobrien
93919370Spstvoid InstanceKlass::process_interfaces(Thread *thread) {
94019370Spst  // link this class into the implementors list of every interface it implements
94119370Spst  for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
94219370Spst    assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
94319370Spst    InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
94419370Spst    assert(interf->is_interface(), "expected interface");
94519370Spst    interf->add_implementor(this);
94619370Spst  }
94719370Spst}
94819370Spst
94998948Sobrienbool InstanceKlass::can_be_primary_super_slow() const {
95098948Sobrien  if (is_interface())
95119370Spst    return false;
95219370Spst  else
95319370Spst    return Klass::can_be_primary_super_slow();
95498948Sobrien}
95519370Spst
95619370SpstGrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
95798948Sobrien  // The secondaries are the implemented interfaces.
95819370Spst  InstanceKlass* ik = InstanceKlass::cast(this);
95998948Sobrien  Array<Klass*>* interfaces = ik->transitive_interfaces();
96098948Sobrien  int num_secondaries = num_extra_slots + interfaces->length();
96198948Sobrien  if (num_secondaries == 0) {
96219370Spst    // Must share this for correct bootstrapping!
963130809Smarcel    set_secondary_supers(Universe::the_empty_klass_array());
96498948Sobrien    return NULL;
965130809Smarcel  } else if (num_extra_slots == 0) {
96619370Spst    // The secondary super list is exactly the same as the transitive interfaces.
96798948Sobrien    // Redefine classes has to be careful not to delete this!
96819370Spst    set_secondary_supers(interfaces);
96919370Spst    return NULL;
97019370Spst  } else {
97119370Spst    // Copy transitive interfaces to a temporary growable array to be constructed
97219370Spst    // into the secondary super list with extra slots.
97319370Spst    GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
97419370Spst    for (int i = 0; i < interfaces->length(); i++) {
97519370Spst      secondaries->push(interfaces->at(i));
97698948Sobrien    }
97798948Sobrien    return secondaries;
97898948Sobrien  }
97998948Sobrien}
98098948Sobrien
98198948Sobrienbool InstanceKlass::compute_is_subtype_of(Klass* k) {
98219370Spst  if (k->is_interface()) {
98319370Spst    return implements_interface(k);
98498948Sobrien  } else {
98519370Spst    return Klass::compute_is_subtype_of(k);
98698948Sobrien  }
98798948Sobrien}
98898948Sobrien
98919370Spstbool InstanceKlass::implements_interface(Klass* k) const {
99019370Spst  if (this == k) return true;
99119370Spst  assert(k->is_interface(), "should be an interface class");
99219370Spst  for (int i = 0; i < transitive_interfaces()->length(); i++) {
99398948Sobrien    if (transitive_interfaces()->at(i) == k) {
99419370Spst      return true;
99519370Spst    }
99619370Spst  }
99719370Spst  return false;
99819370Spst}
99919370Spst
100098948Sobrienbool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
100198948Sobrien  // Verify direct super interface
100298948Sobrien  if (this == k) return true;
100319370Spst  assert(k->is_interface(), "should be an interface class");
1004130809Smarcel  for (int i = 0; i < local_interfaces()->length(); i++) {
100519370Spst    if (local_interfaces()->at(i) == k) {
1006130809Smarcel      return true;
100719370Spst    }
100819370Spst  }
100998948Sobrien  return false;
101098948Sobrien}
101198948Sobrien
101219370SpstobjArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
101398948Sobrien  if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
101498948Sobrien  if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
101598948Sobrien    report_java_out_of_memory("Requested array size exceeds VM limit");
101698948Sobrien    JvmtiExport::post_array_size_exhausted();
101798948Sobrien    THROW_OOP_0(Universe::out_of_memory_error_array_size());
101898948Sobrien  }
101998948Sobrien  int size = objArrayOopDesc::object_size(length);
102098948Sobrien  Klass* ak = array_klass(n, CHECK_NULL);
102198948Sobrien  KlassHandle h_ak (THREAD, ak);
102298948Sobrien  objArrayOop o =
102398948Sobrien    (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
102498948Sobrien  return o;
102598948Sobrien}
102698948Sobrien
102798948SobrieninstanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
102819370Spst  if (TraceFinalizerRegistration) {
102998948Sobrien    tty->print("Registered ");
103019370Spst    i->print_value_on(tty);
103119370Spst    tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", p2i(i));
103219370Spst  }
103319370Spst  instanceHandle h_i(THREAD, i);
103419370Spst  // Pass the handle as argument, JavaCalls::call expects oop as jobjects
103598948Sobrien  JavaValue result(T_VOID);
103698948Sobrien  JavaCallArguments args(h_i);
103798948Sobrien  methodHandle mh (THREAD, Universe::finalizer_register_method());
103898948Sobrien  JavaCalls::call(&result, mh, &args, CHECK_NULL);
103998948Sobrien  return h_i();
104098948Sobrien}
104198948Sobrien
104298948SobrieninstanceOop InstanceKlass::allocate_instance(TRAPS) {
104398948Sobrien  bool has_finalizer_flag = has_finalizer(); // Query before possible GC
104498948Sobrien  int size = size_helper();  // Query before forming handle.
104598948Sobrien
104619370Spst  KlassHandle h_k(THREAD, this);
104798948Sobrien
104898948Sobrien  instanceOop i;
104998948Sobrien
105098948Sobrien  i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
105198948Sobrien  if (has_finalizer_flag && !RegisterFinalizersAtInit) {
105298948Sobrien    i = register_finalizer(i, CHECK_NULL);
105398948Sobrien  }
105498948Sobrien  return i;
105598948Sobrien}
105698948Sobrien
105798948Sobrienvoid InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1058130809Smarcel  if (is_interface() || is_abstract()) {
1059130809Smarcel    ResourceMark rm(THREAD);
1060130809Smarcel    THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1061130809Smarcel              : vmSymbols::java_lang_InstantiationException(), external_name());
1062130809Smarcel  }
1063130809Smarcel  if (this == SystemDictionary::Class_klass()) {
106498948Sobrien    ResourceMark rm(THREAD);
1065130809Smarcel    THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1066130809Smarcel              : vmSymbols::java_lang_IllegalAccessException(), external_name());
1067130809Smarcel  }
106898948Sobrien}
106998948Sobrien
107098948SobrienKlass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
107198948Sobrien  instanceKlassHandle this_k(THREAD, this);
107298948Sobrien  return array_klass_impl(this_k, or_null, n, THREAD);
107398948Sobrien}
107498948Sobrien
107598948SobrienKlass* InstanceKlass::array_klass_impl(instanceKlassHandle this_k, bool or_null, int n, TRAPS) {
107698948Sobrien  if (this_k->array_klasses() == NULL) {
107798948Sobrien    if (or_null) return NULL;
107898948Sobrien
107998948Sobrien    ResourceMark rm;
108098948Sobrien    JavaThread *jt = (JavaThread *)THREAD;
108198948Sobrien    {
108298948Sobrien      // Atomic creation of array_klasses
108398948Sobrien      MutexLocker mc(Compile_lock, THREAD);   // for vtables
108498948Sobrien      MutexLocker ma(MultiArray_lock, THREAD);
108598948Sobrien
108698948Sobrien      // Check if update has already taken place
108798948Sobrien      if (this_k->array_klasses() == NULL) {
108898948Sobrien        Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_k->class_loader_data(), 1, this_k, CHECK_NULL);
108998948Sobrien        this_k->set_array_klasses(k);
109098948Sobrien      }
109198948Sobrien    }
109298948Sobrien  }
109398948Sobrien  // _this will always be set at this point
109498948Sobrien  ObjArrayKlass* oak = (ObjArrayKlass*)this_k->array_klasses();
109598948Sobrien  if (or_null) {
109698948Sobrien    return oak->array_klass_or_null(n);
109798948Sobrien  }
109898948Sobrien  return oak->array_klass(n, THREAD);
109998948Sobrien}
110098948Sobrien
110198948SobrienKlass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
110219370Spst  return array_klass_impl(or_null, 1, THREAD);
110319370Spst}
110419370Spst
110519370Spstvoid InstanceKlass::call_class_initializer(TRAPS) {
110698948Sobrien  instanceKlassHandle ik (THREAD, this);
110798948Sobrien  call_class_initializer_impl(ik, THREAD);
110898948Sobrien}
110919370Spst
111019370Spststatic int call_class_initializer_impl_counter = 0;   // for debugging
111146289Sdfr
111298948SobrienMethod* InstanceKlass::class_initializer() {
111346289Sdfr  Method* clinit = find_method(
111498948Sobrien      vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1115130809Smarcel  if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1116130809Smarcel    return clinit;
1117130809Smarcel  }
1118130809Smarcel  return NULL;
1119130809Smarcel}
1120130809Smarcel
1121130809Smarcelvoid InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_k, TRAPS) {
112246289Sdfr  if (ReplayCompiles &&
112398948Sobrien      (ReplaySuppressInitializers == 1 ||
112498948Sobrien       ReplaySuppressInitializers >= 2 && this_k->class_loader() != NULL)) {
112598948Sobrien    // Hide the existence of the initializer for the purpose of replaying the compile
112698948Sobrien    return;
112798948Sobrien  }
112898948Sobrien
112998948Sobrien  methodHandle h_method(THREAD, this_k->class_initializer());
113098948Sobrien  assert(!this_k->is_initialized(), "we cannot initialize twice");
113198948Sobrien  if (TraceClassInitialization) {
113298948Sobrien    tty->print("%d Initializing ", call_class_initializer_impl_counter++);
113398948Sobrien    this_k->name()->print_value();
113498948Sobrien    tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", p2i(this_k()));
1135130809Smarcel  }
113698948Sobrien  if (h_method() != NULL) {
1137130809Smarcel    JavaCallArguments args; // No arguments
1138130809Smarcel    JavaValue result(T_VOID);
1139130809Smarcel    JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1140130809Smarcel  }
1141130809Smarcel}
1142130809Smarcel
114398948Sobrien
114498948Sobrienvoid InstanceKlass::mask_for(const methodHandle& method, int bci,
114598948Sobrien  InterpreterOopMap* entry_for) {
114698948Sobrien  // Dirty read, then double-check under a lock.
114798948Sobrien  if (_oop_map_cache == NULL) {
114898948Sobrien    // Otherwise, allocate a new one.
114998948Sobrien    MutexLocker x(OopMapCacheAlloc_lock);
115098948Sobrien    // First time use. Allocate a cache in C heap
115198948Sobrien    if (_oop_map_cache == NULL) {
115298948Sobrien      // Release stores from OopMapCache constructor before assignment
115398948Sobrien      // to _oop_map_cache. C++ compilers on ppc do not emit the
115498948Sobrien      // required memory barrier only because of the volatile
115598948Sobrien      // qualifier of _oop_map_cache.
115698948Sobrien      OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());
115798948Sobrien    }
115898948Sobrien  }
115998948Sobrien  // _oop_map_cache is constant after init; lookup below does is own locking.
116019370Spst  _oop_map_cache->lookup(method, bci, entry_for);
116119370Spst}
116298948Sobrien
116319370Spst
116419370Spstbool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
116519370Spst  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
116619370Spst    Symbol* f_name = fs.name();
116719370Spst    Symbol* f_sig  = fs.signature();
116819370Spst    if (f_name == name && f_sig == sig) {
116998948Sobrien      fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
117098948Sobrien      return true;
117198948Sobrien    }
117298948Sobrien  }
117398948Sobrien  return false;
117498948Sobrien}
117598948Sobrien
117698948Sobrien
117719370SpstKlass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
117819370Spst  const int n = local_interfaces()->length();
117919370Spst  for (int i = 0; i < n; i++) {
118019370Spst    Klass* intf1 = local_interfaces()->at(i);
118119370Spst    assert(intf1->is_interface(), "just checking type");
118219370Spst    // search for field in current interface
118319370Spst    if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
118419370Spst      assert(fd->is_static(), "interface field must be static");
118519370Spst      return intf1;
118619370Spst    }
118719370Spst    // search for field in direct superinterfaces
118819370Spst    Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
118919370Spst    if (intf2 != NULL) return intf2;
119098948Sobrien  }
119119370Spst  // otherwise field lookup fails
119219370Spst  return NULL;
119319370Spst}
119419370Spst
119519370Spst
119619370SpstKlass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
119719370Spst  // search order according to newest JVM spec (5.4.3.2, p.167).
119819370Spst  // 1) search for field in current klass
119919370Spst  if (find_local_field(name, sig, fd)) {
120019370Spst    return const_cast<InstanceKlass*>(this);
120146289Sdfr  }
120219370Spst  // 2) search for field recursively in direct superinterfaces
120398948Sobrien  { Klass* intf = find_interface_field(name, sig, fd);
120498948Sobrien    if (intf != NULL) return intf;
120519370Spst  }
120619370Spst  // 3) apply field lookup recursively if superclass exists
120719370Spst  { Klass* supr = super();
120819370Spst    if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
120919370Spst  }
121019370Spst  // 4) otherwise field lookup fails
121119370Spst  return NULL;
121219370Spst}
121319370Spst
121419370Spst
121519370SpstKlass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
121619370Spst  // search order according to newest JVM spec (5.4.3.2, p.167).
121719370Spst  // 1) search for field in current klass
121819370Spst  if (find_local_field(name, sig, fd)) {
1219130809Smarcel    if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1220130809Smarcel  }
1221130809Smarcel  // 2) search for field recursively in direct superinterfaces
1222130809Smarcel  if (is_static) {
1223130809Smarcel    Klass* intf = find_interface_field(name, sig, fd);
1224130809Smarcel    if (intf != NULL) return intf;
1225130809Smarcel  }
1226130809Smarcel  // 3) apply field lookup recursively if superclass exists
1227130809Smarcel  { Klass* supr = super();
1228130809Smarcel    if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1229130809Smarcel  }
1230130809Smarcel  // 4) otherwise field lookup fails
1231130809Smarcel  return NULL;
1232130809Smarcel}
1233130809Smarcel
1234130809Smarcel
1235130809Smarcelbool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1236130809Smarcel  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1237130809Smarcel    if (fs.offset() == offset) {
1238130809Smarcel      fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1239130809Smarcel      if (fd->is_static() == is_static) return true;
1240130809Smarcel    }
1241130809Smarcel  }
1242130809Smarcel  return false;
1243130809Smarcel}
1244130809Smarcel
124598948Sobrien
124619370Spstbool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
124719370Spst  Klass* klass = const_cast<InstanceKlass*>(this);
124819370Spst  while (klass != NULL) {
124919370Spst    if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
125019370Spst      return true;
125119370Spst    }
125219370Spst    klass = klass->super();
125319370Spst  }
125419370Spst  return false;
125519370Spst}
125619370Spst
125719370Spst
125819370Spstvoid InstanceKlass::methods_do(void f(Method* method)) {
125919370Spst  // Methods aren't stable until they are loaded.  This can be read outside
126098948Sobrien  // a lock through the ClassLoaderData for profiling
126119370Spst  if (!is_loaded()) {
126219370Spst    return;
126319370Spst  }
126419370Spst
126519370Spst  int len = methods()->length();
126619370Spst  for (int index = 0; index < len; index++) {
126719370Spst    Method* m = methods()->at(index);
126898948Sobrien    assert(m->is_method(), "must be method");
126919370Spst    f(m);
127019370Spst  }
127119370Spst}
127219370Spst
127319370Spst
127419370Spstvoid InstanceKlass::do_local_static_fields(FieldClosure* cl) {
127519370Spst  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
127619370Spst    if (fs.access_flags().is_static()) {
127719370Spst      fieldDescriptor& fd = fs.field_descriptor();
127819370Spst      cl->do_field(&fd);
127919370Spst    }
128098948Sobrien  }
128119370Spst}
128298948Sobrien
128319370Spst
128419370Spstvoid InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
128519370Spst  instanceKlassHandle h_this(THREAD, this);
128619370Spst  do_local_static_fields_impl(h_this, f, mirror, CHECK);
128719370Spst}
128819370Spst
128919370Spst
129019370Spstvoid InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,
129119370Spst                             void f(fieldDescriptor* fd, Handle, TRAPS), Handle mirror, TRAPS) {
129219370Spst  for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {
129319370Spst    if (fs.access_flags().is_static()) {
129419370Spst      fieldDescriptor& fd = fs.field_descriptor();
129519370Spst      f(&fd, mirror, CHECK);
129619370Spst    }
129798948Sobrien  }
129819370Spst}
129919370Spst
130019370Spst
130119370Spststatic int compare_fields_by_offset(int* a, int* b) {
130219370Spst  return a[0] - b[0];
130398948Sobrien}
130498948Sobrien
130598948Sobrienvoid InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
130698948Sobrien  InstanceKlass* super = superklass();
130798948Sobrien  if (super != NULL) {
130898948Sobrien    super->do_nonstatic_fields(cl);
130998948Sobrien  }
131098948Sobrien  fieldDescriptor fd;
131119370Spst  int length = java_fields_count();
131219370Spst  // In DebugInfo nonstatic fields are sorted by offset.
131319370Spst  int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
131419370Spst  int j = 0;
131519370Spst  for (int i = 0; i < length; i += 1) {
131619370Spst    fd.reinitialize(this, i);
131719370Spst    if (!fd.is_static()) {
131819370Spst      fields_sorted[j + 0] = fd.offset();
131919370Spst      fields_sorted[j + 1] = i;
132019370Spst      j += 2;
132119370Spst    }
132219370Spst  }
132319370Spst  if (j > 0) {
132419370Spst    length = j;
132519370Spst    // _sort_Fn is defined in growableArray.hpp.
132619370Spst    qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
132719370Spst    for (int i = 0; i < length; i += 2) {
132819370Spst      fd.reinitialize(this, fields_sorted[i + 1]);
1329130809Smarcel      assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
133019370Spst      cl->do_field(&fd);
1331130809Smarcel    }
133219370Spst  }
133319370Spst  FREE_C_HEAP_ARRAY(int, fields_sorted);
133419370Spst}
133519370Spst
133619370Spst
1337130809Smarcelvoid InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
133819370Spst  if (array_klasses() != NULL)
1339130809Smarcel    ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
134019370Spst}
134119370Spst
134219370Spstvoid InstanceKlass::array_klasses_do(void f(Klass* k)) {
134319370Spst  if (array_klasses() != NULL)
134419370Spst    ArrayKlass::cast(array_klasses())->array_klasses_do(f);
134519370Spst}
134619370Spst
134719370Spst#ifdef ASSERT
134819370Spststatic int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
134919370Spst  int len = methods->length();
135019370Spst  for (int index = 0; index < len; index++) {
135119370Spst    Method* m = methods->at(index);
135219370Spst    assert(m->is_method(), "must be method");
135319370Spst    if (m->signature() == signature && m->name() == name) {
135419370Spst       return index;
135519370Spst    }
135619370Spst  }
135719370Spst  return -1;
135819370Spst}
1359130809Smarcel#endif
136019370Spst
136119370Spststatic int binary_search(Array<Method*>* methods, Symbol* name) {
136298948Sobrien  int len = methods->length();
136398948Sobrien  // methods are sorted, so do binary search
136498948Sobrien  int l = 0;
136598948Sobrien  int h = len - 1;
136619370Spst  while (l <= h) {
136719370Spst    int mid = (l + h) >> 1;
1368130809Smarcel    Method* m = methods->at(mid);
136919370Spst    assert(m->is_method(), "must be method");
137019370Spst    int res = m->name()->fast_compare(name);
137119370Spst    if (res == 0) {
137219370Spst      return mid;
137319370Spst    } else if (res < 0) {
137419370Spst      l = mid + 1;
137519370Spst    } else {
137698948Sobrien      h = mid - 1;
137798948Sobrien    }
137819370Spst  }
137998948Sobrien  return -1;
138019370Spst}
138119370Spst
138219370Spst// find_method looks up the name/signature in the local methods array
138319370SpstMethod* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
138498948Sobrien  return find_method_impl(name, signature, find_overpass, find_static, find_private);
138598948Sobrien}
138698948Sobrien
138798948SobrienMethod* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature,
138819370Spst                                        OverpassLookupMode overpass_mode,
138919370Spst                                        StaticLookupMode static_mode,
139098948Sobrien                                        PrivateLookupMode private_mode) const {
139198948Sobrien  return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);
139298948Sobrien}
139398948Sobrien
139498948Sobrien// find_instance_method looks up the name/signature in the local methods array
139598948Sobrien// and skips over static methods
139698948SobrienMethod* InstanceKlass::find_instance_method(
139798948Sobrien    Array<Method*>* methods, Symbol* name, Symbol* signature) {
139898948Sobrien  Method* meth = InstanceKlass::find_method_impl(methods, name, signature,
139998948Sobrien                                                 find_overpass, skip_static, find_private);
140019370Spst  assert(((meth == NULL) || !meth->is_static()), "find_instance_method should have skipped statics");
1401130809Smarcel  return meth;
140298948Sobrien}
140319370Spst
140419370Spst// find_instance_method looks up the name/signature in the local methods array
1405130809Smarcel// and skips over static methods
140619370SpstMethod* InstanceKlass::find_instance_method(Symbol* name, Symbol* signature) {
140719370Spst    return InstanceKlass::find_instance_method(methods(), name, signature);
140819370Spst}
140919370Spst
141019370Spst// Find looks up the name/signature in the local methods array
141119370Spst// and filters on the overpass, static and private flags
1412130809Smarcel// This returns the first one found
141319370Spst// note that the local methods array can have up to one overpass, one static
141419370Spst// and one instance (private or not) with the same name/signature
141519370SpstMethod* InstanceKlass::find_local_method(Symbol* name, Symbol* signature,
1416130809Smarcel                                        OverpassLookupMode overpass_mode,
141719370Spst                                        StaticLookupMode static_mode,
141819370Spst                                        PrivateLookupMode private_mode) const {
141919370Spst  return InstanceKlass::find_method_impl(methods(), name, signature, overpass_mode, static_mode, private_mode);
142019370Spst}
142119370Spst
142246289Sdfr// Find looks up the name/signature in the local methods array
142398948Sobrien// and filters on the overpass, static and private flags
142498948Sobrien// This returns the first one found
142546289Sdfr// note that the local methods array can have up to one overpass, one static
142698948Sobrien// and one instance (private or not) with the same name/signature
142719370SpstMethod* InstanceKlass::find_local_method(Array<Method*>* methods,
142819370Spst                                        Symbol* name, Symbol* signature,
142998948Sobrien                                        OverpassLookupMode overpass_mode,
143019370Spst                                        StaticLookupMode static_mode,
143119370Spst                                        PrivateLookupMode private_mode) {
143219370Spst  return InstanceKlass::find_method_impl(methods, name, signature, overpass_mode, static_mode, private_mode);
143319370Spst}
143498948Sobrien
143519370Spst
143619370Spst// find_method looks up the name/signature in the local methods array
143719370SpstMethod* InstanceKlass::find_method(
143898948Sobrien    Array<Method*>* methods, Symbol* name, Symbol* signature) {
143919370Spst  return InstanceKlass::find_method_impl(methods, name, signature, find_overpass, find_static, find_private);
144019370Spst}
144119370Spst
144219370SpstMethod* InstanceKlass::find_method_impl(
144319370Spst    Array<Method*>* methods, Symbol* name, Symbol* signature,
144419370Spst    OverpassLookupMode overpass_mode, StaticLookupMode static_mode,
144519370Spst    PrivateLookupMode private_mode) {
144619370Spst  int hit = find_method_index(methods, name, signature, overpass_mode, static_mode, private_mode);
144719370Spst  return hit >= 0 ? methods->at(hit): NULL;
144898948Sobrien}
144998948Sobrien
145098948Sobrienbool InstanceKlass::method_matches(Method* m, Symbol* signature, bool skipping_overpass, bool skipping_static, bool skipping_private) {
145198948Sobrien    return  ((m->signature() == signature) &&
145298948Sobrien            (!skipping_overpass || !m->is_overpass()) &&
145398948Sobrien            (!skipping_static || !m->is_static()) &&
145419370Spst            (!skipping_private || !m->is_private()));
145519370Spst}
145619370Spst
145719370Spst// Used directly for default_methods to find the index into the
145898948Sobrien// default_vtable_indices, and indirectly by find_method
145998948Sobrien// find_method_index looks in the local methods array to return the index
146019370Spst// of the matching name/signature. If, overpass methods are being ignored,
146119370Spst// the search continues to find a potential non-overpass match.  This capability
146298948Sobrien// is important during method resolution to prefer a static method, for example,
146319370Spst// over an overpass method.
146498948Sobrien// There is the possibility in any _method's array to have the same name/signature
146519370Spst// for a static method, an overpass method and a local instance method
146619370Spst// To correctly catch a given method, the search criteria may need
146719370Spst// to explicitly skip the other two. For local instance methods, it
146819370Spst// is often necessary to skip private methods
146998948Sobrienint InstanceKlass::find_method_index(
147019370Spst    Array<Method*>* methods, Symbol* name, Symbol* signature,
147119370Spst    OverpassLookupMode overpass_mode, StaticLookupMode static_mode,
147219370Spst    PrivateLookupMode private_mode) {
147319370Spst  bool skipping_overpass = (overpass_mode == skip_overpass);
147419370Spst  bool skipping_static = (static_mode == skip_static);
147519370Spst  bool skipping_private = (private_mode == skip_private);
147619370Spst  int hit = binary_search(methods, name);
147719370Spst  if (hit != -1) {
147819370Spst    Method* m = methods->at(hit);
147919370Spst
148019370Spst    // Do linear search to find matching signature.  First, quick check
148119370Spst    // for common case, ignoring overpasses if requested.
148219370Spst    if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return hit;
148319370Spst
148498948Sobrien    // search downwards through overloaded methods
148598948Sobrien    int i;
148698948Sobrien    for (i = hit - 1; i >= 0; --i) {
148798948Sobrien        Method* m = methods->at(i);
148819370Spst        assert(m->is_method(), "must be method");
148998948Sobrien        if (m->name() != name) break;
149019370Spst        if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;
149119370Spst    }
149219370Spst    // search upwards
149319370Spst    for (i = hit + 1; i < methods->length(); ++i) {
149419370Spst        Method* m = methods->at(i);
149519370Spst        assert(m->is_method(), "must be method");
149619370Spst        if (m->name() != name) break;
149719370Spst        if (method_matches(m, signature, skipping_overpass, skipping_static, skipping_private)) return i;
149819370Spst    }
149998948Sobrien    // not found
150098948Sobrien#ifdef ASSERT
150198948Sobrien    int index = (skipping_overpass || skipping_static || skipping_private) ? -1 : linear_search(methods, name, signature);
150298948Sobrien    assert(index == -1, "binary search should have found entry %d", index);
150398948Sobrien#endif
150498948Sobrien  }
150598948Sobrien  return -1;
150698948Sobrien}
150798948Sobrienint InstanceKlass::find_method_by_name(Symbol* name, int* end) {
150898948Sobrien  return find_method_by_name(methods(), name, end);
150998948Sobrien}
151098948Sobrien
151198948Sobrienint InstanceKlass::find_method_by_name(
151298948Sobrien    Array<Method*>* methods, Symbol* name, int* end_ptr) {
151398948Sobrien  assert(end_ptr != NULL, "just checking");
151498948Sobrien  int start = binary_search(methods, name);
151598948Sobrien  int end = start + 1;
151698948Sobrien  if (start != -1) {
151798948Sobrien    while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
151898948Sobrien    while (end < methods->length() && (methods->at(end))->name() == name) ++end;
151998948Sobrien    *end_ptr = end;
152098948Sobrien    return start;
152119370Spst  }
152219370Spst  return -1;
152319370Spst}
152419370Spst
152519370Spst// uncached_lookup_method searches both the local class methods array and all
152619370Spst// superclasses methods arrays, skipping any overpass methods in superclasses.
152719370SpstMethod* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, OverpassLookupMode overpass_mode) const {
152819370Spst  OverpassLookupMode overpass_local_mode = overpass_mode;
152919370Spst  Klass* klass = const_cast<InstanceKlass*>(this);
153019370Spst  while (klass != NULL) {
153119370Spst    Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, overpass_local_mode, find_static, find_private);
153219370Spst    if (method != NULL) {
153319370Spst      return method;
153446289Sdfr    }
153598948Sobrien    klass = InstanceKlass::cast(klass)->super();
153698948Sobrien    overpass_local_mode = skip_overpass;   // Always ignore overpass methods in superclasses
153719370Spst  }
153819370Spst  return NULL;
153946289Sdfr}
154019370Spst
154119370Spst#ifdef ASSERT
154219370Spst// search through class hierarchy and return true if this class or
154319370Spst// one of the superclasses was redefined
154419370Spstbool InstanceKlass::has_redefined_this_or_super() const {
154519370Spst  const InstanceKlass* klass = this;
154619370Spst  while (klass != NULL) {
154719370Spst    if (klass->has_been_redefined()) {
154819370Spst      return true;
154919370Spst    }
155019370Spst    klass = InstanceKlass::cast(klass->super());
155119370Spst  }
155219370Spst  return false;
155319370Spst}
155419370Spst#endif
155598948Sobrien
155619370Spst// lookup a method in the default methods list then in all transitive interfaces
155719370Spst// Do NOT return private or static methods
155819370SpstMethod* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
155919370Spst                                                         Symbol* signature) const {
156019370Spst  Method* m = NULL;
156119370Spst  if (default_methods() != NULL) {
156219370Spst    m = find_method(default_methods(), name, signature);
156319370Spst  }
156419370Spst  // Look up interfaces
156519370Spst  if (m == NULL) {
156698948Sobrien    m = lookup_method_in_all_interfaces(name, signature, find_defaults);
156719370Spst  }
156819370Spst  return m;
156919370Spst}
157019370Spst
157119370Spst// lookup a method in all the interfaces that this class implements
157298948Sobrien// Do NOT return private or static methods, new in JDK8 which are not externally visible
157319370Spst// They should only be found in the initial InterfaceMethodRef
157419370SpstMethod* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
157519370Spst                                                       Symbol* signature,
157619370Spst                                                       DefaultsLookupMode defaults_mode) const {
157719370Spst  Array<Klass*>* all_ifs = transitive_interfaces();
157819370Spst  int num_ifs = all_ifs->length();
157919370Spst  InstanceKlass *ik = NULL;
158019370Spst  for (int i = 0; i < num_ifs; i++) {
158119370Spst    ik = InstanceKlass::cast(all_ifs->at(i));
158219370Spst    Method* m = ik->lookup_method(name, signature);
158319370Spst    if (m != NULL && m->is_public() && !m->is_static() &&
158419370Spst        ((defaults_mode != skip_defaults) || !m->is_default_method())) {
158519370Spst      return m;
158619370Spst    }
158719370Spst  }
158819370Spst  return NULL;
158919370Spst}
159019370Spst
159119370Spst/* jni_id_for_impl for jfieldIds only */
159219370SpstJNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_k, int offset) {
159319370Spst  MutexLocker ml(JfieldIdCreation_lock);
159419370Spst  // Retry lookup after we got the lock
159519370Spst  JNIid* probe = this_k->jni_ids() == NULL ? NULL : this_k->jni_ids()->find(offset);
159619370Spst  if (probe == NULL) {
159798948Sobrien    // Slow case, allocate new static field identifier
159898948Sobrien    probe = new JNIid(this_k(), offset, this_k->jni_ids());
159998948Sobrien    this_k->set_jni_ids(probe);
160098948Sobrien  }
160198948Sobrien  return probe;
160298948Sobrien}
160398948Sobrien
160498948Sobrien
160519370Spst/* jni_id_for for jfieldIds only */
160619370SpstJNIid* InstanceKlass::jni_id_for(int offset) {
160719370Spst  JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
160819370Spst  if (probe == NULL) {
160919370Spst    probe = jni_id_for_impl(this, offset);
161019370Spst  }
161119370Spst  return probe;
161298948Sobrien}
161398948Sobrien
161498948Sobrienu2 InstanceKlass::enclosing_method_data(int offset) {
161519370Spst  Array<jushort>* inner_class_list = inner_classes();
161619370Spst  if (inner_class_list == NULL) {
161798948Sobrien    return 0;
161819370Spst  }
161919370Spst  int length = inner_class_list->length();
162019370Spst  if (length % inner_class_next_offset == 0) {
162119370Spst    return 0;
162219370Spst  } else {
162398948Sobrien    int index = length - enclosing_method_attribute_size;
162498948Sobrien    assert(offset < enclosing_method_attribute_size, "invalid offset");
162598948Sobrien    return inner_class_list->at(index + offset);
162698948Sobrien  }
162798948Sobrien}
162819370Spst
162919370Spstvoid InstanceKlass::set_enclosing_method_indices(u2 class_index,
163019370Spst                                                 u2 method_index) {
163119370Spst  Array<jushort>* inner_class_list = inner_classes();
163219370Spst  assert (inner_class_list != NULL, "_inner_classes list is not set up");
163346289Sdfr  int length = inner_class_list->length();
163419370Spst  if (length % inner_class_next_offset == enclosing_method_attribute_size) {
163519370Spst    int index = length - enclosing_method_attribute_size;
163619370Spst    inner_class_list->at_put(
163719370Spst      index + enclosing_method_class_index_offset, class_index);
163846289Sdfr    inner_class_list->at_put(
163946289Sdfr      index + enclosing_method_method_index_offset, method_index);
164019370Spst  }
164119370Spst}
164219370Spst
164398948Sobrien// Lookup or create a jmethodID.
164419370Spst// This code is called by the VMThread and JavaThreads so the
164519370Spst// locking has to be done very carefully to avoid deadlocks
164619370Spst// and/or other cache consistency problems.
164719370Spst//
164819370SpstjmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, const methodHandle& method_h) {
164919370Spst  size_t idnum = (size_t)method_h->method_idnum();
165019370Spst  jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
165119370Spst  size_t length = 0;
165219370Spst  jmethodID id = NULL;
165319370Spst
165419370Spst  // We use a double-check locking idiom here because this cache is
1655130809Smarcel  // performance sensitive. In the normal system, this cache only
1656130809Smarcel  // transitions from NULL to non-NULL which is safe because we use
1657130809Smarcel  // release_set_methods_jmethod_ids() to advertise the new cache.
1658130809Smarcel  // A partially constructed cache should never be seen by a racing
1659130809Smarcel  // thread. We also use release_store_ptr() to save a new jmethodID
1660130809Smarcel  // in the cache so a partially constructed jmethodID should never be
1661130809Smarcel  // seen either. Cache reads of existing jmethodIDs proceed without a
1662130809Smarcel  // lock, but cache writes of a new jmethodID requires uniqueness and
1663130809Smarcel  // creation of the cache itself requires no leaks so a lock is
1664130809Smarcel  // generally acquired in those two cases.
166519370Spst  //
166619370Spst  // If the RedefineClasses() API has been used, then this cache can
166719370Spst  // grow and we'll have transitions from non-NULL to bigger non-NULL.
166819370Spst  // Cache creation requires no leaks and we require safety between all
166998948Sobrien  // cache accesses and freeing of the old cache so a lock is generally
167098948Sobrien  // acquired when the RedefineClasses() API has been used.
167198948Sobrien
167298948Sobrien  if (jmeths != NULL) {
167398948Sobrien    // the cache already exists
167419370Spst    if (!ik_h->idnum_can_increment()) {
167519370Spst      // the cache can't grow so we can just get the current values
167619370Spst      get_jmethod_id_length_value(jmeths, idnum, &length, &id);
167719370Spst    } else {
167819370Spst      // cache can grow so we have to be more careful
167919370Spst      if (Threads::number_of_threads() == 0 ||
168019370Spst          SafepointSynchronize::is_at_safepoint()) {
168119370Spst        // we're single threaded or at a safepoint - no locking needed
168219370Spst        get_jmethod_id_length_value(jmeths, idnum, &length, &id);
168319370Spst      } else {
168419370Spst        MutexLocker ml(JmethodIdCreation_lock);
168519370Spst        get_jmethod_id_length_value(jmeths, idnum, &length, &id);
168619370Spst      }
168719370Spst    }
168819370Spst  }
168919370Spst  // implied else:
169019370Spst  // we need to allocate a cache so default length and id values are good
169119370Spst
169219370Spst  if (jmeths == NULL ||   // no cache yet
169319370Spst      length <= idnum ||  // cache is too short
169498948Sobrien      id == NULL) {       // cache doesn't contain entry
169519370Spst
169619370Spst    // This function can be called by the VMThread so we have to do all
169719370Spst    // things that might block on a safepoint before grabbing the lock.
169819370Spst    // Otherwise, we can deadlock with the VMThread or have a cache
169919370Spst    // consistency issue. These vars keep track of what we might have
170019370Spst    // to free after the lock is dropped.
170198948Sobrien    jmethodID  to_dealloc_id     = NULL;
170219370Spst    jmethodID* to_dealloc_jmeths = NULL;
170319370Spst
170498948Sobrien    // may not allocate new_jmeths or use it if we allocate it
170598948Sobrien    jmethodID* new_jmeths = NULL;
170698948Sobrien    if (length <= idnum) {
170798948Sobrien      // allocate a new cache that might be used
170898948Sobrien      size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
170919370Spst      new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
171019370Spst      memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
171119370Spst      // cache size is stored in element[0], other elements offset by one
171219370Spst      new_jmeths[0] = (jmethodID)size;
171319370Spst    }
171419370Spst
171519370Spst    // allocate a new jmethodID that might be used
171619370Spst    jmethodID new_id = NULL;
171719370Spst    if (method_h->is_old() && !method_h->is_obsolete()) {
171819370Spst      // The method passed in is old (but not obsolete), we need to use the current version
171919370Spst      Method* current_method = ik_h->method_with_idnum((int)idnum);
172019370Spst      assert(current_method != NULL, "old and but not obsolete, so should exist");
172119370Spst      new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
172219370Spst    } else {
172319370Spst      // It is the current version of the method or an obsolete method,
172419370Spst      // use the version passed in
172519370Spst      new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
172619370Spst    }
172719370Spst
172819370Spst    if (Threads::number_of_threads() == 0 ||
172919370Spst        SafepointSynchronize::is_at_safepoint()) {
173046289Sdfr      // we're single threaded or at a safepoint - no locking needed
173146289Sdfr      id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
173246289Sdfr                                          &to_dealloc_id, &to_dealloc_jmeths);
173346289Sdfr    } else {
173419370Spst      MutexLocker ml(JmethodIdCreation_lock);
173519370Spst      id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
173619370Spst                                          &to_dealloc_id, &to_dealloc_jmeths);
173719370Spst    }
173819370Spst
173919370Spst    // The lock has been dropped so we can free resources.
174019370Spst    // Free up either the old cache or the new cache if we allocated one.
174119370Spst    if (to_dealloc_jmeths != NULL) {
174219370Spst      FreeHeap(to_dealloc_jmeths);
174319370Spst    }
174419370Spst    // free up the new ID since it wasn't needed
174519370Spst    if (to_dealloc_id != NULL) {
174619370Spst      Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
174719370Spst    }
174819370Spst  }
174919370Spst  return id;
175019370Spst}
175119370Spst
175219370Spst// Figure out how many jmethodIDs haven't been allocated, and make
175319370Spst// sure space for them is pre-allocated.  This makes getting all
175419370Spst// method ids much, much faster with classes with more than 8
175519370Spst// methods, and has a *substantial* effect on performance with jvmti
175619370Spst// code that loads all jmethodIDs for all classes.
175719370Spstvoid InstanceKlass::ensure_space_for_methodids(int start_offset) {
175819370Spst  int new_jmeths = 0;
175919370Spst  int length = methods()->length();
176019370Spst  for (int index = start_offset; index < length; index++) {
176119370Spst    Method* m = methods()->at(index);
176219370Spst    jmethodID id = m->find_jmethod_id_or_null();
176319370Spst    if (id == NULL) {
176419370Spst      new_jmeths++;
176519370Spst    }
176619370Spst  }
176719370Spst  if (new_jmeths != 0) {
176819370Spst    Method::ensure_jmethod_ids(class_loader_data(), new_jmeths);
176919370Spst  }
177019370Spst}
177198948Sobrien
177219370Spst// Common code to fetch the jmethodID from the cache or update the
177319370Spst// cache with the new jmethodID. This function should never do anything
177419370Spst// that causes the caller to go to a safepoint or we can deadlock with
177519370Spst// the VMThread or have cache consistency issues.
177698948Sobrien//
177746289SdfrjmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
177846289Sdfr            instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
177946289Sdfr            jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
178046289Sdfr            jmethodID** to_dealloc_jmeths_p) {
178198948Sobrien  assert(new_id != NULL, "sanity check");
178219370Spst  assert(to_dealloc_id_p != NULL, "sanity check");
178398948Sobrien  assert(to_dealloc_jmeths_p != NULL, "sanity check");
178498948Sobrien  assert(Threads::number_of_threads() == 0 ||
178598948Sobrien         SafepointSynchronize::is_at_safepoint() ||
178698948Sobrien         JmethodIdCreation_lock->owned_by_self(), "sanity check");
178798948Sobrien
178819370Spst  // reacquire the cache - we are locked, single threaded or at a safepoint
178919370Spst  jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
179019370Spst  jmethodID  id     = NULL;
179198948Sobrien  size_t     length = 0;
179219370Spst
179319370Spst  if (jmeths == NULL ||                         // no cache yet
179419370Spst      (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
179519370Spst    if (jmeths != NULL) {
179619370Spst      // copy any existing entries from the old cache
179719370Spst      for (size_t index = 0; index < length; index++) {
179819370Spst        new_jmeths[index+1] = jmeths[index+1];
179919370Spst      }
180019370Spst      *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
180119370Spst    }
180219370Spst    ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
180319370Spst  } else {
180419370Spst    // fetch jmethodID (if any) from the existing cache
180598948Sobrien    id = jmeths[idnum+1];
180619370Spst    *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
180719370Spst  }
180819370Spst  if (id == NULL) {
180919370Spst    // No matching jmethodID in the existing cache or we have a new
181019370Spst    // cache or we just grew the cache. This cache write is done here
181119370Spst    // by the first thread to win the foot race because a jmethodID
181219370Spst    // needs to be unique once it is generally available.
181319370Spst    id = new_id;
181419370Spst
181519370Spst    // The jmethodID cache can be read while unlocked so we have to
181619370Spst    // make sure the new jmethodID is complete before installing it
181719370Spst    // in the cache.
181819370Spst    OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
181919370Spst  } else {
182019370Spst    *to_dealloc_id_p = new_id; // save new id for later delete
182198948Sobrien  }
182298948Sobrien  return id;
182398948Sobrien}
182498948Sobrien
182598948Sobrien
182698948Sobrien// Common code to get the jmethodID cache length and the jmethodID
182719370Spst// value at index idnum if there is one.
182819370Spst//
182919370Spstvoid InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
183019370Spst       size_t idnum, size_t *length_p, jmethodID* id_p) {
183119370Spst  assert(cache != NULL, "sanity check");
183219370Spst  assert(length_p != NULL, "sanity check");
183319370Spst  assert(id_p != NULL, "sanity check");
183419370Spst
183519370Spst  // cache size is stored in element[0], other elements offset by one
183619370Spst  *length_p = (size_t)cache[0];
183719370Spst  if (*length_p <= idnum) {  // cache is too short
183819370Spst    *id_p = NULL;
183919370Spst  } else {
184019370Spst    *id_p = cache[idnum+1];  // fetch jmethodID (if any)
184119370Spst  }
184219370Spst}
184319370Spst
184419370Spst
184519370Spst// Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
184619370SpstjmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
184719370Spst  size_t idnum = (size_t)method->method_idnum();
184819370Spst  jmethodID* jmeths = methods_jmethod_ids_acquire();
184919370Spst  size_t length;                                // length assigned as debugging crumb
185098948Sobrien  jmethodID id = NULL;
185119370Spst  if (jmeths != NULL &&                         // If there is a cache
185219370Spst      (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
185319370Spst    id = jmeths[idnum+1];                       // Look up the id (may be NULL)
185419370Spst  }
185519370Spst  return id;
185619370Spst}
185719370Spst
185819370Spstint nmethodBucket::decrement() {
185919370Spst  return Atomic::add(-1, (volatile int *)&_count);
186019370Spst}
186119370Spst
1862130809Smarcel//
186319370Spst// Walk the list of dependent nmethods searching for nmethods which
1864130809Smarcel// are dependent on the changes that were passed in and mark them for
186519370Spst// deoptimization.  Returns the number of nmethods found.
186619370Spst//
186798948Sobrienint nmethodBucket::mark_dependent_nmethods(nmethodBucket* deps, DepChange& changes) {
186819370Spst  assert_locked_or_safepoint(CodeCache_lock);
186919370Spst  int found = 0;
187019370Spst  for (nmethodBucket* b = deps; b != NULL; b = b->next()) {
187119370Spst    nmethod* nm = b->get_nmethod();
187219370Spst    // since dependencies aren't removed until an nmethod becomes a zombie,
187319370Spst    // the dependency list may contain nmethods which aren't alive.
187419370Spst    if (b->count() > 0 && nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
187519370Spst      if (TraceDependencies) {
187619370Spst        ResourceMark rm;
187719370Spst        tty->print_cr("Marked for deoptimization");
187819370Spst        changes.print();
187998948Sobrien        nm->print();
188098948Sobrien        nm->print_dependencies();
188119370Spst      }
188219370Spst      nm->mark_for_deoptimization();
188319370Spst      found++;
188419370Spst    }
188519370Spst  }
188619370Spst  return found;
188719370Spst}
188819370Spst
188998948Sobrien//
189019370Spst// Add an nmethodBucket to the list of dependencies for this nmethod.
189119370Spst// It's possible that an nmethod has multiple dependencies on this klass
189219370Spst// so a count is kept for each bucket to guarantee that creation and
189319370Spst// deletion of dependencies is consistent. Returns new head of the list.
189419370Spst//
189519370SpstnmethodBucket* nmethodBucket::add_dependent_nmethod(nmethodBucket* deps, nmethod* nm) {
189619370Spst  assert_locked_or_safepoint(CodeCache_lock);
189719370Spst  for (nmethodBucket* b = deps; b != NULL; b = b->next()) {
189819370Spst    if (nm == b->get_nmethod()) {
189919370Spst      b->increment();
190019370Spst      return deps;
190119370Spst    }
190219370Spst  }
190319370Spst  return new nmethodBucket(nm, deps);
190419370Spst}
190519370Spst
190619370Spst//
190719370Spst// Decrement count of the nmethod in the dependency list and remove
190819370Spst// the bucket completely when the count goes to 0.  This method must
190919370Spst// find a corresponding bucket otherwise there's a bug in the
191019370Spst// recording of dependencies. Returns true if the bucket was deleted,
191119370Spst// or marked ready for reclaimation.
191219370Spstbool nmethodBucket::remove_dependent_nmethod(nmethodBucket** deps, nmethod* nm, bool delete_immediately) {
191398948Sobrien  assert_locked_or_safepoint(CodeCache_lock);
191419370Spst
191519370Spst  nmethodBucket* first = *deps;
191619370Spst  nmethodBucket* last = NULL;
191719370Spst
191819370Spst  for (nmethodBucket* b = first; b != NULL; b = b->next()) {
191919370Spst    if (nm == b->get_nmethod()) {
192098948Sobrien      int val = b->decrement();
192119370Spst      guarantee(val >= 0, "Underflow: %d", val);
192219370Spst      if (val == 0) {
192319370Spst        if (delete_immediately) {
192419370Spst          if (last == NULL) {
192519370Spst            *deps = b->next();
192619370Spst          } else {
192719370Spst            last->set_next(b->next());
192819370Spst          }
192919370Spst          delete b;
193019370Spst        }
193119370Spst      }
193219370Spst      return true;
193319370Spst    }
193419370Spst    last = b;
1935130809Smarcel  }
193619370Spst
1937130809Smarcel#ifdef ASSERT
193819370Spst  tty->print_raw_cr("### can't find dependent nmethod");
193919370Spst  nm->print();
194019370Spst#endif // ASSERT
194119370Spst  ShouldNotReachHere();
194219370Spst  return false;
194319370Spst}
194419370Spst
194519370Spst// Convenience overload, for callers that don't want to delete the nmethodBucket entry.
194619370Spstbool nmethodBucket::remove_dependent_nmethod(nmethodBucket* deps, nmethod* nm) {
194719370Spst  nmethodBucket** deps_addr = &deps;
194819370Spst  return remove_dependent_nmethod(deps_addr, nm, false /* Don't delete */);
194919370Spst}
1950130809Smarcel
195119370Spst//
1952130809Smarcel// Reclaim all unused buckets. Returns new head of the list.
195319370Spst//
195419370SpstnmethodBucket* nmethodBucket::clean_dependent_nmethods(nmethodBucket* deps) {
195519370Spst  nmethodBucket* first = deps;
195619370Spst  nmethodBucket* last = NULL;
195719370Spst  nmethodBucket* b = first;
195819370Spst
195919370Spst  while (b != NULL) {
196019370Spst    assert(b->count() >= 0, "bucket count: %d", b->count());
196119370Spst    nmethodBucket* next = b->next();
196219370Spst    if (b->count() == 0) {
196319370Spst      if (last == NULL) {
196419370Spst        first = next;
196519370Spst      } else {
196619370Spst        last->set_next(next);
196798948Sobrien      }
196819370Spst      delete b;
196919370Spst      // last stays the same.
197019370Spst    } else {
197119370Spst      last = b;
197219370Spst    }
197319370Spst    b = next;
197419370Spst  }
197519370Spst  return first;
197619370Spst}
197719370Spst
197819370Spst#ifndef PRODUCT
197919370Spstvoid nmethodBucket::print_dependent_nmethods(nmethodBucket* deps, bool verbose) {
198019370Spst  int idx = 0;
198119370Spst  for (nmethodBucket* b = deps; b != NULL; b = b->next()) {
198219370Spst    nmethod* nm = b->get_nmethod();
198319370Spst    tty->print("[%d] count=%d { ", idx++, b->count());
198419370Spst    if (!verbose) {
198519370Spst      nm->print_on(tty, "nmethod");
198619370Spst      tty->print_cr(" } ");
198719370Spst    } else {
198819370Spst      nm->print();
198946289Sdfr      nm->print_dependencies();
199046289Sdfr      tty->print_cr("--- } ");
199146289Sdfr    }
199246289Sdfr  }
199346289Sdfr}
199446289Sdfr
199519370Spstbool nmethodBucket::is_dependent_nmethod(nmethodBucket* deps, nmethod* nm) {
199619370Spst  for (nmethodBucket* b = deps; b != NULL; b = b->next()) {
199719370Spst    if (nm == b->get_nmethod()) {
199898948Sobrien#ifdef ASSERT
199998948Sobrien      int count = b->count();
200098948Sobrien      assert(count >= 0, "count shouldn't be negative: %d", count);
200198948Sobrien#endif
200219370Spst      return true;
200319370Spst    }
200419370Spst  }
200519370Spst  return false;
200619370Spst}
200719370Spst#endif //PRODUCT
200819370Spst
200919370Spstint InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
201019370Spst  assert_locked_or_safepoint(CodeCache_lock);
201119370Spst  return nmethodBucket::mark_dependent_nmethods(_dependencies, changes);
201219370Spst}
201319370Spst
201419370Spstvoid InstanceKlass::clean_dependent_nmethods() {
201519370Spst  assert_locked_or_safepoint(CodeCache_lock);
201619370Spst
201719370Spst  if (has_unloaded_dependent()) {
201819370Spst    _dependencies = nmethodBucket::clean_dependent_nmethods(_dependencies);
201919370Spst    set_has_unloaded_dependent(false);
202019370Spst  }
202119370Spst#ifdef ASSERT
202219370Spst  else {
202398948Sobrien    // Verification
202419370Spst    for (nmethodBucket* b = _dependencies; b != NULL; b = b->next()) {
202519370Spst      assert(b->count() >= 0, "bucket count: %d", b->count());
202619370Spst      assert(b->count() != 0, "empty buckets need to be cleaned");
202719370Spst    }
202819370Spst  }
202919370Spst#endif
203019370Spst}
203119370Spst
203219370Spstvoid InstanceKlass::add_dependent_nmethod(nmethod* nm) {
203319370Spst  assert_locked_or_safepoint(CodeCache_lock);
203419370Spst  _dependencies = nmethodBucket::add_dependent_nmethod(_dependencies, nm);
203519370Spst}
203619370Spst
203719370Spstvoid InstanceKlass::remove_dependent_nmethod(nmethod* nm, bool delete_immediately) {
203819370Spst  assert_locked_or_safepoint(CodeCache_lock);
203919370Spst
204019370Spst  if (nmethodBucket::remove_dependent_nmethod(&_dependencies, nm, delete_immediately)) {
204119370Spst    set_has_unloaded_dependent(true);
204219370Spst  }
204319370Spst}
204419370Spst
204519370Spst#ifndef PRODUCT
204619370Spstvoid InstanceKlass::print_dependent_nmethods(bool verbose) {
204719370Spst  nmethodBucket::print_dependent_nmethods(_dependencies, verbose);
204898948Sobrien}
204919370Spst
205019370Spstbool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
205119370Spst  return nmethodBucket::is_dependent_nmethod(_dependencies, nm);
205219370Spst}
205319370Spst#endif //PRODUCT
205446289Sdfr
205546289Sdfrvoid InstanceKlass::clean_weak_instanceklass_links(BoolObjectClosure* is_alive) {
205646289Sdfr  clean_implementors_list(is_alive);
205746289Sdfr  clean_method_data(is_alive);
205846289Sdfr
205946289Sdfr  clean_dependent_nmethods();
206046289Sdfr}
206119370Spst
206219370Spstvoid InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
206319370Spst  assert(class_loader_data()->is_alive(is_alive), "this klass should be live");
206419370Spst  if (is_interface()) {
206519370Spst    if (ClassUnloading) {
206619370Spst      Klass* impl = implementor();
206719370Spst      if (impl != NULL) {
206819370Spst        if (!impl->is_loader_alive(is_alive)) {
206998948Sobrien          // remove this guy
207019370Spst          Klass** klass = adr_implementor();
207119370Spst          assert(klass != NULL, "null klass");
207219370Spst          if (klass != NULL) {
207319370Spst            *klass = NULL;
207419370Spst          }
207519370Spst        }
207619370Spst      }
207719370Spst    }
207819370Spst  }
207919370Spst}
208019370Spst
208119370Spstvoid InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
208219370Spst  for (int m = 0; m < methods()->length(); m++) {
208319370Spst    MethodData* mdo = methods()->at(m)->method_data();
208419370Spst    if (mdo != NULL) {
208519370Spst      mdo->clean_method_data(is_alive);
208619370Spst    }
208719370Spst  }
208819370Spst}
208919370Spst
209019370Spst
209119370Spststatic void remove_unshareable_in_class(Klass* k) {
209219370Spst  // remove klass's unshareable info
209319370Spst  k->remove_unshareable_info();
209419370Spst}
209519370Spst
209619370Spstvoid InstanceKlass::remove_unshareable_info() {
209719370Spst  Klass::remove_unshareable_info();
209819370Spst  // Unlink the class
209919370Spst  if (is_linked()) {
210098948Sobrien    unlink_class();
210119370Spst  }
210219370Spst  init_implementor();
210319370Spst
210419370Spst  constants()->remove_unshareable_info();
210519370Spst
210619370Spst  for (int i = 0; i < methods()->length(); i++) {
210719370Spst    Method* m = methods()->at(i);
210819370Spst    m->remove_unshareable_info();
210919370Spst  }
211019370Spst
2111130809Smarcel  // do array classes also.
211219370Spst  array_klasses_do(remove_unshareable_in_class);
2113130809Smarcel}
211419370Spst
211519370Spststatic void restore_unshareable_in_class(Klass* k, TRAPS) {
211619370Spst  // Array classes have null protection domain.
211719370Spst  // --> see ArrayKlass::complete_create_array_klass()
211819370Spst  k->restore_unshareable_info(ClassLoaderData::the_null_class_loader_data(), Handle(), CHECK);
211919370Spst}
212019370Spst
212119370Spstvoid InstanceKlass::restore_unshareable_info(ClassLoaderData* loader_data, Handle protection_domain, TRAPS) {
212298948Sobrien  Klass::restore_unshareable_info(loader_data, protection_domain, CHECK);
212319370Spst  instanceKlassHandle ik(THREAD, this);
212419370Spst
212519370Spst  Array<Method*>* methods = ik->methods();
212698948Sobrien  int num_methods = methods->length();
212719370Spst  for (int index2 = 0; index2 < num_methods; ++index2) {
212819370Spst    methodHandle m(THREAD, methods->at(index2));
212919370Spst    m->restore_unshareable_info(CHECK);
213019370Spst  }
213119370Spst  if (JvmtiExport::has_redefined_a_class()) {
213219370Spst    // Reinitialize vtable because RedefineClasses may have changed some
213319370Spst    // entries in this vtable for super classes so the CDS vtable might
213419370Spst    // point to old or obsolete entries.  RedefineClasses doesn't fix up
213519370Spst    // vtables in the shared system dictionary, only the main one.
213619370Spst    // It also redefines the itable too so fix that too.
213719370Spst    ResourceMark rm(THREAD);
213819370Spst    ik->vtable()->initialize_vtable(false, CHECK);
213919370Spst    ik->itable()->initialize_itable(false, CHECK);
214019370Spst  }
214119370Spst
214219370Spst  // restore constant pool resolved references
214319370Spst  ik->constants()->restore_unshareable_info(CHECK);
214419370Spst
214519370Spst  ik->array_klasses_do(restore_unshareable_in_class, CHECK);
214619370Spst}
214719370Spst
214819370Spst// returns true IFF is_in_error_state() has been changed as a result of this call.
214919370Spstbool InstanceKlass::check_sharing_error_state() {
215019370Spst  assert(DumpSharedSpaces, "should only be called during dumping");
215198948Sobrien  bool old_state = is_in_error_state();
215219370Spst
215319370Spst  if (!is_in_error_state()) {
215419370Spst    bool bad = false;
215519370Spst    for (InstanceKlass* sup = java_super(); sup; sup = sup->java_super()) {
215619370Spst      if (sup->is_in_error_state()) {
215719370Spst        bad = true;
215819370Spst        break;
215919370Spst      }
216019370Spst    }
216119370Spst    if (!bad) {
216219370Spst      Array<Klass*>* interfaces = transitive_interfaces();
216398948Sobrien      for (int i = 0; i < interfaces->length(); i++) {
216498948Sobrien        Klass* iface = interfaces->at(i);
216546289Sdfr        if (InstanceKlass::cast(iface)->is_in_error_state()) {
216646289Sdfr          bad = true;
216746289Sdfr          break;
216846289Sdfr        }
216946289Sdfr      }
217046289Sdfr    }
217198948Sobrien
217298948Sobrien    if (bad) {
217346289Sdfr      set_in_error_state();
217446289Sdfr    }
217546289Sdfr  }
217646289Sdfr
217746289Sdfr  return (old_state != is_in_error_state());
217846289Sdfr}
217946289Sdfr
218046289Sdfrstatic void clear_all_breakpoints(Method* m) {
218146289Sdfr  m->clear_all_breakpoints();
2182130809Smarcel}
218346289Sdfr
2184130809Smarcel
218546289Sdfrvoid InstanceKlass::notify_unload_class(InstanceKlass* ik) {
218646289Sdfr  // notify the debugger
218798948Sobrien  if (JvmtiExport::should_post_class_unload()) {
218846289Sdfr    JvmtiExport::post_class_unload(ik);
218919370Spst  }
219046289Sdfr
219146289Sdfr  // notify ClassLoadingService of class unload
219246289Sdfr  ClassLoadingService::notify_class_unloaded(ik);
219346289Sdfr}
219446289Sdfr
219546289Sdfrvoid InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
219646289Sdfr  // Clean up C heap
219746289Sdfr  ik->release_C_heap_structures();
219846289Sdfr  ik->constants()->release_C_heap_structures();
219946289Sdfr}
220046289Sdfr
220146289Sdfrvoid InstanceKlass::release_C_heap_structures() {
220246289Sdfr
220346289Sdfr  // Can't release the constant pool here because the constant pool can be
220446289Sdfr  // deallocated separately from the InstanceKlass for default methods and
220546289Sdfr  // redefine classes.
220646289Sdfr
220798948Sobrien  // Deallocate oop map cache
220846289Sdfr  if (_oop_map_cache != NULL) {
220946289Sdfr    delete _oop_map_cache;
221046289Sdfr    _oop_map_cache = NULL;
2211130809Smarcel  }
221246289Sdfr
221398948Sobrien  // Deallocate JNI identifiers for jfieldIDs
221498948Sobrien  JNIid::deallocate(jni_ids());
221598948Sobrien  set_jni_ids(NULL);
221698948Sobrien
221798948Sobrien  jmethodID* jmeths = methods_jmethod_ids_acquire();
221898948Sobrien  if (jmeths != (jmethodID*)NULL) {
2219130809Smarcel    release_set_methods_jmethod_ids(NULL);
222046289Sdfr    FreeHeap(jmeths);
222146289Sdfr  }
222219370Spst
222319370Spst  // Deallocate MemberNameTable
222419370Spst  {
222519370Spst    Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
222619370Spst    MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
222719370Spst    MemberNameTable* mnt = member_names();
222819370Spst    if (mnt != NULL) {
222919370Spst      delete mnt;
223019370Spst      set_member_names(NULL);
223119370Spst    }
223219370Spst  }
223319370Spst
223419370Spst  // release dependencies
223519370Spst  nmethodBucket* b = _dependencies;
223619370Spst  _dependencies = NULL;
223719370Spst  while (b != NULL) {
223819370Spst    nmethodBucket* next = b->next();
223919370Spst    delete b;
224098948Sobrien    b = next;
224119370Spst  }
224219370Spst
224319370Spst  // Deallocate breakpoint records
224419370Spst  if (breakpoints() != 0x0) {
224519370Spst    methods_do(clear_all_breakpoints);
224619370Spst    assert(breakpoints() == 0x0, "should have cleared breakpoints");
224719370Spst  }
224898948Sobrien
224998948Sobrien  // deallocate the cached class file
225019370Spst  if (_cached_class_file != NULL) {
225119370Spst    os::free(_cached_class_file);
225219370Spst    _cached_class_file = NULL;
225319370Spst  }
225419370Spst
225519370Spst  // Decrement symbol reference counts associated with the unloaded class.
225619370Spst  if (_name != NULL) _name->decrement_refcount();
225719370Spst  // unreference array name derived from this class name (arrays of an unloaded
225819370Spst  // class can't be referenced anymore).
225919370Spst  if (_array_name != NULL)  _array_name->decrement_refcount();
226019370Spst  if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension);
226119370Spst
226219370Spst  assert(_total_instanceKlass_count >= 1, "Sanity check");
226319370Spst  Atomic::dec(&_total_instanceKlass_count);
226419370Spst}
226519370Spst
226619370Spstvoid InstanceKlass::set_source_debug_extension(char* array, int length) {
226719370Spst  if (array == NULL) {
226898948Sobrien    _source_debug_extension = NULL;
226919370Spst  } else {
227019370Spst    // Adding one to the attribute length in order to store a null terminator
227119370Spst    // character could cause an overflow because the attribute length is
227219370Spst    // already coded with an u4 in the classfile, but in practice, it's
227319370Spst    // unlikely to happen.
227498948Sobrien    assert((length+1) > length, "Overflow checking");
227598948Sobrien    char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
227698948Sobrien    for (int i = 0; i < length; i++) {
227798948Sobrien      sde[i] = array[i];
227898948Sobrien    }
227998948Sobrien    sde[length] = '\0';
228098948Sobrien    _source_debug_extension = sde;
228119370Spst  }
228219370Spst}
228319370Spst
228419370Spstaddress InstanceKlass::static_field_addr(int offset) {
228519370Spst  return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
228619370Spst}
228719370Spst
228819370Spst
228919370Spstconst char* InstanceKlass::signature_name() const {
229098948Sobrien  int hash_len = 0;
229119370Spst  char hash_buf[40];
229219370Spst
2293130809Smarcel  // If this is an anonymous class, append a hash to make the name unique
2294130809Smarcel  if (is_anonymous()) {
2295130809Smarcel    intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2296130809Smarcel    jio_snprintf(hash_buf, sizeof(hash_buf), "/" UINTX_FORMAT, (uintx)hash);
229746289Sdfr    hash_len = (int)strlen(hash_buf);
229846289Sdfr  }
229946289Sdfr
230046289Sdfr  // Get the internal name as a c string
230146289Sdfr  const char* src = (const char*) (name()->as_C_string());
230246289Sdfr  const int src_length = (int)strlen(src);
230346289Sdfr
230446289Sdfr  char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
230546289Sdfr
230646289Sdfr  // Add L as type indicator
230746289Sdfr  int dest_index = 0;
230846289Sdfr  dest[dest_index++] = 'L';
230946289Sdfr
231046289Sdfr  // Add the actual class name
231146289Sdfr  for (int src_index = 0; src_index < src_length; ) {
231246289Sdfr    dest[dest_index++] = src[src_index++];
231346289Sdfr  }
231498948Sobrien
231546289Sdfr  // If we have a hash, append it
231646289Sdfr  for (int hash_index = 0; hash_index < hash_len; ) {
231746289Sdfr    dest[dest_index++] = hash_buf[hash_index++];
231846289Sdfr  }
231946289Sdfr
232046289Sdfr  // Add the semicolon and the NULL
232146289Sdfr  dest[dest_index++] = ';';
232246289Sdfr  dest[dest_index] = '\0';
232398948Sobrien  return dest;
232446289Sdfr}
232546289Sdfr
232646289Sdfr// different verisons of is_same_class_package
232746289Sdfrbool InstanceKlass::is_same_class_package(Klass* class2) {
232846289Sdfr  Klass* class1 = this;
232946289Sdfr  oop classloader1 = InstanceKlass::cast(class1)->class_loader();
233046289Sdfr  Symbol* classname1 = class1->name();
233146289Sdfr
233246289Sdfr  if (class2->oop_is_objArray()) {
233346289Sdfr    class2 = ObjArrayKlass::cast(class2)->bottom_klass();
233446289Sdfr  }
233546289Sdfr  oop classloader2;
233646289Sdfr  if (class2->oop_is_instance()) {
233746289Sdfr    classloader2 = InstanceKlass::cast(class2)->class_loader();
233846289Sdfr  } else {
233946289Sdfr    assert(class2->oop_is_typeArray(), "should be type array");
234046289Sdfr    classloader2 = NULL;
234146289Sdfr  }
234246289Sdfr  Symbol* classname2 = class2->name();
234346289Sdfr
234498948Sobrien  return InstanceKlass::is_same_class_package(classloader1, classname1,
234519370Spst                                              classloader2, classname2);
234619370Spst}
234719370Spst
234819370Spstbool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
234919370Spst  Klass* class1 = this;
235019370Spst  oop classloader1 = InstanceKlass::cast(class1)->class_loader();
235198948Sobrien  Symbol* classname1 = class1->name();
235298948Sobrien
235398948Sobrien  return InstanceKlass::is_same_class_package(classloader1, classname1,
235498948Sobrien                                              classloader2, classname2);
235598948Sobrien}
235698948Sobrien
235798948Sobrien// return true if two classes are in the same package, classloader
235819370Spst// and classname information is enough to determine a class's package
235919370Spstbool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
236019370Spst                                          oop class_loader2, Symbol* class_name2) {
236119370Spst  if (class_loader1 != class_loader2) {
236219370Spst    return false;
236398948Sobrien  } else if (class_name1 == class_name2) {
236419370Spst    return true;                // skip painful bytewise comparison
236519370Spst  } else {
236619370Spst    ResourceMark rm;
236746289Sdfr
236819370Spst    // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
236919370Spst    // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
237046289Sdfr    // Otherwise, we just compare jbyte values between the strings.
237119370Spst    const jbyte *name1 = class_name1->base();
237219370Spst    const jbyte *name2 = class_name2->base();
237398948Sobrien
237446289Sdfr    const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
237519370Spst    const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
237619370Spst
237719370Spst    if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
237846289Sdfr      // One of the two doesn't have a package.  Only return true
237946289Sdfr      // if the other one also doesn't have a package.
238046289Sdfr      return last_slash1 == last_slash2;
238146289Sdfr    } else {
238246289Sdfr      // Skip over '['s
238346289Sdfr      if (*name1 == '[') {
238419370Spst        do {
238546289Sdfr          name1++;
238646289Sdfr        } while (*name1 == '[');
238746289Sdfr        if (*name1 != 'L') {
238846289Sdfr          // Something is terribly wrong.  Shouldn't be here.
238946289Sdfr          return false;
239046289Sdfr        }
239119370Spst      }
239219370Spst      if (*name2 == '[') {
239319370Spst        do {
239419370Spst          name2++;
239519370Spst        } while (*name2 == '[');
239619370Spst        if (*name2 != 'L') {
239719370Spst          // Something is terribly wrong.  Shouldn't be here.
239819370Spst          return false;
239919370Spst        }
240019370Spst      }
240119370Spst
240219370Spst      // Check that package part is identical
240319370Spst      int length1 = last_slash1 - name1;
240419370Spst      int length2 = last_slash2 - name2;
240519370Spst
240619370Spst      return UTF8::equal(name1, length1, name2, length2);
240746289Sdfr    }
240846289Sdfr  }
240946289Sdfr}
241098948Sobrien
241146289Sdfr// Returns true iff super_method can be overridden by a method in targetclassname
241246289Sdfr// See JSL 3rd edition 8.4.6.1
241346289Sdfr// Assumes name-signature match
241446289Sdfr// "this" is InstanceKlass of super_method which must exist
241598948Sobrien// note that the InstanceKlass of the method in the targetclassname has not always been created yet
241646289Sdfrbool InstanceKlass::is_override(const methodHandle& super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
241719370Spst   // Private methods can not be overridden
241819370Spst   if (super_method->is_private()) {
241946289Sdfr     return false;
242046289Sdfr   }
242146289Sdfr   // If super method is accessible, then override
242246289Sdfr   if ((super_method->is_protected()) ||
242346289Sdfr       (super_method->is_public())) {
242446289Sdfr     return true;
242546289Sdfr   }
242619370Spst   // Package-private methods are not inherited outside of package
242798948Sobrien   assert(super_method->is_package_private(), "must be package private");
242898948Sobrien   return(is_same_class_package(targetclassloader(), targetclassname));
242998948Sobrien}
243098948Sobrien
243198948Sobrien/* defined for now in jvm.cpp, for historical reasons *--
243298948SobrienKlass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
243398948Sobrien                                                     Symbol*& simple_name_result, TRAPS) {
243498948Sobrien  ...
243519370Spst}
243619370Spst*/
243719370Spst
243846289Sdfr// tell if two classes have the same enclosing class (at package level)
243919370Spstbool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
244019370Spst                                                Klass* class2_oop, TRAPS) {
244119370Spst  if (class2_oop == class1())                       return true;
244219370Spst  if (!class2_oop->oop_is_instance())  return false;
244319370Spst  instanceKlassHandle class2(THREAD, class2_oop);
244498948Sobrien
2445130809Smarcel  // must be in same package before we try anything else
244619370Spst  if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
244719370Spst    return false;
244898948Sobrien
244919370Spst  // As long as there is an outer1.getEnclosingClass,
245019370Spst  // shift the search outward.
245198948Sobrien  instanceKlassHandle outer1 = class1;
245219370Spst  for (;;) {
245319370Spst    // As we walk along, look for equalities between outer1 and class2.
245419370Spst    // Eventually, the walks will terminate as outer1 stops
245519370Spst    // at the top-level class around the original class.
245619370Spst    bool ignore_inner_is_member;
245798948Sobrien    Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
245898948Sobrien                                                    CHECK_false);
245919370Spst    if (next == NULL)  break;
246019370Spst    if (next == class2())  return true;
246198948Sobrien    outer1 = instanceKlassHandle(THREAD, next);
246298948Sobrien  }
246319370Spst
246419370Spst  // Now do the same for class2.
246519370Spst  instanceKlassHandle outer2 = class2;
246619370Spst  for (;;) {
246719370Spst    bool ignore_inner_is_member;
246819370Spst    Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
246919370Spst                                                    CHECK_false);
247098948Sobrien    if (next == NULL)  break;
247119370Spst    // Might as well check the new outer against all available values.
247298948Sobrien    if (next == class1())  return true;
247319370Spst    if (next == outer1())  return true;
247419370Spst    outer2 = instanceKlassHandle(THREAD, next);
247519370Spst  }
247619370Spst
247719370Spst  // If by this point we have not found an equality between the
247898948Sobrien  // two classes, we know they are in separate package members.
247998948Sobrien  return false;
248019370Spst}
248119370Spst
248219370Spstbool InstanceKlass::find_inner_classes_attr(instanceKlassHandle k, int* ooff, int* noff, TRAPS) {
248398948Sobrien  constantPoolHandle i_cp(THREAD, k->constants());
248498948Sobrien  for (InnerClassesIterator iter(k); !iter.done(); iter.next()) {
248519370Spst    int ioff = iter.inner_class_info_index();
248619370Spst    if (ioff != 0) {
248719370Spst      // Check to see if the name matches the class we're looking for
248819370Spst      // before attempting to find the class.
248919370Spst      if (i_cp->klass_name_at_matches(k, ioff)) {
249019370Spst        Klass* inner_klass = i_cp->klass_at(ioff, CHECK_false);
249119370Spst        if (k() == inner_klass) {
249219370Spst          *ooff = iter.outer_class_info_index();
249319370Spst          *noff = iter.inner_name_index();
249419370Spst          return true;
249519370Spst        }
249619370Spst      }
249719370Spst    }
249819370Spst  }
249919370Spst  return false;
250019370Spst}
250119370Spst
250219370SpstKlass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle k, bool* inner_is_member, TRAPS) {
250319370Spst  instanceKlassHandle outer_klass;
250419370Spst  *inner_is_member = false;
250519370Spst  int ooff = 0, noff = 0;
250619370Spst  if (find_inner_classes_attr(k, &ooff, &noff, THREAD)) {
250719370Spst    constantPoolHandle i_cp(THREAD, k->constants());
250819370Spst    if (ooff != 0) {
250919370Spst      Klass* ok = i_cp->klass_at(ooff, CHECK_NULL);
251019370Spst      outer_klass = instanceKlassHandle(THREAD, ok);
251119370Spst      *inner_is_member = true;
251219370Spst    }
251319370Spst    if (outer_klass.is_null()) {
251419370Spst      // It may be anonymous; try for that.
251519370Spst      int encl_method_class_idx = k->enclosing_method_class_index();
251619370Spst      if (encl_method_class_idx != 0) {
251719370Spst        Klass* ok = i_cp->klass_at(encl_method_class_idx, CHECK_NULL);
251819370Spst        outer_klass = instanceKlassHandle(THREAD, ok);
251919370Spst        *inner_is_member = false;
252019370Spst      }
252119370Spst    }
252219370Spst  }
252319370Spst
252419370Spst  // If no inner class attribute found for this class.
252519370Spst  if (outer_klass.is_null())  return NULL;
252619370Spst
252719370Spst  // Throws an exception if outer klass has not declared k as an inner klass
252819370Spst  // We need evidence that each klass knows about the other, or else
252919370Spst  // the system could allow a spoof of an inner class to gain access rights.
253019370Spst  Reflection::check_for_inner_class(outer_klass, k, *inner_is_member, CHECK_NULL);
253119370Spst  return outer_klass();
253219370Spst}
253319370Spst
253419370Spstjint InstanceKlass::compute_modifier_flags(TRAPS) const {
253519370Spst  jint access = access_flags().as_int();
253698948Sobrien
253798948Sobrien  // But check if it happens to be member class.
253819370Spst  instanceKlassHandle ik(THREAD, this);
253919370Spst  InnerClassesIterator iter(ik);
254098948Sobrien  for (; !iter.done(); iter.next()) {
254198948Sobrien    int ioff = iter.inner_class_info_index();
254298948Sobrien    // Inner class attribute can be zero, skip it.
254398948Sobrien    // Strange but true:  JVM spec. allows null inner class refs.
254498948Sobrien    if (ioff == 0) continue;
254598948Sobrien
254698948Sobrien    // only look at classes that are already loaded
254798948Sobrien    // since we are looking for the flags for our self.
254898948Sobrien    Symbol* inner_name = ik->constants()->klass_name_at(ioff);
254998948Sobrien    if ((ik->name() == inner_name)) {
2550130809Smarcel      // This is really a member class.
255119370Spst      access = iter.inner_access_flags();
2552130809Smarcel      break;
255319370Spst    }
255419370Spst  }
255519370Spst  // Remember to strip ACC_SUPER bit
255619370Spst  return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
255798948Sobrien}
255819370Spst
255919370Spstjint InstanceKlass::jvmti_class_status() const {
256098948Sobrien  jint result = 0;
256198948Sobrien
256298948Sobrien  if (is_linked()) {
256319370Spst    result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
256419370Spst  }
256519370Spst
256619370Spst  if (is_initialized()) {
256719370Spst    assert(is_linked(), "Class status is not consistent");
256898948Sobrien    result |= JVMTI_CLASS_STATUS_INITIALIZED;
256998948Sobrien  }
257098948Sobrien  if (is_in_error_state()) {
257198948Sobrien    result |= JVMTI_CLASS_STATUS_ERROR;
257298948Sobrien  }
257319370Spst  return result;
257498948Sobrien}
257598948Sobrien
257698948SobrienMethod* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
257798948Sobrien  itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
257898948Sobrien  int method_table_offset_in_words = ioe->offset()/wordSize;
257998948Sobrien  int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
258098948Sobrien                       / itableOffsetEntry::size();
258198948Sobrien
258219370Spst  for (int cnt = 0 ; ; cnt ++, ioe ++) {
258319370Spst    // If the interface isn't implemented by the receiver class,
258419370Spst    // the VM should throw IncompatibleClassChangeError.
258519370Spst    if (cnt >= nof_interfaces) {
258619370Spst      THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
258719370Spst    }
258819370Spst
258919370Spst    Klass* ik = ioe->interface_klass();
259046289Sdfr    if (ik == holder) break;
259146289Sdfr  }
259219370Spst
259319370Spst  itableMethodEntry* ime = ioe->first_method_entry(this);
259419370Spst  Method* m = ime[index].method();
259519370Spst  if (m == NULL) {
259646289Sdfr    THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
259719370Spst  }
259819370Spst  return m;
259919370Spst}
260019370Spst
260119370Spst
260219370Spst#if INCLUDE_JVMTI
2603130809Smarcel// update default_methods for redefineclasses for methods that are
2604130809Smarcel// not yet in the vtable due to concurrent subclass define and superinterface
2605130809Smarcel// redefinition
260619370Spst// Note: those in the vtable, should have been updated via adjust_method_entries
260719370Spstvoid InstanceKlass::adjust_default_methods(InstanceKlass* holder, bool* trace_name_printed) {
2608130809Smarcel  // search the default_methods for uses of either obsolete or EMCP methods
2609130809Smarcel  if (default_methods() != NULL) {
2610130809Smarcel    for (int index = 0; index < default_methods()->length(); index ++) {
261119370Spst      Method* old_method = default_methods()->at(index);
261219370Spst      if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) {
261319370Spst        continue; // skip uninteresting entries
261419370Spst      }
261519370Spst      assert(!old_method->is_deleted(), "default methods may not be deleted");
2616130809Smarcel
2617130809Smarcel      Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum());
2618130809Smarcel
2619130809Smarcel      assert(new_method != NULL, "method_with_idnum() should not be NULL");
262019370Spst      assert(old_method != new_method, "sanity check");
262119370Spst
262219370Spst      default_methods()->at_put(index, new_method);
262319370Spst      if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
262419370Spst        if (!(*trace_name_printed)) {
262519370Spst          // RC_TRACE_MESG macro has an embedded ResourceMark
262698948Sobrien          RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
262719370Spst                         external_name(),
262819370Spst                         old_method->method_holder()->external_name()));
262946289Sdfr          *trace_name_printed = true;
263046289Sdfr        }
263146289Sdfr        RC_TRACE(0x00100000, ("default method update: %s(%s) ",
263246289Sdfr                              new_method->name()->as_C_string(),
263346289Sdfr                              new_method->signature()->as_C_string()));
263446289Sdfr      }
263519370Spst    }
263619370Spst  }
263719370Spst}
263819370Spst#endif // INCLUDE_JVMTI
263919370Spst
264019370Spst// On-stack replacement stuff
264119370Spstvoid InstanceKlass::add_osr_nmethod(nmethod* n) {
2642130809Smarcel  // only one compilation can be active
2643130809Smarcel  {
2644130809Smarcel    // This is a short non-blocking critical region, so the no safepoint check is ok.
2645130809Smarcel    MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2646130809Smarcel    assert(n->is_osr_method(), "wrong kind of nmethod");
2647130809Smarcel    n->set_osr_link(osr_nmethods_head());
2648130809Smarcel    set_osr_nmethods_head(n);
2649130809Smarcel    // Raise the highest osr level if necessary
2650130809Smarcel    if (TieredCompilation) {
2651130809Smarcel      Method* m = n->method();
2652130809Smarcel      m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2653130809Smarcel    }
2654130809Smarcel  }
2655130809Smarcel
2656130809Smarcel  // Get rid of the osr methods for the same bci that have lower levels.
2657130809Smarcel  if (TieredCompilation) {
2658130809Smarcel    for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2659130809Smarcel      nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2660130809Smarcel      if (inv != NULL && inv->is_in_use()) {
2661130809Smarcel        inv->make_not_entrant();
2662130809Smarcel      }
2663130809Smarcel    }
2664130809Smarcel  }
2665130809Smarcel}
2666130809Smarcel
2667130809Smarcel
2668130809Smarcelvoid InstanceKlass::remove_osr_nmethod(nmethod* n) {
2669130809Smarcel  // This is a short non-blocking critical region, so the no safepoint check is ok.
2670130809Smarcel  MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
2671130809Smarcel  assert(n->is_osr_method(), "wrong kind of nmethod");
2672130809Smarcel  nmethod* last = NULL;
2673130809Smarcel  nmethod* cur  = osr_nmethods_head();
2674130809Smarcel  int max_level = CompLevel_none;  // Find the max comp level excluding n
2675130809Smarcel  Method* m = n->method();
2676130809Smarcel  // Search for match
2677130809Smarcel  while(cur != NULL && cur != n) {
2678130809Smarcel    if (TieredCompilation && m == cur->method()) {
2679130809Smarcel      // Find max level before n
2680130809Smarcel      max_level = MAX2(max_level, cur->comp_level());
2681130809Smarcel    }
2682130809Smarcel    last = cur;
2683130809Smarcel    cur = cur->osr_link();
2684130809Smarcel  }
2685130809Smarcel  nmethod* next = NULL;
2686130809Smarcel  if (cur == n) {
2687130809Smarcel    next = cur->osr_link();
2688130809Smarcel    if (last == NULL) {
2689130809Smarcel      // Remove first element
2690130809Smarcel      set_osr_nmethods_head(next);
2691130809Smarcel    } else {
2692130809Smarcel      last->set_osr_link(next);
2693130809Smarcel    }
269419370Spst  }
269519370Spst  n->set_osr_link(NULL);
269698948Sobrien  if (TieredCompilation) {
269798948Sobrien    cur = next;
269898948Sobrien    while (cur != NULL) {
269998948Sobrien      // Find max level after n
270019370Spst      if (m == cur->method()) {
270198948Sobrien        max_level = MAX2(max_level, cur->comp_level());
270219370Spst      }
270319370Spst      cur = cur->osr_link();
270498948Sobrien    }
270519370Spst    m->set_highest_osr_comp_level(max_level);
270646289Sdfr  }
270719370Spst}
270846289Sdfr
270946289Sdfrint InstanceKlass::mark_osr_nmethods(const Method* m) {
271019370Spst  // This is a short non-blocking critical region, so the no safepoint check is ok.
271146289Sdfr  MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
271246289Sdfr  nmethod* osr = osr_nmethods_head();
271319370Spst  int found = 0;
271446289Sdfr  while (osr != NULL) {
271598948Sobrien    assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
271646289Sdfr    if (osr->method() == m) {
271746289Sdfr      osr->mark_for_deoptimization();
271846289Sdfr      found++;
271946289Sdfr    }
272019370Spst    osr = osr->osr_link();
2721130809Smarcel  }
272298948Sobrien  return found;
272346289Sdfr}
272446289Sdfr
272519370Spstnmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
272619370Spst  // This is a short non-blocking critical region, so the no safepoint check is ok.
272719370Spst  MutexLockerEx ml(OsrList_lock, Mutex::_no_safepoint_check_flag);
272819370Spst  nmethod* osr = osr_nmethods_head();
272919370Spst  nmethod* best = NULL;
273019370Spst  while (osr != NULL) {
273119370Spst    assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
273219370Spst    // There can be a time when a c1 osr method exists but we are waiting
273319370Spst    // for a c2 version. When c2 completes its osr nmethod we will trash
273446289Sdfr    // the c1 version and only be able to find the c2 version. However
273519370Spst    // while we overflow in the c1 code at back branches we don't want to
273619370Spst    // try and switch to the same code as we are already running
273719370Spst
273898948Sobrien    if (osr->method() == m &&
273998948Sobrien        (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
274019370Spst      if (match_level) {
274119370Spst        if (osr->comp_level() == comp_level) {
274219370Spst          // Found a match - return it.
274346289Sdfr          return osr;
274446289Sdfr        }
274519370Spst      } else {
274619370Spst        if (best == NULL || (osr->comp_level() > best->comp_level())) {
274746289Sdfr          if (osr->comp_level() == CompLevel_highest_tier) {
274846289Sdfr            // Found the best possible - return it.
274946289Sdfr            return osr;
275046289Sdfr          }
275146289Sdfr          best = osr;
275246289Sdfr        }
275346289Sdfr      }
275446289Sdfr    }
275546289Sdfr    osr = osr->osr_link();
2756130809Smarcel  }
275746289Sdfr  if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
2758130809Smarcel    return best;
275946289Sdfr  }
276046289Sdfr  return NULL;
276146289Sdfr}
276246289Sdfr
276398948Sobrienbool InstanceKlass::add_member_name(Handle mem_name) {
276498948Sobrien  jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
276598948Sobrien  MutexLocker ml(MemberNameTable_lock);
276698948Sobrien  DEBUG_ONLY(No_Safepoint_Verifier nsv);
276798948Sobrien
276898948Sobrien  // Check if method has been redefined while taking out MemberNameTable_lock, if so
276998948Sobrien  // return false.  We cannot cache obsolete methods. They will crash when the function
277098948Sobrien  // is called!
277198948Sobrien  Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name());
277298948Sobrien  if (method->is_obsolete()) {
277398948Sobrien    return false;
277498948Sobrien  } else if (method->is_old()) {
277598948Sobrien    // Replace method with redefined version
277698948Sobrien    java_lang_invoke_MemberName::set_vmtarget(mem_name(), method_with_idnum(method->method_idnum()));
277798948Sobrien  }
277898948Sobrien
277998948Sobrien  if (_member_names == NULL) {
278098948Sobrien    _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
278198948Sobrien  }
278298948Sobrien  _member_names->add_member_name(mem_name_wref);
278398948Sobrien  return true;
278498948Sobrien}
278598948Sobrien
278698948Sobrien// -----------------------------------------------------------------------------------------------------
278798948Sobrien// Printing
278898948Sobrien
278998948Sobrien#ifndef PRODUCT
279098948Sobrien
279198948Sobrien#define BULLET  " - "
279298948Sobrien
279398948Sobrienstatic const char* state_names[] = {
279498948Sobrien  "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
279598948Sobrien};
279698948Sobrien
279798948Sobrienstatic void print_vtable(intptr_t* start, int len, outputStream* st) {
279898948Sobrien  for (int i = 0; i < len; i++) {
279998948Sobrien    intptr_t e = start[i];
280098948Sobrien    st->print("%d : " INTPTR_FORMAT, i, e);
280198948Sobrien    if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
280298948Sobrien      st->print(" ");
280398948Sobrien      ((Metadata*)e)->print_value_on(st);
280498948Sobrien    }
280598948Sobrien    st->cr();
280646289Sdfr  }
280746289Sdfr}
280846289Sdfr
280946289Sdfrvoid InstanceKlass::print_on(outputStream* st) const {
281098948Sobrien  assert(is_klass(), "must be klass");
281146289Sdfr  Klass::print_on(st);
281246289Sdfr
281398948Sobrien  st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
281498948Sobrien  st->print(BULLET"klass size:        %d", size());                               st->cr();
281598948Sobrien  st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
281698948Sobrien  st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
281798948Sobrien  st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
281898948Sobrien  st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
281998948Sobrien  st->print(BULLET"sub:               ");
282098948Sobrien  Klass* sub = subklass();
282198948Sobrien  int n;
282298948Sobrien  for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
282319370Spst    if (n < MaxSubklassPrintSize) {
282419370Spst      sub->print_value_on(st);
282519370Spst      st->print("   ");
282646289Sdfr    }
282719370Spst  }
282819370Spst  if (n >= MaxSubklassPrintSize) st->print("(" INTX_FORMAT " more klasses...)", n - MaxSubklassPrintSize);
282919370Spst  st->cr();
283019370Spst
283119370Spst  if (is_interface()) {
283219370Spst    st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
283319370Spst    if (nof_implementors() == 1) {
283498948Sobrien      st->print_cr(BULLET"implementor:    ");
283598948Sobrien      st->print("   ");
283698948Sobrien      implementor()->print_value_on(st);
283798948Sobrien      st->cr();
283898948Sobrien    }
283998948Sobrien  }
284098948Sobrien
284198948Sobrien  st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
284298948Sobrien  st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
284398948Sobrien  if (Verbose || WizardMode) {
284498948Sobrien    Array<Method*>* method_array = methods();
284519370Spst    for (int i = 0; i < method_array->length(); i++) {
284619370Spst      st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
2847130809Smarcel    }
2848130809Smarcel  }
284998948Sobrien  st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
285046289Sdfr  st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
285198948Sobrien  if (Verbose && default_methods() != NULL) {
285219370Spst    Array<Method*>* method_array = default_methods();
285346289Sdfr    for (int i = 0; i < method_array->length(); i++) {
285419370Spst      st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
285546289Sdfr    }
285698948Sobrien  }
285746289Sdfr  if (default_vtable_indices() != NULL) {
285819370Spst    st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
285919370Spst  }
286019370Spst  st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
286146289Sdfr  st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
286246289Sdfr  st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
286346289Sdfr  if (class_loader_data() != NULL) {
286446289Sdfr    st->print(BULLET"class loader data:  ");
286546289Sdfr    class_loader_data()->print_value_on(st);
286698948Sobrien    st->cr();
286746289Sdfr  }
286846289Sdfr  st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
286946289Sdfr  if (source_file_name() != NULL) {
287098948Sobrien    st->print(BULLET"source file:       ");
287146289Sdfr    source_file_name()->print_value_on(st);
287246289Sdfr    st->cr();
287346289Sdfr  }
287446289Sdfr  if (source_debug_extension() != NULL) {
287546289Sdfr    st->print(BULLET"source debug extension:       ");
287646289Sdfr    st->print("%s", source_debug_extension());
287746289Sdfr    st->cr();
287846289Sdfr  }
287946289Sdfr  st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
288046289Sdfr  st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
288146289Sdfr  st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
288246289Sdfr  st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
288346289Sdfr  {
288446289Sdfr    bool have_pv = false;
288546289Sdfr    // previous versions are linked together through the InstanceKlass
288646289Sdfr    for (InstanceKlass* pv_node = _previous_versions;
288746289Sdfr         pv_node != NULL;
288846289Sdfr         pv_node = pv_node->previous_versions()) {
288946289Sdfr      if (!have_pv)
289046289Sdfr        st->print(BULLET"previous version:  ");
289146289Sdfr      have_pv = true;
289246289Sdfr      pv_node->constants()->print_value_on(st);
289346289Sdfr    }
289446289Sdfr    if (have_pv) st->cr();
289519370Spst  }
289619370Spst
289746289Sdfr  if (generic_signature() != NULL) {
289846289Sdfr    st->print(BULLET"generic signature: ");
289946289Sdfr    generic_signature()->print_value_on(st);
290019370Spst    st->cr();
290146289Sdfr  }
290219370Spst  st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
290346289Sdfr  st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
290446289Sdfr  st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), p2i(start_of_vtable())); st->cr();
290598948Sobrien  if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
290646289Sdfr  st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), p2i(start_of_itable())); st->cr();
290746289Sdfr  if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
290819370Spst  st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
290919370Spst  FieldPrinter print_static_field(st);
291019370Spst  ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
291119370Spst  st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
291219370Spst  FieldPrinter print_nonstatic_field(st);
291346289Sdfr  ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
291446289Sdfr
291546289Sdfr  st->print(BULLET"non-static oop maps: ");
291646289Sdfr  OopMapBlock* map     = start_of_nonstatic_oop_maps();
291746289Sdfr  OopMapBlock* end_map = map + nonstatic_oop_map_count();
291819370Spst  while (map < end_map) {
291919370Spst    st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
292019370Spst    map++;
292119370Spst  }
292219370Spst  st->cr();
292319370Spst}
292419370Spst
292519370Spst#endif //PRODUCT
292619370Spst
292719370Spstvoid InstanceKlass::print_value_on(outputStream* st) const {
292819370Spst  assert(is_klass(), "must be klass");
292919370Spst  if (Verbose || WizardMode)  access_flags().print_on(st);
293019370Spst  name()->print_value_on(st);
293119370Spst}
293219370Spst
293319370Spst#ifndef PRODUCT
293419370Spst
293598948Sobrienvoid FieldPrinter::do_field(fieldDescriptor* fd) {
293619370Spst  _st->print(BULLET);
293719370Spst   if (_obj == NULL) {
293819370Spst     fd->print_on(_st);
2939130809Smarcel     _st->cr();
294019370Spst   } else {
294198948Sobrien     fd->print_on_for(_st, _obj);
294298948Sobrien     _st->cr();
2943130809Smarcel   }
294419370Spst}
294519370Spst
294619370Spst
294719370Spstvoid InstanceKlass::oop_print_on(oop obj, outputStream* st) {
294819370Spst  Klass::oop_print_on(obj, st);
294919370Spst
295019370Spst  if (this == SystemDictionary::String_klass()) {
295119370Spst    typeArrayOop value  = java_lang_String::value(obj);
295219370Spst    juint        offset = java_lang_String::offset(obj);
295319370Spst    juint        length = java_lang_String::length(obj);
295419370Spst    if (value != NULL &&
295519370Spst        value->is_typeArray() &&
295646289Sdfr        offset          <= (juint) value->length() &&
295798948Sobrien        offset + length <= (juint) value->length()) {
295819370Spst      st->print(BULLET"string: ");
295919370Spst      java_lang_String::print(obj, st);
296046289Sdfr      st->cr();
296146289Sdfr      if (!WizardMode)  return;  // that is enough
296246289Sdfr    }
296346289Sdfr  }
296446289Sdfr
296546289Sdfr  st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
296619370Spst  FieldPrinter print_field(st, obj);
296719370Spst  do_nonstatic_fields(&print_field);
296819370Spst
296946289Sdfr  if (this == SystemDictionary::Class_klass()) {
297046289Sdfr    st->print(BULLET"signature: ");
297119370Spst    java_lang_Class::print_signature(obj, st);
297219370Spst    st->cr();
297319370Spst    Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
297419370Spst    st->print(BULLET"fake entry for mirror: ");
297519370Spst    mirrored_klass->print_value_on_maybe_null(st);
297619370Spst    st->cr();
297746289Sdfr    Klass* array_klass = java_lang_Class::array_klass(obj);
297819370Spst    st->print(BULLET"fake entry for array: ");
297919370Spst    array_klass->print_value_on_maybe_null(st);
298019370Spst    st->cr();
298119370Spst    st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
298219370Spst    st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
298319370Spst    Klass* real_klass = java_lang_Class::as_Klass(obj);
298419370Spst    if (real_klass != NULL && real_klass->oop_is_instance()) {
298519370Spst      InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
298619370Spst    }
298719370Spst  } else if (this == SystemDictionary::MethodType_klass()) {
298819370Spst    st->print(BULLET"signature: ");
298919370Spst    java_lang_invoke_MethodType::print_signature(obj, st);
299019370Spst    st->cr();
299119370Spst  }
299219370Spst}
299319370Spst
299498948Sobrien#endif //PRODUCT
299598948Sobrien
299698948Sobrienvoid InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
299798948Sobrien  st->print("a ");
299846289Sdfr  name()->print_value_on(st);
299946289Sdfr  obj->print_address_on(st);
300019370Spst  if (this == SystemDictionary::String_klass()
300119370Spst      && java_lang_String::value(obj) != NULL) {
300298948Sobrien    ResourceMark rm;
300319370Spst    int len = java_lang_String::length(obj);
300419370Spst    int plen = (len < 24 ? len : 12);
300519370Spst    char* str = java_lang_String::as_utf8_string(obj, 0, plen);
300619370Spst    st->print(" = \"%s\"", str);
300746289Sdfr    if (len > plen)
300846289Sdfr      st->print("...[%d]", len);
300946289Sdfr  } else if (this == SystemDictionary::Class_klass()) {
301046289Sdfr    Klass* k = java_lang_Class::as_Klass(obj);
301119370Spst    st->print(" = ");
301246289Sdfr    if (k != NULL) {
301346289Sdfr      k->print_value_on(st);
301446289Sdfr    } else {
301546289Sdfr      const char* tname = type2name(java_lang_Class::primitive_type(obj));
301646289Sdfr      st->print("%s", tname ? tname : "type?");
301719370Spst    }
301846289Sdfr  } else if (this == SystemDictionary::MethodType_klass()) {
301946289Sdfr    st->print(" = ");
302019370Spst    java_lang_invoke_MethodType::print_signature(obj, st);
302119370Spst  } else if (java_lang_boxing_object::is_instance(obj)) {
302219370Spst    st->print(" = ");
302319370Spst    java_lang_boxing_object::print(obj, st);
302419370Spst  } else if (this == SystemDictionary::LambdaForm_klass()) {
302519370Spst    oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
302619370Spst    if (vmentry != NULL) {
302719370Spst      st->print(" => ");
302819370Spst      vmentry->print_value_on(st);
302998948Sobrien    }
303019370Spst  } else if (this == SystemDictionary::MemberName_klass()) {
303119370Spst    Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
303298948Sobrien    if (vmtarget != NULL) {
303398948Sobrien      st->print(" = ");
303419370Spst      vmtarget->print_value_on(st);
303519370Spst    } else {
303646289Sdfr      java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
303746289Sdfr      st->print(".");
303819370Spst      java_lang_invoke_MemberName::name(obj)->print_value_on(st);
303919370Spst    }
304019370Spst  }
304119370Spst}
304298948Sobrien
304398948Sobrienconst char* InstanceKlass::internal_name() const {
304419370Spst  return external_name();
304519370Spst}
304619370Spst
304719370Spst#if INCLUDE_SERVICES
304819370Spst// Size Statistics
304919370Spstvoid InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
305019370Spst  Klass::collect_statistics(sz);
305119370Spst
305298948Sobrien  sz->_inst_size  = HeapWordSize * size_helper();
305319370Spst  sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
305419370Spst  sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
305519370Spst  sz->_nonstatic_oopmap_bytes = HeapWordSize *
305698948Sobrien        ((is_interface() || is_anonymous()) ?
305719370Spst         align_object_offset(nonstatic_oop_map_size()) :
305819370Spst         nonstatic_oop_map_size());
305919370Spst
306098948Sobrien  int n = 0;
306119370Spst  n += (sz->_methods_array_bytes         = sz->count_array(methods()));
306219370Spst  n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
306319370Spst  n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
306419370Spst  n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
306598948Sobrien  n += (sz->_fields_bytes                = sz->count_array(fields()));
306698948Sobrien  n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
306719370Spst  sz->_ro_bytes += n;
306819370Spst
306919370Spst  const ConstantPool* cp = constants();
307019370Spst  if (cp) {
307119370Spst    cp->collect_statistics(sz);
307219370Spst  }
307319370Spst
307419370Spst  const Annotations* anno = annotations();
307598948Sobrien  if (anno) {
307619370Spst    anno->collect_statistics(sz);
307719370Spst  }
307819370Spst
307919370Spst  const Array<Method*>* methods_array = methods();
308019370Spst  if (methods()) {
308198948Sobrien    for (int i = 0; i < methods_array->length(); i++) {
308219370Spst      Method* method = methods_array->at(i);
308319370Spst      if (method) {
308419370Spst        sz->_method_count ++;
308519370Spst        method->collect_statistics(sz);
308619370Spst      }
308719370Spst    }
308819370Spst  }
308919370Spst}
309019370Spst#endif // INCLUDE_SERVICES
309119370Spst
309219370Spst// Verification
309319370Spst
309419370Spstclass VerifyFieldClosure: public OopClosure {
309519370Spst protected:
309619370Spst  template <class T> void do_oop_work(T* p) {
309719370Spst    oop obj = oopDesc::load_decode_heap_oop(p);
309819370Spst    if (!obj->is_oop_or_null()) {
309919370Spst      tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p2i(p), p2i(obj));
310019370Spst      Universe::print();
310119370Spst      guarantee(false, "boom");
310219370Spst    }
310319370Spst  }
310419370Spst public:
310519370Spst  virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
310619370Spst  virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
310719370Spst};
310898948Sobrien
310998948Sobrienvoid InstanceKlass::verify_on(outputStream* st) {
311019370Spst#ifndef PRODUCT
311119370Spst  // Avoid redundant verifies, this really should be in product.
311219370Spst  if (_verify_count == Universe::verify_count()) return;
311319370Spst  _verify_count = Universe::verify_count();
311419370Spst#endif
311519370Spst
311646289Sdfr  // Verify Klass
311798948Sobrien  Klass::verify_on(st);
311846289Sdfr
311946289Sdfr  // Verify that klass is present in ClassLoaderData
312046289Sdfr  guarantee(class_loader_data()->contains_klass(this),
312146289Sdfr            "this class isn't found in class loader data");
312219370Spst
312319370Spst  // Verify vtables
312419370Spst  if (is_linked()) {
312519370Spst    ResourceMark rm;
312646289Sdfr    // $$$ This used to be done only for m/s collections.  Doing it
312746289Sdfr    // always seemed a valid generalization.  (DLD -- 6/00)
312846289Sdfr    vtable()->verify(st);
312946289Sdfr  }
313046289Sdfr
313146289Sdfr  // Verify first subklass
313298948Sobrien  if (subklass() != NULL) {
313398948Sobrien    guarantee(subklass()->is_klass(), "should be klass");
313498948Sobrien  }
313598948Sobrien
3136130809Smarcel  // Verify siblings
313798948Sobrien  Klass* super = this->super();
3138130809Smarcel  Klass* sib = next_sibling();
313998948Sobrien  if (sib != NULL) {
314098948Sobrien    if (sib == this) {
314119370Spst      fatal("subclass points to itself " PTR_FORMAT, p2i(sib));
314219370Spst    }
314398948Sobrien
314498948Sobrien    guarantee(sib->is_klass(), "should be klass");
314519370Spst    guarantee(sib->super() == super, "siblings should have same superklass");
314619370Spst  }
314719370Spst
314819370Spst  // Verify implementor fields
314919370Spst  Klass* im = implementor();
315019370Spst  if (im != NULL) {
315119370Spst    guarantee(is_interface(), "only interfaces should have implementor set");
315219370Spst    guarantee(im->is_klass(), "should be klass");
315319370Spst    guarantee(!im->is_interface() || im == this,
315419370Spst      "implementors cannot be interfaces");
315519370Spst  }
315619370Spst
315719370Spst  // Verify local interfaces
315819370Spst  if (local_interfaces()) {
315919370Spst    Array<Klass*>* local_interfaces = this->local_interfaces();
316019370Spst    for (int j = 0; j < local_interfaces->length(); j++) {
316119370Spst      Klass* e = local_interfaces->at(j);
316219370Spst      guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
316319370Spst    }
316419370Spst  }
316519370Spst
316619370Spst  // Verify transitive interfaces
316719370Spst  if (transitive_interfaces() != NULL) {
316819370Spst    Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
316919370Spst    for (int j = 0; j < transitive_interfaces->length(); j++) {
317019370Spst      Klass* e = transitive_interfaces->at(j);
317119370Spst      guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
317219370Spst    }
317319370Spst  }
317419370Spst
317519370Spst  // Verify methods
317619370Spst  if (methods() != NULL) {
317719370Spst    Array<Method*>* methods = this->methods();
317819370Spst    for (int j = 0; j < methods->length(); j++) {
317919370Spst      guarantee(methods->at(j)->is_method(), "non-method in methods array");
318019370Spst    }
318119370Spst    for (int j = 0; j < methods->length() - 1; j++) {
318219370Spst      Method* m1 = methods->at(j);
318319370Spst      Method* m2 = methods->at(j + 1);
318419370Spst      guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
318519370Spst    }
318619370Spst  }
318719370Spst
318819370Spst  // Verify method ordering
318946289Sdfr  if (method_ordering() != NULL) {
319046289Sdfr    Array<int>* method_ordering = this->method_ordering();
319146289Sdfr    int length = method_ordering->length();
319298948Sobrien    if (JvmtiExport::can_maintain_original_method_order() ||
319319370Spst        ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
319419370Spst      guarantee(length == methods()->length(), "invalid method ordering length");
319519370Spst      jlong sum = 0;
319646289Sdfr      for (int j = 0; j < length; j++) {
319746289Sdfr        int original_index = method_ordering->at(j);
319846289Sdfr        guarantee(original_index >= 0, "invalid method ordering index");
319946289Sdfr        guarantee(original_index < length, "invalid method ordering index");
320019370Spst        sum += original_index;
320119370Spst      }
320219370Spst      // Verify sum of indices 0,1,...,length-1
320319370Spst      guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
320419370Spst    } else {
320519370Spst      guarantee(length == 0, "invalid method ordering length");
320619370Spst    }
320719370Spst  }
320819370Spst
320919370Spst  // Verify default methods
321019370Spst  if (default_methods() != NULL) {
321119370Spst    Array<Method*>* methods = this->default_methods();
321219370Spst    for (int j = 0; j < methods->length(); j++) {
321319370Spst      guarantee(methods->at(j)->is_method(), "non-method in methods array");
321419370Spst    }
321546289Sdfr    for (int j = 0; j < methods->length() - 1; j++) {
321646289Sdfr      Method* m1 = methods->at(j);
321719370Spst      Method* m2 = methods->at(j + 1);
321819370Spst      guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
321919370Spst    }
322019370Spst  }
322119370Spst
322219370Spst  // Verify JNI static field identifiers
322319370Spst  if (jni_ids() != NULL) {
322419370Spst    jni_ids()->verify(this);
322519370Spst  }
322619370Spst
322719370Spst  // Verify other fields
322819370Spst  if (array_klasses() != NULL) {
322919370Spst    guarantee(array_klasses()->is_klass(), "should be klass");
323019370Spst  }
323119370Spst  if (constants() != NULL) {
323219370Spst    guarantee(constants()->is_constantPool(), "should be constant pool");
323319370Spst  }
323419370Spst  const Klass* host = host_klass();
323519370Spst  if (host != NULL) {
323619370Spst    guarantee(host->is_klass(), "should be klass");
323719370Spst  }
323819370Spst}
323919370Spst
324019370Spstvoid InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
324119370Spst  Klass::oop_verify_on(obj, st);
324219370Spst  VerifyFieldClosure blk;
324319370Spst  obj->oop_iterate_no_header(&blk);
324419370Spst}
324519370Spst
324619370Spst
3247130809Smarcel// JNIid class for jfieldIDs only
324819370Spst// Note to reviewers:
324919370Spst// These JNI functions are just moved over to column 1 and not changed
325019370Spst// in the compressed oops workspace.
325119370SpstJNIid::JNIid(Klass* holder, int offset, JNIid* next) {
325219370Spst  _holder = holder;
325319370Spst  _offset = offset;
3254130809Smarcel  _next = next;
325519370Spst  debug_only(_is_static_field_id = false;)
325619370Spst}
325719370Spst
325819370Spst
325919370SpstJNIid* JNIid::find(int offset) {
326019370Spst  JNIid* current = this;
326119370Spst  while (current != NULL) {
326219370Spst    if (current->offset() == offset) return current;
326319370Spst    current = current->next();
3264130809Smarcel  }
326519370Spst  return NULL;
326619370Spst}
326719370Spst
326819370Spstvoid JNIid::deallocate(JNIid* current) {
326919370Spst  while (current != NULL) {
327019370Spst    JNIid* next = current->next();
3271130809Smarcel    delete current;
327219370Spst    current = next;
327398948Sobrien  }
327419370Spst}
327519370Spst
327619370Spst
327719370Spstvoid JNIid::verify(Klass* holder) {
3278130809Smarcel  int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3279130809Smarcel  int end_field_offset;
328019370Spst  end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
328119370Spst
328219370Spst  JNIid* current = this;
328319370Spst  while (current != NULL) {
328419370Spst    guarantee(current->holder() == holder, "Invalid klass in JNIid");
328519370Spst#ifdef ASSERT
328619370Spst    int o = current->offset();
328719370Spst    if (current->is_static_field_id()) {
328819370Spst      guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
328919370Spst    }
329019370Spst#endif
329119370Spst    current = current->next();
329219370Spst  }
329319370Spst}
329419370Spst
329519370Spst
329619370Spst#ifdef ASSERT
329719370Spstvoid InstanceKlass::set_init_state(ClassState state) {
329819370Spst  bool good_state = is_shared() ? (_init_state <= state)
329946289Sdfr                                               : (_init_state < state);
330019370Spst  assert(good_state || state == allocated, "illegal state transition");
330119370Spst  _init_state = (u1)state;
330219370Spst}
330319370Spst#endif
330419370Spst
330519370Spst
330619370Spst
330719370Spst// RedefineClasses() support for previous versions:
330819370Spstint InstanceKlass::_previous_version_count = 0;
330919370Spst
331019370Spst// Purge previous versions before adding new previous versions of the class.
331119370Spstvoid InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
331219370Spst  if (ik->previous_versions() != NULL) {
331319370Spst    // This klass has previous versions so see what we can cleanup
331419370Spst    // while it is safe to do so.
331519370Spst
331619370Spst    int deleted_count = 0;    // leave debugging breadcrumbs
331746289Sdfr    int live_count = 0;
331819370Spst    ClassLoaderData* loader_data = ik->class_loader_data();
331919370Spst    assert(loader_data != NULL, "should never be null");
332019370Spst
332198948Sobrien    // RC_TRACE macro has an embedded ResourceMark
332298948Sobrien    RC_TRACE(0x00000200, ("purge: %s: previous versions", ik->external_name()));
332319370Spst
332419370Spst    // previous versions are linked together through the InstanceKlass
332519370Spst    InstanceKlass* pv_node = ik->previous_versions();
332698948Sobrien    InstanceKlass* last = ik;
332798948Sobrien    int version = 0;
332898948Sobrien
332998948Sobrien    // check the previous versions list
333098948Sobrien    for (; pv_node != NULL; ) {
3331130809Smarcel
333298948Sobrien      ConstantPool* pvcp = pv_node->constants();
333398948Sobrien      assert(pvcp != NULL, "cp ref was unexpectedly cleared");
3334130809Smarcel
333598948Sobrien      if (!pvcp->on_stack()) {
333698948Sobrien        // If the constant pool isn't on stack, none of the methods
333798948Sobrien        // are executing.  Unlink this previous_version.
333898948Sobrien        // The previous version InstanceKlass is on the ClassLoaderData deallocate list
333998948Sobrien        // so will be deallocated during the next phase of class unloading.
334098948Sobrien        RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is dead",
334198948Sobrien                              p2i(pv_node)));
334298948Sobrien        // For debugging purposes.
334398948Sobrien        pv_node->set_is_scratch_class();
334498948Sobrien        pv_node->class_loader_data()->add_to_deallocate_list(pv_node);
334598948Sobrien        pv_node = pv_node->previous_versions();
334698948Sobrien        last->link_previous_versions(pv_node);
334798948Sobrien        deleted_count++;
334898948Sobrien        version++;
334998948Sobrien        continue;
335098948Sobrien      } else {
335198948Sobrien        RC_TRACE(0x00000200, ("purge: previous version " INTPTR_FORMAT " is alive",
335298948Sobrien                              p2i(pv_node)));
335319370Spst        assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
335419370Spst        guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
335598948Sobrien        live_count++;
335698948Sobrien      }
335798948Sobrien
335898948Sobrien      // At least one method is live in this previous version.
335998948Sobrien      // Reset dead EMCP methods not to get breakpoints.
336098948Sobrien      // All methods are deallocated when all of the methods for this class are no
336198948Sobrien      // longer running.
336298948Sobrien      Array<Method*>* method_refs = pv_node->methods();
336398948Sobrien      if (method_refs != NULL) {
336498948Sobrien        RC_TRACE(0x00000200, ("purge: previous methods length=%d",
336598948Sobrien          method_refs->length()));
336698948Sobrien        for (int j = 0; j < method_refs->length(); j++) {
336798948Sobrien          Method* method = method_refs->at(j);
336898948Sobrien
336998948Sobrien          if (!method->on_stack()) {
337098948Sobrien            // no breakpoints for non-running methods
337198948Sobrien            if (method->is_running_emcp()) {
337298948Sobrien              method->set_running_emcp(false);
3373130809Smarcel            }
3374130809Smarcel          } else {
3375130809Smarcel            assert (method->is_obsolete() || method->is_running_emcp(),
337698948Sobrien                    "emcp method cannot run after emcp bit is cleared");
3377130809Smarcel            // RC_TRACE macro has an embedded ResourceMark
3378130809Smarcel            RC_TRACE(0x00000200,
3379130809Smarcel              ("purge: %s(%s): prev method @%d in version @%d is alive",
3380130809Smarcel              method->name()->as_C_string(),
3381130809Smarcel              method->signature()->as_C_string(), j, version));
3382130809Smarcel          }
3383130809Smarcel        }
3384130809Smarcel      }
3385130809Smarcel      // next previous version
3386130809Smarcel      last = pv_node;
3387130809Smarcel      pv_node = pv_node->previous_versions();
3388130809Smarcel      version++;
3389130809Smarcel    }
3390130809Smarcel    RC_TRACE(0x00000200,
3391130809Smarcel      ("purge: previous version stats: live=%d, deleted=%d", live_count,
3392130809Smarcel      deleted_count));
3393130809Smarcel  }
3394130809Smarcel}
3395130809Smarcel
3396130809Smarcelvoid InstanceKlass::mark_newly_obsolete_methods(Array<Method*>* old_methods,
3397130809Smarcel                                                int emcp_method_count) {
3398130809Smarcel  int obsolete_method_count = old_methods->length() - emcp_method_count;
3399130809Smarcel
3400130809Smarcel  if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3401130809Smarcel      _previous_versions != NULL) {
3402130809Smarcel    // We have a mix of obsolete and EMCP methods so we have to
3403130809Smarcel    // clear out any matching EMCP method entries the hard way.
3404130809Smarcel    int local_count = 0;
3405130809Smarcel    for (int i = 0; i < old_methods->length(); i++) {
3406130809Smarcel      Method* old_method = old_methods->at(i);
3407130809Smarcel      if (old_method->is_obsolete()) {
3408130809Smarcel        // only obsolete methods are interesting
3409130809Smarcel        Symbol* m_name = old_method->name();
3410130809Smarcel        Symbol* m_signature = old_method->signature();
3411130809Smarcel
3412130809Smarcel        // previous versions are linked together through the InstanceKlass
3413130809Smarcel        int j = 0;
3414130809Smarcel        for (InstanceKlass* prev_version = _previous_versions;
3415130809Smarcel             prev_version != NULL;
3416130809Smarcel             prev_version = prev_version->previous_versions(), j++) {
3417130809Smarcel
3418130809Smarcel          Array<Method*>* method_refs = prev_version->methods();
3419130809Smarcel          for (int k = 0; k < method_refs->length(); k++) {
3420130809Smarcel            Method* method = method_refs->at(k);
3421130809Smarcel
3422130809Smarcel            if (!method->is_obsolete() &&
3423130809Smarcel                method->name() == m_name &&
3424130809Smarcel                method->signature() == m_signature) {
3425130809Smarcel              // The current RedefineClasses() call has made all EMCP
342698948Sobrien              // versions of this method obsolete so mark it as obsolete
342719370Spst              RC_TRACE(0x00000400,
342819370Spst                ("add: %s(%s): flush obsolete method @%d in version @%d",
342919370Spst                m_name->as_C_string(), m_signature->as_C_string(), k, j));
343019370Spst
343119370Spst              method->set_is_obsolete();
343219370Spst              break;
343319370Spst            }
343419370Spst          }
343519370Spst
343698948Sobrien          // The previous loop may not find a matching EMCP method, but
343798948Sobrien          // that doesn't mean that we can optimize and not go any
343898948Sobrien          // further back in the PreviousVersion generations. The EMCP
343998948Sobrien          // method for this generation could have already been made obsolete,
344019370Spst          // but there still may be an older EMCP method that has not
344119370Spst          // been made obsolete.
344219370Spst        }
344398948Sobrien
344498948Sobrien        if (++local_count >= obsolete_method_count) {
344519370Spst          // no more obsolete methods so bail out now
344619370Spst          break;
344719370Spst        }
344819370Spst      }
344919370Spst    }
345019370Spst  }
345119370Spst}
345219370Spst
345319370Spst// Save the scratch_class as the previous version if any of the methods are running.
345419370Spst// The previous_versions are used to set breakpoints in EMCP methods and they are
345519370Spst// also used to clean MethodData links to redefined methods that are no longer running.
345619370Spstvoid InstanceKlass::add_previous_version(instanceKlassHandle scratch_class,
345719370Spst                                         int emcp_method_count) {
345898948Sobrien  assert(Thread::current()->is_VM_thread(),
345998948Sobrien         "only VMThread can add previous versions");
346098948Sobrien
346198948Sobrien  // RC_TRACE macro has an embedded ResourceMark
346219370Spst  RC_TRACE(0x00000400, ("adding previous version ref for %s, EMCP_cnt=%d",
346319370Spst    scratch_class->external_name(), emcp_method_count));
346419370Spst
346519370Spst  // Clean out old previous versions
346619370Spst  purge_previous_versions(this);
346719370Spst
346819370Spst  // Mark newly obsolete methods in remaining previous versions.  An EMCP method from
346919370Spst  // a previous redefinition may be made obsolete by this redefinition.
347046289Sdfr  Array<Method*>* old_methods = scratch_class->methods();
347146289Sdfr  mark_newly_obsolete_methods(old_methods, emcp_method_count);
347246289Sdfr
347346289Sdfr  // If the constant pool for this previous version of the class
347446289Sdfr  // is not marked as being on the stack, then none of the methods
347519370Spst  // in this previous version of the class are on the stack so
347619370Spst  // we don't need to add this as a previous version.
347719370Spst  ConstantPool* cp_ref = scratch_class->constants();
347898948Sobrien  if (!cp_ref->on_stack()) {
347919370Spst    RC_TRACE(0x00000400, ("add: scratch class not added; no methods are running"));
348019370Spst    // For debugging purposes.
348119370Spst    scratch_class->set_is_scratch_class();
348219370Spst    scratch_class->class_loader_data()->add_to_deallocate_list(scratch_class());
348319370Spst    // Update count for class unloading.
348419370Spst    _previous_version_count--;
348519370Spst    return;
348619370Spst  }
348719370Spst
348819370Spst  if (emcp_method_count != 0) {
348919370Spst    // At least one method is still running, check for EMCP methods
349019370Spst    for (int i = 0; i < old_methods->length(); i++) {
349119370Spst      Method* old_method = old_methods->at(i);
349219370Spst      if (!old_method->is_obsolete() && old_method->on_stack()) {
349319370Spst        // if EMCP method (not obsolete) is on the stack, mark as EMCP so that
349419370Spst        // we can add breakpoints for it.
349519370Spst
349619370Spst        // We set the method->on_stack bit during safepoints for class redefinition
349719370Spst        // and use this bit to set the is_running_emcp bit.
349898948Sobrien        // After the safepoint, the on_stack bit is cleared and the running emcp
349998948Sobrien        // method may exit.   If so, we would set a breakpoint in a method that
350098948Sobrien        // is never reached, but this won't be noticeable to the programmer.
350198948Sobrien        old_method->set_running_emcp(true);
350298948Sobrien        RC_TRACE(0x00000400, ("add: EMCP method %s is on_stack " INTPTR_FORMAT,
350398948Sobrien                              old_method->name_and_sig_as_C_string(), p2i(old_method)));
350419370Spst      } else if (!old_method->is_obsolete()) {
350598948Sobrien        RC_TRACE(0x00000400, ("add: EMCP method %s is NOT on_stack " INTPTR_FORMAT,
350698948Sobrien                              old_method->name_and_sig_as_C_string(), p2i(old_method)));
350798948Sobrien      }
350819370Spst    }
350998948Sobrien  }
351019370Spst
351119370Spst  // Add previous version if any methods are still running.
351219370Spst  RC_TRACE(0x00000400, ("add: scratch class added; one of its methods is on_stack"));
351398948Sobrien  assert(scratch_class->previous_versions() == NULL, "shouldn't have a previous version");
351498948Sobrien  scratch_class->link_previous_versions(previous_versions());
351519370Spst  link_previous_versions(scratch_class());
351619370Spst  // Update count for class unloading.
351798948Sobrien  _previous_version_count++;
351819370Spst} // end add_previous_version()
351919370Spst
352098948Sobrien
352198948SobrienMethod* InstanceKlass::method_with_idnum(int idnum) {
352298948Sobrien  Method* m = NULL;
352398948Sobrien  if (idnum < methods()->length()) {
352498948Sobrien    m = methods()->at(idnum);
352519370Spst  }
352619370Spst  if (m == NULL || m->method_idnum() != idnum) {
352719370Spst    for (int index = 0; index < methods()->length(); ++index) {
352819370Spst      m = methods()->at(index);
352919370Spst      if (m->method_idnum() == idnum) {
353019370Spst        return m;
353119370Spst      }
353219370Spst    }
353319370Spst    // None found, return null for the caller to handle.
353419370Spst    return NULL;
353519370Spst  }
353698948Sobrien  return m;
353798948Sobrien}
353898948Sobrien
353919370Spst
354098948SobrienMethod* InstanceKlass::method_with_orig_idnum(int idnum) {
354198948Sobrien  if (idnum >= methods()->length()) {
354298948Sobrien    return NULL;
354398948Sobrien  }
354498948Sobrien  Method* m = methods()->at(idnum);
354598948Sobrien  if (m != NULL && m->orig_method_idnum() == idnum) {
354698948Sobrien    return m;
354798948Sobrien  }
354898948Sobrien  // Obsolete method idnum does not match the original idnum
354998948Sobrien  for (int index = 0; index < methods()->length(); ++index) {
355098948Sobrien    m = methods()->at(index);
355198948Sobrien    if (m->orig_method_idnum() == idnum) {
355298948Sobrien      return m;
355398948Sobrien    }
355498948Sobrien  }
355598948Sobrien  // None found, return null for the caller to handle.
355698948Sobrien  return NULL;
355719370Spst}
355819370Spst
355919370Spst
356019370SpstMethod* InstanceKlass::method_with_orig_idnum(int idnum, int version) {
356119370Spst  InstanceKlass* holder = get_klass_version(version);
356219370Spst  if (holder == NULL) {
356319370Spst    return NULL; // The version of klass is gone, no method is found
356419370Spst  }
356519370Spst  Method* method = holder->method_with_orig_idnum(idnum);
356698948Sobrien  return method;
356719370Spst}
356846289Sdfr
356919370Spst
357019370Spstjint InstanceKlass::get_cached_class_file_len() {
357119370Spst  return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
357219370Spst}
357319370Spst
357419370Spstunsigned char * InstanceKlass::get_cached_class_file_bytes() {
357519370Spst  return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
357619370Spst}
357719370Spst
357819370Spst
357919370Spst/////////////// Unit tests ///////////////
358019370Spst
358119370Spst#ifndef PRODUCT
358219370Spst
358319370Spstclass TestNmethodBucketContext {
358419370Spst public:
358519370Spst  nmethod* _nmethodLast;
358619370Spst  nmethod* _nmethodMiddle;
358719370Spst  nmethod* _nmethodFirst;
358819370Spst
358919370Spst  nmethodBucket* _bucketLast;
359019370Spst  nmethodBucket* _bucketMiddle;
3591130809Smarcel  nmethodBucket* _bucketFirst;
359219370Spst
359319370Spst  nmethodBucket* _bucketList;
359419370Spst
359519370Spst  TestNmethodBucketContext() {
359619370Spst    CodeCache_lock->lock_without_safepoint_check();
3597130809Smarcel
359819370Spst    _nmethodLast   = reinterpret_cast<nmethod*>(0x8 * 0);
359919370Spst    _nmethodMiddle = reinterpret_cast<nmethod*>(0x8 * 1);
360019370Spst    _nmethodFirst  = reinterpret_cast<nmethod*>(0x8 * 2);
360119370Spst
360219370Spst    _bucketLast   = new nmethodBucket(_nmethodLast,   NULL);
360319370Spst    _bucketMiddle = new nmethodBucket(_nmethodMiddle, _bucketLast);
360419370Spst    _bucketFirst  = new nmethodBucket(_nmethodFirst,   _bucketMiddle);
360519370Spst
360619370Spst    _bucketList = _bucketFirst;
360719370Spst  }
360819370Spst
360919370Spst  ~TestNmethodBucketContext() {
361019370Spst    delete _bucketLast;
361119370Spst    delete _bucketMiddle;
361219370Spst    delete _bucketFirst;
361319370Spst
361419370Spst    CodeCache_lock->unlock();
361519370Spst  }
3616130809Smarcel};
3617130809Smarcel
3618130809Smarcelclass TestNmethodBucket {
3619130809Smarcel public:
3620130809Smarcel  static void testRemoveDependentNmethodFirstDeleteImmediately() {
3621130809Smarcel    TestNmethodBucketContext c;
3622130809Smarcel
3623130809Smarcel    nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodFirst, true /* delete */);
362419370Spst
3625130809Smarcel    assert(c._bucketList == c._bucketMiddle, "check");
3626130809Smarcel    assert(c._bucketList->next() == c._bucketLast, "check");
3627130809Smarcel    assert(c._bucketList->next()->next() == NULL, "check");
3628130809Smarcel
3629130809Smarcel    // Cleanup before context is deleted.
3630130809Smarcel    c._bucketFirst = NULL;
3631130809Smarcel  }
3632130809Smarcel
3633130809Smarcel  static void testRemoveDependentNmethodMiddleDeleteImmediately() {
3634130809Smarcel    TestNmethodBucketContext c;
3635130809Smarcel
3636130809Smarcel    nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodMiddle, true /* delete */);
3637130809Smarcel
3638130809Smarcel    assert(c._bucketList == c._bucketFirst, "check");
3639130809Smarcel    assert(c._bucketList->next() == c._bucketLast, "check");
3640130809Smarcel    assert(c._bucketList->next()->next() == NULL, "check");
3641130809Smarcel
3642130809Smarcel    // Cleanup before context is deleted.
3643130809Smarcel    c._bucketMiddle = NULL;
3644130809Smarcel  }
3645130809Smarcel
364619370Spst  static void testRemoveDependentNmethodLastDeleteImmediately() {
364798948Sobrien    TestNmethodBucketContext c;
364819370Spst
364998948Sobrien    nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodLast, true /* delete */);
365019370Spst
365119370Spst    assert(c._bucketList == c._bucketFirst, "check");
365219370Spst    assert(c._bucketList->next() == c._bucketMiddle, "check");
365319370Spst    assert(c._bucketList->next()->next() == NULL, "check");
365419370Spst
365519370Spst    // Cleanup before context is deleted.
365619370Spst    c._bucketLast = NULL;
365719370Spst  }
365819370Spst
365919370Spst  static void testRemoveDependentNmethodFirstDeleteDeferred() {
366019370Spst    TestNmethodBucketContext c;
366119370Spst
366298948Sobrien    nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodFirst, false /* delete */);
366319370Spst
366498948Sobrien    assert(c._bucketList                         == c._bucketFirst,  "check");
366519370Spst    assert(c._bucketList->next()                 == c._bucketMiddle, "check");
366619370Spst    assert(c._bucketList->next()->next()         == c._bucketLast,   "check");
366719370Spst    assert(c._bucketList->next()->next()->next() == NULL,            "check");
366819370Spst
366919370Spst    assert(c._bucketFirst->count()  == 0, "check");
367019370Spst    assert(c._bucketMiddle->count() == 1, "check");
367119370Spst    assert(c._bucketLast->count()   == 1, "check");
367298948Sobrien  }
367319370Spst
367419370Spst  static void testRemoveDependentNmethodMiddleDeleteDeferred() {
367519370Spst    TestNmethodBucketContext c;
367619370Spst
367719370Spst    nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodMiddle, false /* delete */);
367819370Spst
367998948Sobrien    assert(c._bucketList                         == c._bucketFirst,  "check");
368019370Spst    assert(c._bucketList->next()                 == c._bucketMiddle, "check");
368119370Spst    assert(c._bucketList->next()->next()         == c._bucketLast,   "check");
368219370Spst    assert(c._bucketList->next()->next()->next() == NULL,            "check");
368319370Spst
368419370Spst    assert(c._bucketFirst->count()  == 1, "check");
368519370Spst    assert(c._bucketMiddle->count() == 0, "check");
368619370Spst    assert(c._bucketLast->count()   == 1, "check");
368719370Spst  }
368898948Sobrien
368919370Spst  static void testRemoveDependentNmethodLastDeleteDeferred() {
369019370Spst    TestNmethodBucketContext c;
369119370Spst
369219370Spst    nmethodBucket::remove_dependent_nmethod(&c._bucketList, c._nmethodLast, false /* delete */);
369319370Spst
369419370Spst    assert(c._bucketList                         == c._bucketFirst,  "check");
369519370Spst    assert(c._bucketList->next()                 == c._bucketMiddle, "check");
369619370Spst    assert(c._bucketList->next()->next()         == c._bucketLast,   "check");
369719370Spst    assert(c._bucketList->next()->next()->next() == NULL,            "check");
369898948Sobrien
369998948Sobrien    assert(c._bucketFirst->count()  == 1, "check");
370098948Sobrien    assert(c._bucketMiddle->count() == 1, "check");
370119370Spst    assert(c._bucketLast->count()   == 0, "check");
370219370Spst  }
370319370Spst
370419370Spst  static void testRemoveDependentNmethodConvenienceFirst() {
370519370Spst    TestNmethodBucketContext c;
370619370Spst
370798948Sobrien    nmethodBucket::remove_dependent_nmethod(c._bucketList, c._nmethodFirst);
370819370Spst
370919370Spst    assert(c._bucketList                         == c._bucketFirst,  "check");
371019370Spst    assert(c._bucketList->next()                 == c._bucketMiddle, "check");
371119370Spst    assert(c._bucketList->next()->next()         == c._bucketLast,   "check");
371298948Sobrien    assert(c._bucketList->next()->next()->next() == NULL,            "check");
371319370Spst
371419370Spst    assert(c._bucketFirst->count()  == 0, "check");
371519370Spst    assert(c._bucketMiddle->count() == 1, "check");
371698948Sobrien    assert(c._bucketLast->count()   == 1, "check");
371798948Sobrien  }
371898948Sobrien
371998948Sobrien  static void testRemoveDependentNmethodConvenienceMiddle() {
372098948Sobrien    TestNmethodBucketContext c;
372119370Spst
372219370Spst    nmethodBucket::remove_dependent_nmethod(c._bucketList, c._nmethodMiddle);
372319370Spst
372419370Spst    assert(c._bucketList                         == c._bucketFirst,  "check");
372519370Spst    assert(c._bucketList->next()                 == c._bucketMiddle, "check");
372619370Spst    assert(c._bucketList->next()->next()         == c._bucketLast,   "check");
372719370Spst    assert(c._bucketList->next()->next()->next() == NULL,            "check");
372819370Spst
372919370Spst    assert(c._bucketFirst->count()  == 1, "check");
373019370Spst    assert(c._bucketMiddle->count() == 0, "check");
373119370Spst    assert(c._bucketLast->count()   == 1, "check");
373219370Spst  }
373319370Spst
373419370Spst  static void testRemoveDependentNmethodConvenienceLast() {
373519370Spst    TestNmethodBucketContext c;
373619370Spst
373719370Spst    nmethodBucket::remove_dependent_nmethod(c._bucketList, c._nmethodLast);
373819370Spst
373919370Spst    assert(c._bucketList                         == c._bucketFirst,  "check");
374019370Spst    assert(c._bucketList->next()                 == c._bucketMiddle, "check");
374119370Spst    assert(c._bucketList->next()->next()         == c._bucketLast,   "check");
374219370Spst    assert(c._bucketList->next()->next()->next() == NULL,            "check");
374319370Spst
374498948Sobrien    assert(c._bucketFirst->count()  == 1, "check");
374519370Spst    assert(c._bucketMiddle->count() == 1, "check");
374619370Spst    assert(c._bucketLast->count()   == 0, "check");
374798948Sobrien  }
374819370Spst
374919370Spst  static void testRemoveDependentNmethod() {
375098948Sobrien    testRemoveDependentNmethodFirstDeleteImmediately();
375119370Spst    testRemoveDependentNmethodMiddleDeleteImmediately();
375298948Sobrien    testRemoveDependentNmethodLastDeleteImmediately();
375319370Spst
375419370Spst    testRemoveDependentNmethodFirstDeleteDeferred();
375519370Spst    testRemoveDependentNmethodMiddleDeleteDeferred();
375698948Sobrien    testRemoveDependentNmethodLastDeleteDeferred();
375798948Sobrien
375819370Spst    testRemoveDependentNmethodConvenienceFirst();
375919370Spst    testRemoveDependentNmethodConvenienceMiddle();
376019370Spst    testRemoveDependentNmethodConvenienceLast();
376119370Spst  }
376219370Spst
376319370Spst  static void test() {
376498948Sobrien    testRemoveDependentNmethod();
376598948Sobrien  }
376698948Sobrien};
376798948Sobrien
376898948Sobrienvoid TestNmethodBucket_test() {
376919370Spst  TestNmethodBucket::test();
377019370Spst}
377119370Spst
377219370Spst#endif
377319370Spst