instanceKlass.cpp revision 6646:b596a1063e90
1/*
2 * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25#include "precompiled.hpp"
26#include "classfile/javaClasses.hpp"
27#include "classfile/systemDictionary.hpp"
28#include "classfile/verifier.hpp"
29#include "classfile/vmSymbols.hpp"
30#include "compiler/compileBroker.hpp"
31#include "gc_implementation/shared/markSweep.inline.hpp"
32#include "gc_interface/collectedHeap.inline.hpp"
33#include "interpreter/oopMapCache.hpp"
34#include "interpreter/rewriter.hpp"
35#include "jvmtifiles/jvmti.h"
36#include "memory/genOopClosures.inline.hpp"
37#include "memory/heapInspection.hpp"
38#include "memory/metadataFactory.hpp"
39#include "memory/oopFactory.hpp"
40#include "oops/fieldStreams.hpp"
41#include "oops/instanceClassLoaderKlass.hpp"
42#include "oops/instanceKlass.hpp"
43#include "oops/instanceMirrorKlass.hpp"
44#include "oops/instanceOop.hpp"
45#include "oops/klass.inline.hpp"
46#include "oops/method.hpp"
47#include "oops/oop.inline.hpp"
48#include "oops/symbol.hpp"
49#include "prims/jvmtiExport.hpp"
50#include "prims/jvmtiRedefineClassesTrace.hpp"
51#include "prims/jvmtiRedefineClasses.hpp"
52#include "prims/jvmtiThreadState.hpp"
53#include "prims/methodComparator.hpp"
54#include "runtime/atomic.inline.hpp"
55#include "runtime/fieldDescriptor.hpp"
56#include "runtime/handles.inline.hpp"
57#include "runtime/javaCalls.hpp"
58#include "runtime/mutexLocker.hpp"
59#include "runtime/orderAccess.inline.hpp"
60#include "runtime/thread.inline.hpp"
61#include "services/classLoadingService.hpp"
62#include "services/threadService.hpp"
63#include "utilities/dtrace.hpp"
64#include "utilities/macros.hpp"
65#if INCLUDE_ALL_GCS
66#include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
67#include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
68#include "gc_implementation/g1/g1OopClosures.inline.hpp"
69#include "gc_implementation/g1/g1RemSet.inline.hpp"
70#include "gc_implementation/g1/heapRegionSeq.inline.hpp"
71#include "gc_implementation/parNew/parOopClosures.inline.hpp"
72#include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp"
73#include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
74#include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
75#include "oops/oop.pcgc.inline.hpp"
76#endif // INCLUDE_ALL_GCS
77#ifdef COMPILER1
78#include "c1/c1_Compiler.hpp"
79#endif
80
81PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
82
83#ifdef DTRACE_ENABLED
84
85
86#define HOTSPOT_CLASS_INITIALIZATION_required HOTSPOT_CLASS_INITIALIZATION_REQUIRED
87#define HOTSPOT_CLASS_INITIALIZATION_recursive HOTSPOT_CLASS_INITIALIZATION_RECURSIVE
88#define HOTSPOT_CLASS_INITIALIZATION_concurrent HOTSPOT_CLASS_INITIALIZATION_CONCURRENT
89#define HOTSPOT_CLASS_INITIALIZATION_erroneous HOTSPOT_CLASS_INITIALIZATION_ERRONEOUS
90#define HOTSPOT_CLASS_INITIALIZATION_super__failed HOTSPOT_CLASS_INITIALIZATION_SUPER_FAILED
91#define HOTSPOT_CLASS_INITIALIZATION_clinit HOTSPOT_CLASS_INITIALIZATION_CLINIT
92#define HOTSPOT_CLASS_INITIALIZATION_error HOTSPOT_CLASS_INITIALIZATION_ERROR
93#define HOTSPOT_CLASS_INITIALIZATION_end HOTSPOT_CLASS_INITIALIZATION_END
94#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)          \
95  {                                                              \
96    char* data = NULL;                                           \
97    int len = 0;                                                 \
98    Symbol* name = (clss)->name();                               \
99    if (name != NULL) {                                          \
100      data = (char*)name->bytes();                               \
101      len = name->utf8_length();                                 \
102    }                                                            \
103    HOTSPOT_CLASS_INITIALIZATION_##type(                         \
104      data, len, (clss)->class_loader(), thread_type);           \
105  }
106
107#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait) \
108  {                                                              \
109    char* data = NULL;                                           \
110    int len = 0;                                                 \
111    Symbol* name = (clss)->name();                               \
112    if (name != NULL) {                                          \
113      data = (char*)name->bytes();                               \
114      len = name->utf8_length();                                 \
115    }                                                            \
116    HOTSPOT_CLASS_INITIALIZATION_##type(                         \
117      data, len, (clss)->class_loader(), thread_type, wait);     \
118  }
119
120#else //  ndef DTRACE_ENABLED
121
122#define DTRACE_CLASSINIT_PROBE(type, clss, thread_type)
123#define DTRACE_CLASSINIT_PROBE_WAIT(type, clss, thread_type, wait)
124
125#endif //  ndef DTRACE_ENABLED
126
127volatile int InstanceKlass::_total_instanceKlass_count = 0;
128
129InstanceKlass* InstanceKlass::allocate_instance_klass(
130                                              ClassLoaderData* loader_data,
131                                              int vtable_len,
132                                              int itable_len,
133                                              int static_field_size,
134                                              int nonstatic_oop_map_size,
135                                              ReferenceType rt,
136                                              AccessFlags access_flags,
137                                              Symbol* name,
138                                              Klass* super_klass,
139                                              bool is_anonymous,
140                                              TRAPS) {
141
142  int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
143                                 access_flags.is_interface(), is_anonymous);
144
145  // Allocation
146  InstanceKlass* ik;
147  if (rt == REF_NONE) {
148    if (name == vmSymbols::java_lang_Class()) {
149      ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
150        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
151        access_flags, is_anonymous);
152    } else if (name == vmSymbols::java_lang_ClassLoader() ||
153          (SystemDictionary::ClassLoader_klass_loaded() &&
154          super_klass != NULL &&
155          super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
156      ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
157        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
158        access_flags, is_anonymous);
159    } else {
160      // normal class
161      ik = new (loader_data, size, THREAD) InstanceKlass(
162        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
163        access_flags, is_anonymous);
164    }
165  } else {
166    // reference klass
167    ik = new (loader_data, size, THREAD) InstanceRefKlass(
168        vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
169        access_flags, is_anonymous);
170  }
171
172  // Check for pending exception before adding to the loader data and incrementing
173  // class count.  Can get OOM here.
174  if (HAS_PENDING_EXCEPTION) {
175    return NULL;
176  }
177
178  // Add all classes to our internal class loader list here,
179  // including classes in the bootstrap (NULL) class loader.
180  loader_data->add_class(ik);
181
182  Atomic::inc(&_total_instanceKlass_count);
183  return ik;
184}
185
186
187// copy method ordering from resource area to Metaspace
188void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
189  if (m != NULL) {
190    // allocate a new array and copy contents (memcpy?)
191    _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
192    for (int i = 0; i < m->length(); i++) {
193      _method_ordering->at_put(i, m->at(i));
194    }
195  } else {
196    _method_ordering = Universe::the_empty_int_array();
197  }
198}
199
200// create a new array of vtable_indices for default methods
201Array<int>* InstanceKlass::create_new_default_vtable_indices(int len, TRAPS) {
202  Array<int>* vtable_indices = MetadataFactory::new_array<int>(class_loader_data(), len, CHECK_NULL);
203  assert(default_vtable_indices() == NULL, "only create once");
204  set_default_vtable_indices(vtable_indices);
205  return vtable_indices;
206}
207
208InstanceKlass::InstanceKlass(int vtable_len,
209                             int itable_len,
210                             int static_field_size,
211                             int nonstatic_oop_map_size,
212                             ReferenceType rt,
213                             AccessFlags access_flags,
214                             bool is_anonymous) {
215  No_Safepoint_Verifier no_safepoint; // until k becomes parsable
216
217  int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
218                                   access_flags.is_interface(), is_anonymous);
219
220  set_vtable_length(vtable_len);
221  set_itable_length(itable_len);
222  set_static_field_size(static_field_size);
223  set_nonstatic_oop_map_size(nonstatic_oop_map_size);
224  set_access_flags(access_flags);
225  _misc_flags = 0;  // initialize to zero
226  set_is_anonymous(is_anonymous);
227  assert(size() == iksize, "wrong size for object");
228
229  set_array_klasses(NULL);
230  set_methods(NULL);
231  set_method_ordering(NULL);
232  set_default_methods(NULL);
233  set_default_vtable_indices(NULL);
234  set_local_interfaces(NULL);
235  set_transitive_interfaces(NULL);
236  init_implementor();
237  set_fields(NULL, 0);
238  set_constants(NULL);
239  set_class_loader_data(NULL);
240  set_source_file_name_index(0);
241  set_source_debug_extension(NULL, 0);
242  set_array_name(NULL);
243  set_inner_classes(NULL);
244  set_static_oop_field_count(0);
245  set_nonstatic_field_size(0);
246  set_is_marked_dependent(false);
247  set_init_state(InstanceKlass::allocated);
248  set_init_thread(NULL);
249  set_reference_type(rt);
250  set_oop_map_cache(NULL);
251  set_jni_ids(NULL);
252  set_osr_nmethods_head(NULL);
253  set_breakpoints(NULL);
254  init_previous_versions();
255  set_generic_signature_index(0);
256  release_set_methods_jmethod_ids(NULL);
257  set_annotations(NULL);
258  set_jvmti_cached_class_field_map(NULL);
259  set_initial_method_idnum(0);
260  _dependencies = NULL;
261  set_jvmti_cached_class_field_map(NULL);
262  set_cached_class_file(NULL);
263  set_initial_method_idnum(0);
264  set_minor_version(0);
265  set_major_version(0);
266  NOT_PRODUCT(_verify_count = 0;)
267
268  // initialize the non-header words to zero
269  intptr_t* p = (intptr_t*)this;
270  for (int index = InstanceKlass::header_size(); index < iksize; index++) {
271    p[index] = NULL_WORD;
272  }
273
274  // Set temporary value until parseClassFile updates it with the real instance
275  // size.
276  set_layout_helper(Klass::instance_layout_helper(0, true));
277}
278
279
280void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
281                                       Array<Method*>* methods) {
282  if (methods != NULL && methods != Universe::the_empty_method_array() &&
283      !methods->is_shared()) {
284    for (int i = 0; i < methods->length(); i++) {
285      Method* method = methods->at(i);
286      if (method == NULL) continue;  // maybe null if error processing
287      // Only want to delete methods that are not executing for RedefineClasses.
288      // The previous version will point to them so they're not totally dangling
289      assert (!method->on_stack(), "shouldn't be called with methods on stack");
290      MetadataFactory::free_metadata(loader_data, method);
291    }
292    MetadataFactory::free_array<Method*>(loader_data, methods);
293  }
294}
295
296void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
297                                          Klass* super_klass,
298                                          Array<Klass*>* local_interfaces,
299                                          Array<Klass*>* transitive_interfaces) {
300  // Only deallocate transitive interfaces if not empty, same as super class
301  // or same as local interfaces.  See code in parseClassFile.
302  Array<Klass*>* ti = transitive_interfaces;
303  if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
304    // check that the interfaces don't come from super class
305    Array<Klass*>* sti = (super_klass == NULL) ? NULL :
306                    InstanceKlass::cast(super_klass)->transitive_interfaces();
307    if (ti != sti && ti != NULL && !ti->is_shared()) {
308      MetadataFactory::free_array<Klass*>(loader_data, ti);
309    }
310  }
311
312  // local interfaces can be empty
313  if (local_interfaces != Universe::the_empty_klass_array() &&
314      local_interfaces != NULL && !local_interfaces->is_shared()) {
315    MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
316  }
317}
318
319// This function deallocates the metadata and C heap pointers that the
320// InstanceKlass points to.
321void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
322
323  // Orphan the mirror first, CMS thinks it's still live.
324  if (java_mirror() != NULL) {
325    java_lang_Class::set_klass(java_mirror(), NULL);
326  }
327
328  // Need to take this class off the class loader data list.
329  loader_data->remove_class(this);
330
331  // The array_klass for this class is created later, after error handling.
332  // For class redefinition, we keep the original class so this scratch class
333  // doesn't have an array class.  Either way, assert that there is nothing
334  // to deallocate.
335  assert(array_klasses() == NULL, "array classes shouldn't be created for this class yet");
336
337  // Release C heap allocated data that this might point to, which includes
338  // reference counting symbol names.
339  release_C_heap_structures();
340
341  deallocate_methods(loader_data, methods());
342  set_methods(NULL);
343
344  if (method_ordering() != NULL &&
345      method_ordering() != Universe::the_empty_int_array() &&
346      !method_ordering()->is_shared()) {
347    MetadataFactory::free_array<int>(loader_data, method_ordering());
348  }
349  set_method_ordering(NULL);
350
351  // default methods can be empty
352  if (default_methods() != NULL &&
353      default_methods() != Universe::the_empty_method_array() &&
354      !default_methods()->is_shared()) {
355    MetadataFactory::free_array<Method*>(loader_data, default_methods());
356  }
357  // Do NOT deallocate the default methods, they are owned by superinterfaces.
358  set_default_methods(NULL);
359
360  // default methods vtable indices can be empty
361  if (default_vtable_indices() != NULL &&
362      !default_vtable_indices()->is_shared()) {
363    MetadataFactory::free_array<int>(loader_data, default_vtable_indices());
364  }
365  set_default_vtable_indices(NULL);
366
367
368  // This array is in Klass, but remove it with the InstanceKlass since
369  // this place would be the only caller and it can share memory with transitive
370  // interfaces.
371  if (secondary_supers() != NULL &&
372      secondary_supers() != Universe::the_empty_klass_array() &&
373      secondary_supers() != transitive_interfaces() &&
374      !secondary_supers()->is_shared()) {
375    MetadataFactory::free_array<Klass*>(loader_data, secondary_supers());
376  }
377  set_secondary_supers(NULL);
378
379  deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
380  set_transitive_interfaces(NULL);
381  set_local_interfaces(NULL);
382
383  if (fields() != NULL && !fields()->is_shared()) {
384    MetadataFactory::free_array<jushort>(loader_data, fields());
385  }
386  set_fields(NULL, 0);
387
388  // If a method from a redefined class is using this constant pool, don't
389  // delete it, yet.  The new class's previous version will point to this.
390  if (constants() != NULL) {
391    assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
392    if (!constants()->is_shared()) {
393      MetadataFactory::free_metadata(loader_data, constants());
394    }
395    set_constants(NULL);
396  }
397
398  if (inner_classes() != NULL &&
399      inner_classes() != Universe::the_empty_short_array() &&
400      !inner_classes()->is_shared()) {
401    MetadataFactory::free_array<jushort>(loader_data, inner_classes());
402  }
403  set_inner_classes(NULL);
404
405  // We should deallocate the Annotations instance if it's not in shared spaces.
406  if (annotations() != NULL && !annotations()->is_shared()) {
407    MetadataFactory::free_metadata(loader_data, annotations());
408  }
409  set_annotations(NULL);
410}
411
412bool InstanceKlass::should_be_initialized() const {
413  return !is_initialized();
414}
415
416klassVtable* InstanceKlass::vtable() const {
417  return new klassVtable(this, start_of_vtable(), vtable_length() / vtableEntry::size());
418}
419
420klassItable* InstanceKlass::itable() const {
421  return new klassItable(instanceKlassHandle(this));
422}
423
424void InstanceKlass::eager_initialize(Thread *thread) {
425  if (!EagerInitialization) return;
426
427  if (this->is_not_initialized()) {
428    // abort if the the class has a class initializer
429    if (this->class_initializer() != NULL) return;
430
431    // abort if it is java.lang.Object (initialization is handled in genesis)
432    Klass* super = this->super();
433    if (super == NULL) return;
434
435    // abort if the super class should be initialized
436    if (!InstanceKlass::cast(super)->is_initialized()) return;
437
438    // call body to expose the this pointer
439    instanceKlassHandle this_k(thread, this);
440    eager_initialize_impl(this_k);
441  }
442}
443
444// JVMTI spec thinks there are signers and protection domain in the
445// instanceKlass.  These accessors pretend these fields are there.
446// The hprof specification also thinks these fields are in InstanceKlass.
447oop InstanceKlass::protection_domain() const {
448  // return the protection_domain from the mirror
449  return java_lang_Class::protection_domain(java_mirror());
450}
451
452// To remove these from requires an incompatible change and CCC request.
453objArrayOop InstanceKlass::signers() const {
454  // return the signers from the mirror
455  return java_lang_Class::signers(java_mirror());
456}
457
458oop InstanceKlass::init_lock() const {
459  // return the init lock from the mirror
460  oop lock = java_lang_Class::init_lock(java_mirror());
461  assert((oop)lock != NULL || !is_not_initialized(), // initialized or in_error state
462         "only fully initialized state can have a null lock");
463  return lock;
464}
465
466// Set the initialization lock to null so the object can be GC'ed.  Any racing
467// threads to get this lock will see a null lock and will not lock.
468// That's okay because they all check for initialized state after getting
469// the lock and return.
470void InstanceKlass::fence_and_clear_init_lock() {
471  // make sure previous stores are all done, notably the init_state.
472  OrderAccess::storestore();
473  java_lang_Class::set_init_lock(java_mirror(), NULL);
474  assert(!is_not_initialized(), "class must be initialized now");
475}
476
477void InstanceKlass::eager_initialize_impl(instanceKlassHandle this_k) {
478  EXCEPTION_MARK;
479  oop init_lock = this_k->init_lock();
480  ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
481
482  // abort if someone beat us to the initialization
483  if (!this_k->is_not_initialized()) return;  // note: not equivalent to is_initialized()
484
485  ClassState old_state = this_k->init_state();
486  link_class_impl(this_k, true, THREAD);
487  if (HAS_PENDING_EXCEPTION) {
488    CLEAR_PENDING_EXCEPTION;
489    // Abort if linking the class throws an exception.
490
491    // Use a test to avoid redundantly resetting the state if there's
492    // no change.  Set_init_state() asserts that state changes make
493    // progress, whereas here we might just be spinning in place.
494    if( old_state != this_k->_init_state )
495      this_k->set_init_state (old_state);
496  } else {
497    // linking successfull, mark class as initialized
498    this_k->set_init_state (fully_initialized);
499    this_k->fence_and_clear_init_lock();
500    // trace
501    if (TraceClassInitialization) {
502      ResourceMark rm(THREAD);
503      tty->print_cr("[Initialized %s without side effects]", this_k->external_name());
504    }
505  }
506}
507
508
509// See "The Virtual Machine Specification" section 2.16.5 for a detailed explanation of the class initialization
510// process. The step comments refers to the procedure described in that section.
511// Note: implementation moved to static method to expose the this pointer.
512void InstanceKlass::initialize(TRAPS) {
513  if (this->should_be_initialized()) {
514    HandleMark hm(THREAD);
515    instanceKlassHandle this_k(THREAD, this);
516    initialize_impl(this_k, CHECK);
517    // Note: at this point the class may be initialized
518    //       OR it may be in the state of being initialized
519    //       in case of recursive initialization!
520  } else {
521    assert(is_initialized(), "sanity check");
522  }
523}
524
525
526bool InstanceKlass::verify_code(
527    instanceKlassHandle this_k, bool throw_verifyerror, TRAPS) {
528  // 1) Verify the bytecodes
529  Verifier::Mode mode =
530    throw_verifyerror ? Verifier::ThrowException : Verifier::NoException;
531  return Verifier::verify(this_k, mode, this_k->should_verify_class(), CHECK_false);
532}
533
534
535// Used exclusively by the shared spaces dump mechanism to prevent
536// classes mapped into the shared regions in new VMs from appearing linked.
537
538void InstanceKlass::unlink_class() {
539  assert(is_linked(), "must be linked");
540  _init_state = loaded;
541}
542
543void InstanceKlass::link_class(TRAPS) {
544  assert(is_loaded(), "must be loaded");
545  if (!is_linked()) {
546    HandleMark hm(THREAD);
547    instanceKlassHandle this_k(THREAD, this);
548    link_class_impl(this_k, true, CHECK);
549  }
550}
551
552// Called to verify that a class can link during initialization, without
553// throwing a VerifyError.
554bool InstanceKlass::link_class_or_fail(TRAPS) {
555  assert(is_loaded(), "must be loaded");
556  if (!is_linked()) {
557    HandleMark hm(THREAD);
558    instanceKlassHandle this_k(THREAD, this);
559    link_class_impl(this_k, false, CHECK_false);
560  }
561  return is_linked();
562}
563
564bool InstanceKlass::link_class_impl(
565    instanceKlassHandle this_k, bool throw_verifyerror, TRAPS) {
566  // check for error state
567  if (this_k->is_in_error_state()) {
568    ResourceMark rm(THREAD);
569    THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
570               this_k->external_name(), false);
571  }
572  // return if already verified
573  if (this_k->is_linked()) {
574    return true;
575  }
576
577  // Timing
578  // timer handles recursion
579  assert(THREAD->is_Java_thread(), "non-JavaThread in link_class_impl");
580  JavaThread* jt = (JavaThread*)THREAD;
581
582  // link super class before linking this class
583  instanceKlassHandle super(THREAD, this_k->super());
584  if (super.not_null()) {
585    if (super->is_interface()) {  // check if super class is an interface
586      ResourceMark rm(THREAD);
587      Exceptions::fthrow(
588        THREAD_AND_LOCATION,
589        vmSymbols::java_lang_IncompatibleClassChangeError(),
590        "class %s has interface %s as super class",
591        this_k->external_name(),
592        super->external_name()
593      );
594      return false;
595    }
596
597    link_class_impl(super, throw_verifyerror, CHECK_false);
598  }
599
600  // link all interfaces implemented by this class before linking this class
601  Array<Klass*>* interfaces = this_k->local_interfaces();
602  int num_interfaces = interfaces->length();
603  for (int index = 0; index < num_interfaces; index++) {
604    HandleMark hm(THREAD);
605    instanceKlassHandle ih(THREAD, interfaces->at(index));
606    link_class_impl(ih, throw_verifyerror, CHECK_false);
607  }
608
609  // in case the class is linked in the process of linking its superclasses
610  if (this_k->is_linked()) {
611    return true;
612  }
613
614  // trace only the link time for this klass that includes
615  // the verification time
616  PerfClassTraceTime vmtimer(ClassLoader::perf_class_link_time(),
617                             ClassLoader::perf_class_link_selftime(),
618                             ClassLoader::perf_classes_linked(),
619                             jt->get_thread_stat()->perf_recursion_counts_addr(),
620                             jt->get_thread_stat()->perf_timers_addr(),
621                             PerfClassTraceTime::CLASS_LINK);
622
623  // verification & rewriting
624  {
625    oop init_lock = this_k->init_lock();
626    ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
627    // rewritten will have been set if loader constraint error found
628    // on an earlier link attempt
629    // don't verify or rewrite if already rewritten
630
631    if (!this_k->is_linked()) {
632      if (!this_k->is_rewritten()) {
633        {
634          // Timer includes any side effects of class verification (resolution,
635          // etc), but not recursive entry into verify_code().
636          PerfClassTraceTime timer(ClassLoader::perf_class_verify_time(),
637                                   ClassLoader::perf_class_verify_selftime(),
638                                   ClassLoader::perf_classes_verified(),
639                                   jt->get_thread_stat()->perf_recursion_counts_addr(),
640                                   jt->get_thread_stat()->perf_timers_addr(),
641                                   PerfClassTraceTime::CLASS_VERIFY);
642          bool verify_ok = verify_code(this_k, throw_verifyerror, THREAD);
643          if (!verify_ok) {
644            return false;
645          }
646        }
647
648        // Just in case a side-effect of verify linked this class already
649        // (which can sometimes happen since the verifier loads classes
650        // using custom class loaders, which are free to initialize things)
651        if (this_k->is_linked()) {
652          return true;
653        }
654
655        // also sets rewritten
656        this_k->rewrite_class(CHECK_false);
657      }
658
659      // relocate jsrs and link methods after they are all rewritten
660      this_k->link_methods(CHECK_false);
661
662      // Initialize the vtable and interface table after
663      // methods have been rewritten since rewrite may
664      // fabricate new Method*s.
665      // also does loader constraint checking
666      if (!this_k()->is_shared()) {
667        ResourceMark rm(THREAD);
668        this_k->vtable()->initialize_vtable(true, CHECK_false);
669        this_k->itable()->initialize_itable(true, CHECK_false);
670      }
671#ifdef ASSERT
672      else {
673        ResourceMark rm(THREAD);
674        this_k->vtable()->verify(tty, true);
675        // In case itable verification is ever added.
676        // this_k->itable()->verify(tty, true);
677      }
678#endif
679      this_k->set_init_state(linked);
680      if (JvmtiExport::should_post_class_prepare()) {
681        Thread *thread = THREAD;
682        assert(thread->is_Java_thread(), "thread->is_Java_thread()");
683        JvmtiExport::post_class_prepare((JavaThread *) thread, this_k());
684      }
685    }
686  }
687  return true;
688}
689
690
691// Rewrite the byte codes of all of the methods of a class.
692// The rewriter must be called exactly once. Rewriting must happen after
693// verification but before the first method of the class is executed.
694void InstanceKlass::rewrite_class(TRAPS) {
695  assert(is_loaded(), "must be loaded");
696  instanceKlassHandle this_k(THREAD, this);
697  if (this_k->is_rewritten()) {
698    assert(this_k()->is_shared(), "rewriting an unshared class?");
699    return;
700  }
701  Rewriter::rewrite(this_k, CHECK);
702  this_k->set_rewritten();
703}
704
705// Now relocate and link method entry points after class is rewritten.
706// This is outside is_rewritten flag. In case of an exception, it can be
707// executed more than once.
708void InstanceKlass::link_methods(TRAPS) {
709  int len = methods()->length();
710  for (int i = len-1; i >= 0; i--) {
711    methodHandle m(THREAD, methods()->at(i));
712
713    // Set up method entry points for compiler and interpreter    .
714    m->link_method(m, CHECK);
715
716    // This is for JVMTI and unrelated to relocator but the last thing we do
717#ifdef ASSERT
718    if (StressMethodComparator) {
719      ResourceMark rm(THREAD);
720      static int nmc = 0;
721      for (int j = i; j >= 0 && j >= i-4; j--) {
722        if ((++nmc % 1000) == 0)  tty->print_cr("Have run MethodComparator %d times...", nmc);
723        bool z = MethodComparator::methods_EMCP(m(),
724                   methods()->at(j));
725        if (j == i && !z) {
726          tty->print("MethodComparator FAIL: "); m->print(); m->print_codes();
727          assert(z, "method must compare equal to itself");
728        }
729      }
730    }
731#endif //ASSERT
732  }
733}
734
735
736void InstanceKlass::initialize_impl(instanceKlassHandle this_k, TRAPS) {
737  // Make sure klass is linked (verified) before initialization
738  // A class could already be verified, since it has been reflected upon.
739  this_k->link_class(CHECK);
740
741  DTRACE_CLASSINIT_PROBE(required, InstanceKlass::cast(this_k()), -1);
742
743  bool wait = false;
744
745  // refer to the JVM book page 47 for description of steps
746  // Step 1
747  {
748    oop init_lock = this_k->init_lock();
749    ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
750
751    Thread *self = THREAD; // it's passed the current thread
752
753    // Step 2
754    // If we were to use wait() instead of waitInterruptibly() then
755    // we might end up throwing IE from link/symbol resolution sites
756    // that aren't expected to throw.  This would wreak havoc.  See 6320309.
757    while(this_k->is_being_initialized() && !this_k->is_reentrant_initialization(self)) {
758        wait = true;
759      ol.waitUninterruptibly(CHECK);
760    }
761
762    // Step 3
763    if (this_k->is_being_initialized() && this_k->is_reentrant_initialization(self)) {
764      DTRACE_CLASSINIT_PROBE_WAIT(recursive, InstanceKlass::cast(this_k()), -1,wait);
765      return;
766    }
767
768    // Step 4
769    if (this_k->is_initialized()) {
770      DTRACE_CLASSINIT_PROBE_WAIT(concurrent, InstanceKlass::cast(this_k()), -1,wait);
771      return;
772    }
773
774    // Step 5
775    if (this_k->is_in_error_state()) {
776      DTRACE_CLASSINIT_PROBE_WAIT(erroneous, InstanceKlass::cast(this_k()), -1,wait);
777      ResourceMark rm(THREAD);
778      const char* desc = "Could not initialize class ";
779      const char* className = this_k->external_name();
780      size_t msglen = strlen(desc) + strlen(className) + 1;
781      char* message = NEW_RESOURCE_ARRAY(char, msglen);
782      if (NULL == message) {
783        // Out of memory: can't create detailed error message
784        THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), className);
785      } else {
786        jio_snprintf(message, msglen, "%s%s", desc, className);
787        THROW_MSG(vmSymbols::java_lang_NoClassDefFoundError(), message);
788      }
789    }
790
791    // Step 6
792    this_k->set_init_state(being_initialized);
793    this_k->set_init_thread(self);
794  }
795
796  // Step 7
797  Klass* super_klass = this_k->super();
798  if (super_klass != NULL && !this_k->is_interface() && super_klass->should_be_initialized()) {
799    super_klass->initialize(THREAD);
800
801    if (HAS_PENDING_EXCEPTION) {
802      Handle e(THREAD, PENDING_EXCEPTION);
803      CLEAR_PENDING_EXCEPTION;
804      {
805        EXCEPTION_MARK;
806        this_k->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
807        CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
808      }
809      DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_k()), -1,wait);
810      THROW_OOP(e());
811    }
812  }
813
814  if (this_k->has_default_methods()) {
815    // Step 7.5: initialize any interfaces which have default methods
816    for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {
817      Klass* iface = this_k->local_interfaces()->at(i);
818      InstanceKlass* ik = InstanceKlass::cast(iface);
819      if (ik->has_default_methods() && ik->should_be_initialized()) {
820        ik->initialize(THREAD);
821
822        if (HAS_PENDING_EXCEPTION) {
823          Handle e(THREAD, PENDING_EXCEPTION);
824          CLEAR_PENDING_EXCEPTION;
825          {
826            EXCEPTION_MARK;
827            // Locks object, set state, and notify all waiting threads
828            this_k->set_initialization_state_and_notify(
829                initialization_error, THREAD);
830
831            // ignore any exception thrown, superclass initialization error is
832            // thrown below
833            CLEAR_PENDING_EXCEPTION;
834          }
835          DTRACE_CLASSINIT_PROBE_WAIT(
836              super__failed, InstanceKlass::cast(this_k()), -1, wait);
837          THROW_OOP(e());
838        }
839      }
840    }
841  }
842
843  // Step 8
844  {
845    assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
846    JavaThread* jt = (JavaThread*)THREAD;
847    DTRACE_CLASSINIT_PROBE_WAIT(clinit, InstanceKlass::cast(this_k()), -1,wait);
848    // Timer includes any side effects of class initialization (resolution,
849    // etc), but not recursive entry into call_class_initializer().
850    PerfClassTraceTime timer(ClassLoader::perf_class_init_time(),
851                             ClassLoader::perf_class_init_selftime(),
852                             ClassLoader::perf_classes_inited(),
853                             jt->get_thread_stat()->perf_recursion_counts_addr(),
854                             jt->get_thread_stat()->perf_timers_addr(),
855                             PerfClassTraceTime::CLASS_CLINIT);
856    this_k->call_class_initializer(THREAD);
857  }
858
859  // Step 9
860  if (!HAS_PENDING_EXCEPTION) {
861    this_k->set_initialization_state_and_notify(fully_initialized, CHECK);
862    { ResourceMark rm(THREAD);
863      debug_only(this_k->vtable()->verify(tty, true);)
864    }
865  }
866  else {
867    // Step 10 and 11
868    Handle e(THREAD, PENDING_EXCEPTION);
869    CLEAR_PENDING_EXCEPTION;
870    // JVMTI has already reported the pending exception
871    // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
872    JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
873    {
874      EXCEPTION_MARK;
875      this_k->set_initialization_state_and_notify(initialization_error, THREAD);
876      CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, class initialization error is thrown below
877      // JVMTI has already reported the pending exception
878      // JVMTI internal flag reset is needed in order to report ExceptionInInitializerError
879      JvmtiExport::clear_detected_exception((JavaThread*)THREAD);
880    }
881    DTRACE_CLASSINIT_PROBE_WAIT(error, InstanceKlass::cast(this_k()), -1,wait);
882    if (e->is_a(SystemDictionary::Error_klass())) {
883      THROW_OOP(e());
884    } else {
885      JavaCallArguments args(e);
886      THROW_ARG(vmSymbols::java_lang_ExceptionInInitializerError(),
887                vmSymbols::throwable_void_signature(),
888                &args);
889    }
890  }
891  DTRACE_CLASSINIT_PROBE_WAIT(end, InstanceKlass::cast(this_k()), -1,wait);
892}
893
894
895// Note: implementation moved to static method to expose the this pointer.
896void InstanceKlass::set_initialization_state_and_notify(ClassState state, TRAPS) {
897  instanceKlassHandle kh(THREAD, this);
898  set_initialization_state_and_notify_impl(kh, state, CHECK);
899}
900
901void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_k, ClassState state, TRAPS) {
902  oop init_lock = this_k->init_lock();
903  ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
904  this_k->set_init_state(state);
905  this_k->fence_and_clear_init_lock();
906  ol.notify_all(CHECK);
907}
908
909// The embedded _implementor field can only record one implementor.
910// When there are more than one implementors, the _implementor field
911// is set to the interface Klass* itself. Following are the possible
912// values for the _implementor field:
913//   NULL                  - no implementor
914//   implementor Klass*    - one implementor
915//   self                  - more than one implementor
916//
917// The _implementor field only exists for interfaces.
918void InstanceKlass::add_implementor(Klass* k) {
919  assert(Compile_lock->owned_by_self(), "");
920  assert(is_interface(), "not interface");
921  // Filter out my subinterfaces.
922  // (Note: Interfaces are never on the subklass list.)
923  if (InstanceKlass::cast(k)->is_interface()) return;
924
925  // Filter out subclasses whose supers already implement me.
926  // (Note: CHA must walk subclasses of direct implementors
927  // in order to locate indirect implementors.)
928  Klass* sk = InstanceKlass::cast(k)->super();
929  if (sk != NULL && InstanceKlass::cast(sk)->implements_interface(this))
930    // We only need to check one immediate superclass, since the
931    // implements_interface query looks at transitive_interfaces.
932    // Any supers of the super have the same (or fewer) transitive_interfaces.
933    return;
934
935  Klass* ik = implementor();
936  if (ik == NULL) {
937    set_implementor(k);
938  } else if (ik != this) {
939    // There is already an implementor. Use itself as an indicator of
940    // more than one implementors.
941    set_implementor(this);
942  }
943
944  // The implementor also implements the transitive_interfaces
945  for (int index = 0; index < local_interfaces()->length(); index++) {
946    InstanceKlass::cast(local_interfaces()->at(index))->add_implementor(k);
947  }
948}
949
950void InstanceKlass::init_implementor() {
951  if (is_interface()) {
952    set_implementor(NULL);
953  }
954}
955
956
957void InstanceKlass::process_interfaces(Thread *thread) {
958  // link this class into the implementors list of every interface it implements
959  for (int i = local_interfaces()->length() - 1; i >= 0; i--) {
960    assert(local_interfaces()->at(i)->is_klass(), "must be a klass");
961    InstanceKlass* interf = InstanceKlass::cast(local_interfaces()->at(i));
962    assert(interf->is_interface(), "expected interface");
963    interf->add_implementor(this);
964  }
965}
966
967bool InstanceKlass::can_be_primary_super_slow() const {
968  if (is_interface())
969    return false;
970  else
971    return Klass::can_be_primary_super_slow();
972}
973
974GrowableArray<Klass*>* InstanceKlass::compute_secondary_supers(int num_extra_slots) {
975  // The secondaries are the implemented interfaces.
976  InstanceKlass* ik = InstanceKlass::cast(this);
977  Array<Klass*>* interfaces = ik->transitive_interfaces();
978  int num_secondaries = num_extra_slots + interfaces->length();
979  if (num_secondaries == 0) {
980    // Must share this for correct bootstrapping!
981    set_secondary_supers(Universe::the_empty_klass_array());
982    return NULL;
983  } else if (num_extra_slots == 0) {
984    // The secondary super list is exactly the same as the transitive interfaces.
985    // Redefine classes has to be careful not to delete this!
986    set_secondary_supers(interfaces);
987    return NULL;
988  } else {
989    // Copy transitive interfaces to a temporary growable array to be constructed
990    // into the secondary super list with extra slots.
991    GrowableArray<Klass*>* secondaries = new GrowableArray<Klass*>(interfaces->length());
992    for (int i = 0; i < interfaces->length(); i++) {
993      secondaries->push(interfaces->at(i));
994    }
995    return secondaries;
996  }
997}
998
999bool InstanceKlass::compute_is_subtype_of(Klass* k) {
1000  if (k->is_interface()) {
1001    return implements_interface(k);
1002  } else {
1003    return Klass::compute_is_subtype_of(k);
1004  }
1005}
1006
1007bool InstanceKlass::implements_interface(Klass* k) const {
1008  if (this == k) return true;
1009  assert(k->is_interface(), "should be an interface class");
1010  for (int i = 0; i < transitive_interfaces()->length(); i++) {
1011    if (transitive_interfaces()->at(i) == k) {
1012      return true;
1013    }
1014  }
1015  return false;
1016}
1017
1018bool InstanceKlass::is_same_or_direct_interface(Klass *k) const {
1019  // Verify direct super interface
1020  if (this == k) return true;
1021  assert(k->is_interface(), "should be an interface class");
1022  for (int i = 0; i < local_interfaces()->length(); i++) {
1023    if (local_interfaces()->at(i) == k) {
1024      return true;
1025    }
1026  }
1027  return false;
1028}
1029
1030objArrayOop InstanceKlass::allocate_objArray(int n, int length, TRAPS) {
1031  if (length < 0) THROW_0(vmSymbols::java_lang_NegativeArraySizeException());
1032  if (length > arrayOopDesc::max_array_length(T_OBJECT)) {
1033    report_java_out_of_memory("Requested array size exceeds VM limit");
1034    JvmtiExport::post_array_size_exhausted();
1035    THROW_OOP_0(Universe::out_of_memory_error_array_size());
1036  }
1037  int size = objArrayOopDesc::object_size(length);
1038  Klass* ak = array_klass(n, CHECK_NULL);
1039  KlassHandle h_ak (THREAD, ak);
1040  objArrayOop o =
1041    (objArrayOop)CollectedHeap::array_allocate(h_ak, size, length, CHECK_NULL);
1042  return o;
1043}
1044
1045instanceOop InstanceKlass::register_finalizer(instanceOop i, TRAPS) {
1046  if (TraceFinalizerRegistration) {
1047    tty->print("Registered ");
1048    i->print_value_on(tty);
1049    tty->print_cr(" (" INTPTR_FORMAT ") as finalizable", (address)i);
1050  }
1051  instanceHandle h_i(THREAD, i);
1052  // Pass the handle as argument, JavaCalls::call expects oop as jobjects
1053  JavaValue result(T_VOID);
1054  JavaCallArguments args(h_i);
1055  methodHandle mh (THREAD, Universe::finalizer_register_method());
1056  JavaCalls::call(&result, mh, &args, CHECK_NULL);
1057  return h_i();
1058}
1059
1060instanceOop InstanceKlass::allocate_instance(TRAPS) {
1061  bool has_finalizer_flag = has_finalizer(); // Query before possible GC
1062  int size = size_helper();  // Query before forming handle.
1063
1064  KlassHandle h_k(THREAD, this);
1065
1066  instanceOop i;
1067
1068  i = (instanceOop)CollectedHeap::obj_allocate(h_k, size, CHECK_NULL);
1069  if (has_finalizer_flag && !RegisterFinalizersAtInit) {
1070    i = register_finalizer(i, CHECK_NULL);
1071  }
1072  return i;
1073}
1074
1075void InstanceKlass::check_valid_for_instantiation(bool throwError, TRAPS) {
1076  if (is_interface() || is_abstract()) {
1077    ResourceMark rm(THREAD);
1078    THROW_MSG(throwError ? vmSymbols::java_lang_InstantiationError()
1079              : vmSymbols::java_lang_InstantiationException(), external_name());
1080  }
1081  if (this == SystemDictionary::Class_klass()) {
1082    ResourceMark rm(THREAD);
1083    THROW_MSG(throwError ? vmSymbols::java_lang_IllegalAccessError()
1084              : vmSymbols::java_lang_IllegalAccessException(), external_name());
1085  }
1086}
1087
1088Klass* InstanceKlass::array_klass_impl(bool or_null, int n, TRAPS) {
1089  instanceKlassHandle this_k(THREAD, this);
1090  return array_klass_impl(this_k, or_null, n, THREAD);
1091}
1092
1093Klass* InstanceKlass::array_klass_impl(instanceKlassHandle this_k, bool or_null, int n, TRAPS) {
1094  if (this_k->array_klasses() == NULL) {
1095    if (or_null) return NULL;
1096
1097    ResourceMark rm;
1098    JavaThread *jt = (JavaThread *)THREAD;
1099    {
1100      // Atomic creation of array_klasses
1101      MutexLocker mc(Compile_lock, THREAD);   // for vtables
1102      MutexLocker ma(MultiArray_lock, THREAD);
1103
1104      // Check if update has already taken place
1105      if (this_k->array_klasses() == NULL) {
1106        Klass*    k = ObjArrayKlass::allocate_objArray_klass(this_k->class_loader_data(), 1, this_k, CHECK_NULL);
1107        this_k->set_array_klasses(k);
1108      }
1109    }
1110  }
1111  // _this will always be set at this point
1112  ObjArrayKlass* oak = (ObjArrayKlass*)this_k->array_klasses();
1113  if (or_null) {
1114    return oak->array_klass_or_null(n);
1115  }
1116  return oak->array_klass(n, CHECK_NULL);
1117}
1118
1119Klass* InstanceKlass::array_klass_impl(bool or_null, TRAPS) {
1120  return array_klass_impl(or_null, 1, THREAD);
1121}
1122
1123void InstanceKlass::call_class_initializer(TRAPS) {
1124  instanceKlassHandle ik (THREAD, this);
1125  call_class_initializer_impl(ik, THREAD);
1126}
1127
1128static int call_class_initializer_impl_counter = 0;   // for debugging
1129
1130Method* InstanceKlass::class_initializer() {
1131  Method* clinit = find_method(
1132      vmSymbols::class_initializer_name(), vmSymbols::void_method_signature());
1133  if (clinit != NULL && clinit->has_valid_initializer_flags()) {
1134    return clinit;
1135  }
1136  return NULL;
1137}
1138
1139void InstanceKlass::call_class_initializer_impl(instanceKlassHandle this_k, TRAPS) {
1140  if (ReplayCompiles &&
1141      (ReplaySuppressInitializers == 1 ||
1142       ReplaySuppressInitializers >= 2 && this_k->class_loader() != NULL)) {
1143    // Hide the existence of the initializer for the purpose of replaying the compile
1144    return;
1145  }
1146
1147  methodHandle h_method(THREAD, this_k->class_initializer());
1148  assert(!this_k->is_initialized(), "we cannot initialize twice");
1149  if (TraceClassInitialization) {
1150    tty->print("%d Initializing ", call_class_initializer_impl_counter++);
1151    this_k->name()->print_value();
1152    tty->print_cr("%s (" INTPTR_FORMAT ")", h_method() == NULL ? "(no method)" : "", (address)this_k());
1153  }
1154  if (h_method() != NULL) {
1155    JavaCallArguments args; // No arguments
1156    JavaValue result(T_VOID);
1157    JavaCalls::call(&result, h_method, &args, CHECK); // Static call (no args)
1158  }
1159}
1160
1161
1162void InstanceKlass::mask_for(methodHandle method, int bci,
1163  InterpreterOopMap* entry_for) {
1164  // Dirty read, then double-check under a lock.
1165  if (_oop_map_cache == NULL) {
1166    // Otherwise, allocate a new one.
1167    MutexLocker x(OopMapCacheAlloc_lock);
1168    // First time use. Allocate a cache in C heap
1169    if (_oop_map_cache == NULL) {
1170      // Release stores from OopMapCache constructor before assignment
1171      // to _oop_map_cache. C++ compilers on ppc do not emit the
1172      // required memory barrier only because of the volatile
1173      // qualifier of _oop_map_cache.
1174      OrderAccess::release_store_ptr(&_oop_map_cache, new OopMapCache());
1175    }
1176  }
1177  // _oop_map_cache is constant after init; lookup below does is own locking.
1178  _oop_map_cache->lookup(method, bci, entry_for);
1179}
1180
1181
1182bool InstanceKlass::find_local_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1183  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1184    Symbol* f_name = fs.name();
1185    Symbol* f_sig  = fs.signature();
1186    if (f_name == name && f_sig == sig) {
1187      fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1188      return true;
1189    }
1190  }
1191  return false;
1192}
1193
1194
1195Klass* InstanceKlass::find_interface_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1196  const int n = local_interfaces()->length();
1197  for (int i = 0; i < n; i++) {
1198    Klass* intf1 = local_interfaces()->at(i);
1199    assert(intf1->is_interface(), "just checking type");
1200    // search for field in current interface
1201    if (InstanceKlass::cast(intf1)->find_local_field(name, sig, fd)) {
1202      assert(fd->is_static(), "interface field must be static");
1203      return intf1;
1204    }
1205    // search for field in direct superinterfaces
1206    Klass* intf2 = InstanceKlass::cast(intf1)->find_interface_field(name, sig, fd);
1207    if (intf2 != NULL) return intf2;
1208  }
1209  // otherwise field lookup fails
1210  return NULL;
1211}
1212
1213
1214Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, fieldDescriptor* fd) const {
1215  // search order according to newest JVM spec (5.4.3.2, p.167).
1216  // 1) search for field in current klass
1217  if (find_local_field(name, sig, fd)) {
1218    return const_cast<InstanceKlass*>(this);
1219  }
1220  // 2) search for field recursively in direct superinterfaces
1221  { Klass* intf = find_interface_field(name, sig, fd);
1222    if (intf != NULL) return intf;
1223  }
1224  // 3) apply field lookup recursively if superclass exists
1225  { Klass* supr = super();
1226    if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, fd);
1227  }
1228  // 4) otherwise field lookup fails
1229  return NULL;
1230}
1231
1232
1233Klass* InstanceKlass::find_field(Symbol* name, Symbol* sig, bool is_static, fieldDescriptor* fd) const {
1234  // search order according to newest JVM spec (5.4.3.2, p.167).
1235  // 1) search for field in current klass
1236  if (find_local_field(name, sig, fd)) {
1237    if (fd->is_static() == is_static) return const_cast<InstanceKlass*>(this);
1238  }
1239  // 2) search for field recursively in direct superinterfaces
1240  if (is_static) {
1241    Klass* intf = find_interface_field(name, sig, fd);
1242    if (intf != NULL) return intf;
1243  }
1244  // 3) apply field lookup recursively if superclass exists
1245  { Klass* supr = super();
1246    if (supr != NULL) return InstanceKlass::cast(supr)->find_field(name, sig, is_static, fd);
1247  }
1248  // 4) otherwise field lookup fails
1249  return NULL;
1250}
1251
1252
1253bool InstanceKlass::find_local_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1254  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1255    if (fs.offset() == offset) {
1256      fd->reinitialize(const_cast<InstanceKlass*>(this), fs.index());
1257      if (fd->is_static() == is_static) return true;
1258    }
1259  }
1260  return false;
1261}
1262
1263
1264bool InstanceKlass::find_field_from_offset(int offset, bool is_static, fieldDescriptor* fd) const {
1265  Klass* klass = const_cast<InstanceKlass*>(this);
1266  while (klass != NULL) {
1267    if (InstanceKlass::cast(klass)->find_local_field_from_offset(offset, is_static, fd)) {
1268      return true;
1269    }
1270    klass = klass->super();
1271  }
1272  return false;
1273}
1274
1275
1276void InstanceKlass::methods_do(void f(Method* method)) {
1277  // Methods aren't stable until they are loaded.  This can be read outside
1278  // a lock through the ClassLoaderData for profiling
1279  if (!is_loaded()) {
1280    return;
1281  }
1282
1283  int len = methods()->length();
1284  for (int index = 0; index < len; index++) {
1285    Method* m = methods()->at(index);
1286    assert(m->is_method(), "must be method");
1287    f(m);
1288  }
1289}
1290
1291
1292void InstanceKlass::do_local_static_fields(FieldClosure* cl) {
1293  for (JavaFieldStream fs(this); !fs.done(); fs.next()) {
1294    if (fs.access_flags().is_static()) {
1295      fieldDescriptor& fd = fs.field_descriptor();
1296      cl->do_field(&fd);
1297    }
1298  }
1299}
1300
1301
1302void InstanceKlass::do_local_static_fields(void f(fieldDescriptor*, Handle, TRAPS), Handle mirror, TRAPS) {
1303  instanceKlassHandle h_this(THREAD, this);
1304  do_local_static_fields_impl(h_this, f, mirror, CHECK);
1305}
1306
1307
1308void InstanceKlass::do_local_static_fields_impl(instanceKlassHandle this_k,
1309                             void f(fieldDescriptor* fd, Handle, TRAPS), Handle mirror, TRAPS) {
1310  for (JavaFieldStream fs(this_k()); !fs.done(); fs.next()) {
1311    if (fs.access_flags().is_static()) {
1312      fieldDescriptor& fd = fs.field_descriptor();
1313      f(&fd, mirror, CHECK);
1314    }
1315  }
1316}
1317
1318
1319static int compare_fields_by_offset(int* a, int* b) {
1320  return a[0] - b[0];
1321}
1322
1323void InstanceKlass::do_nonstatic_fields(FieldClosure* cl) {
1324  InstanceKlass* super = superklass();
1325  if (super != NULL) {
1326    super->do_nonstatic_fields(cl);
1327  }
1328  fieldDescriptor fd;
1329  int length = java_fields_count();
1330  // In DebugInfo nonstatic fields are sorted by offset.
1331  int* fields_sorted = NEW_C_HEAP_ARRAY(int, 2*(length+1), mtClass);
1332  int j = 0;
1333  for (int i = 0; i < length; i += 1) {
1334    fd.reinitialize(this, i);
1335    if (!fd.is_static()) {
1336      fields_sorted[j + 0] = fd.offset();
1337      fields_sorted[j + 1] = i;
1338      j += 2;
1339    }
1340  }
1341  if (j > 0) {
1342    length = j;
1343    // _sort_Fn is defined in growableArray.hpp.
1344    qsort(fields_sorted, length/2, 2*sizeof(int), (_sort_Fn)compare_fields_by_offset);
1345    for (int i = 0; i < length; i += 2) {
1346      fd.reinitialize(this, fields_sorted[i + 1]);
1347      assert(!fd.is_static() && fd.offset() == fields_sorted[i], "only nonstatic fields");
1348      cl->do_field(&fd);
1349    }
1350  }
1351  FREE_C_HEAP_ARRAY(int, fields_sorted, mtClass);
1352}
1353
1354
1355void InstanceKlass::array_klasses_do(void f(Klass* k, TRAPS), TRAPS) {
1356  if (array_klasses() != NULL)
1357    ArrayKlass::cast(array_klasses())->array_klasses_do(f, THREAD);
1358}
1359
1360void InstanceKlass::array_klasses_do(void f(Klass* k)) {
1361  if (array_klasses() != NULL)
1362    ArrayKlass::cast(array_klasses())->array_klasses_do(f);
1363}
1364
1365#ifdef ASSERT
1366static int linear_search(Array<Method*>* methods, Symbol* name, Symbol* signature) {
1367  int len = methods->length();
1368  for (int index = 0; index < len; index++) {
1369    Method* m = methods->at(index);
1370    assert(m->is_method(), "must be method");
1371    if (m->signature() == signature && m->name() == name) {
1372       return index;
1373    }
1374  }
1375  return -1;
1376}
1377#endif
1378
1379static int binary_search(Array<Method*>* methods, Symbol* name) {
1380  int len = methods->length();
1381  // methods are sorted, so do binary search
1382  int l = 0;
1383  int h = len - 1;
1384  while (l <= h) {
1385    int mid = (l + h) >> 1;
1386    Method* m = methods->at(mid);
1387    assert(m->is_method(), "must be method");
1388    int res = m->name()->fast_compare(name);
1389    if (res == 0) {
1390      return mid;
1391    } else if (res < 0) {
1392      l = mid + 1;
1393    } else {
1394      h = mid - 1;
1395    }
1396  }
1397  return -1;
1398}
1399
1400// find_method looks up the name/signature in the local methods array
1401Method* InstanceKlass::find_method(Symbol* name, Symbol* signature) const {
1402  return find_method_impl(name, signature, false);
1403}
1404
1405Method* InstanceKlass::find_method_impl(Symbol* name, Symbol* signature, bool skipping_overpass) const {
1406  return InstanceKlass::find_method_impl(methods(), name, signature, skipping_overpass);
1407}
1408
1409// find_instance_method looks up the name/signature in the local methods array
1410// and skips over static methods
1411Method* InstanceKlass::find_instance_method(
1412    Array<Method*>* methods, Symbol* name, Symbol* signature) {
1413  Method* meth = InstanceKlass::find_method(methods, name, signature);
1414  if (meth != NULL && meth->is_static()) {
1415      meth = NULL;
1416  }
1417  return meth;
1418}
1419
1420// find_method looks up the name/signature in the local methods array
1421Method* InstanceKlass::find_method(
1422    Array<Method*>* methods, Symbol* name, Symbol* signature) {
1423  return InstanceKlass::find_method_impl(methods, name, signature, false);
1424}
1425
1426Method* InstanceKlass::find_method_impl(
1427    Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass) {
1428  int hit = find_method_index(methods, name, signature, skipping_overpass);
1429  return hit >= 0 ? methods->at(hit): NULL;
1430}
1431
1432// Used directly for default_methods to find the index into the
1433// default_vtable_indices, and indirectly by find_method
1434// find_method_index looks in the local methods array to return the index
1435// of the matching name/signature. If, overpass methods are being ignored,
1436// the search continues to find a potential non-overpass match.  This capability
1437// is important during method resolution to prefer a static method, for example,
1438// over an overpass method.
1439int InstanceKlass::find_method_index(
1440    Array<Method*>* methods, Symbol* name, Symbol* signature, bool skipping_overpass) {
1441  int hit = binary_search(methods, name);
1442  if (hit != -1) {
1443    Method* m = methods->at(hit);
1444    // Do linear search to find matching signature.  First, quick check
1445    // for common case, ignoring overpasses if requested.
1446    if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return hit;
1447
1448    // search downwards through overloaded methods
1449    int i;
1450    for (i = hit - 1; i >= 0; --i) {
1451        Method* m = methods->at(i);
1452        assert(m->is_method(), "must be method");
1453        if (m->name() != name) break;
1454        if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return i;
1455    }
1456    // search upwards
1457    for (i = hit + 1; i < methods->length(); ++i) {
1458        Method* m = methods->at(i);
1459        assert(m->is_method(), "must be method");
1460        if (m->name() != name) break;
1461        if ((m->signature() == signature) && (!skipping_overpass || !m->is_overpass())) return i;
1462    }
1463    // not found
1464#ifdef ASSERT
1465    int index = skipping_overpass ? -1 : linear_search(methods, name, signature);
1466    assert(index == -1, err_msg("binary search should have found entry %d", index));
1467#endif
1468  }
1469  return -1;
1470}
1471int InstanceKlass::find_method_by_name(Symbol* name, int* end) {
1472  return find_method_by_name(methods(), name, end);
1473}
1474
1475int InstanceKlass::find_method_by_name(
1476    Array<Method*>* methods, Symbol* name, int* end_ptr) {
1477  assert(end_ptr != NULL, "just checking");
1478  int start = binary_search(methods, name);
1479  int end = start + 1;
1480  if (start != -1) {
1481    while (start - 1 >= 0 && (methods->at(start - 1))->name() == name) --start;
1482    while (end < methods->length() && (methods->at(end))->name() == name) ++end;
1483    *end_ptr = end;
1484    return start;
1485  }
1486  return -1;
1487}
1488
1489// uncached_lookup_method searches both the local class methods array and all
1490// superclasses methods arrays, skipping any overpass methods in superclasses.
1491Method* InstanceKlass::uncached_lookup_method(Symbol* name, Symbol* signature, MethodLookupMode mode) const {
1492  MethodLookupMode lookup_mode = mode;
1493  Klass* klass = const_cast<InstanceKlass*>(this);
1494  while (klass != NULL) {
1495    Method* method = InstanceKlass::cast(klass)->find_method_impl(name, signature, (lookup_mode == skip_overpass));
1496    if (method != NULL) {
1497      return method;
1498    }
1499    klass = InstanceKlass::cast(klass)->super();
1500    lookup_mode = skip_overpass;   // Always ignore overpass methods in superclasses
1501  }
1502  return NULL;
1503}
1504
1505#ifdef ASSERT
1506// search through class hierarchy and return true if this class or
1507// one of the superclasses was redefined
1508bool InstanceKlass::has_redefined_this_or_super() const {
1509  const InstanceKlass* klass = this;
1510  while (klass != NULL) {
1511    if (klass->has_been_redefined()) {
1512      return true;
1513    }
1514    klass = InstanceKlass::cast(klass->super());
1515  }
1516  return false;
1517}
1518#endif
1519
1520// lookup a method in the default methods list then in all transitive interfaces
1521// Do NOT return private or static methods
1522Method* InstanceKlass::lookup_method_in_ordered_interfaces(Symbol* name,
1523                                                         Symbol* signature) const {
1524  Method* m = NULL;
1525  if (default_methods() != NULL) {
1526    m = find_method(default_methods(), name, signature);
1527  }
1528  // Look up interfaces
1529  if (m == NULL) {
1530    m = lookup_method_in_all_interfaces(name, signature, normal);
1531  }
1532  return m;
1533}
1534
1535// lookup a method in all the interfaces that this class implements
1536// Do NOT return private or static methods, new in JDK8 which are not externally visible
1537// They should only be found in the initial InterfaceMethodRef
1538Method* InstanceKlass::lookup_method_in_all_interfaces(Symbol* name,
1539                                                       Symbol* signature,
1540                                                       MethodLookupMode mode) const {
1541  Array<Klass*>* all_ifs = transitive_interfaces();
1542  int num_ifs = all_ifs->length();
1543  InstanceKlass *ik = NULL;
1544  for (int i = 0; i < num_ifs; i++) {
1545    ik = InstanceKlass::cast(all_ifs->at(i));
1546    Method* m = ik->lookup_method(name, signature);
1547    if (m != NULL && m->is_public() && !m->is_static() &&
1548        ((mode != skip_defaults) || !m->is_default_method())) {
1549      return m;
1550    }
1551  }
1552  return NULL;
1553}
1554
1555/* jni_id_for_impl for jfieldIds only */
1556JNIid* InstanceKlass::jni_id_for_impl(instanceKlassHandle this_k, int offset) {
1557  MutexLocker ml(JfieldIdCreation_lock);
1558  // Retry lookup after we got the lock
1559  JNIid* probe = this_k->jni_ids() == NULL ? NULL : this_k->jni_ids()->find(offset);
1560  if (probe == NULL) {
1561    // Slow case, allocate new static field identifier
1562    probe = new JNIid(this_k(), offset, this_k->jni_ids());
1563    this_k->set_jni_ids(probe);
1564  }
1565  return probe;
1566}
1567
1568
1569/* jni_id_for for jfieldIds only */
1570JNIid* InstanceKlass::jni_id_for(int offset) {
1571  JNIid* probe = jni_ids() == NULL ? NULL : jni_ids()->find(offset);
1572  if (probe == NULL) {
1573    probe = jni_id_for_impl(this, offset);
1574  }
1575  return probe;
1576}
1577
1578u2 InstanceKlass::enclosing_method_data(int offset) {
1579  Array<jushort>* inner_class_list = inner_classes();
1580  if (inner_class_list == NULL) {
1581    return 0;
1582  }
1583  int length = inner_class_list->length();
1584  if (length % inner_class_next_offset == 0) {
1585    return 0;
1586  } else {
1587    int index = length - enclosing_method_attribute_size;
1588    assert(offset < enclosing_method_attribute_size, "invalid offset");
1589    return inner_class_list->at(index + offset);
1590  }
1591}
1592
1593void InstanceKlass::set_enclosing_method_indices(u2 class_index,
1594                                                 u2 method_index) {
1595  Array<jushort>* inner_class_list = inner_classes();
1596  assert (inner_class_list != NULL, "_inner_classes list is not set up");
1597  int length = inner_class_list->length();
1598  if (length % inner_class_next_offset == enclosing_method_attribute_size) {
1599    int index = length - enclosing_method_attribute_size;
1600    inner_class_list->at_put(
1601      index + enclosing_method_class_index_offset, class_index);
1602    inner_class_list->at_put(
1603      index + enclosing_method_method_index_offset, method_index);
1604  }
1605}
1606
1607// Lookup or create a jmethodID.
1608// This code is called by the VMThread and JavaThreads so the
1609// locking has to be done very carefully to avoid deadlocks
1610// and/or other cache consistency problems.
1611//
1612jmethodID InstanceKlass::get_jmethod_id(instanceKlassHandle ik_h, methodHandle method_h) {
1613  size_t idnum = (size_t)method_h->method_idnum();
1614  jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1615  size_t length = 0;
1616  jmethodID id = NULL;
1617
1618  // We use a double-check locking idiom here because this cache is
1619  // performance sensitive. In the normal system, this cache only
1620  // transitions from NULL to non-NULL which is safe because we use
1621  // release_set_methods_jmethod_ids() to advertise the new cache.
1622  // A partially constructed cache should never be seen by a racing
1623  // thread. We also use release_store_ptr() to save a new jmethodID
1624  // in the cache so a partially constructed jmethodID should never be
1625  // seen either. Cache reads of existing jmethodIDs proceed without a
1626  // lock, but cache writes of a new jmethodID requires uniqueness and
1627  // creation of the cache itself requires no leaks so a lock is
1628  // generally acquired in those two cases.
1629  //
1630  // If the RedefineClasses() API has been used, then this cache can
1631  // grow and we'll have transitions from non-NULL to bigger non-NULL.
1632  // Cache creation requires no leaks and we require safety between all
1633  // cache accesses and freeing of the old cache so a lock is generally
1634  // acquired when the RedefineClasses() API has been used.
1635
1636  if (jmeths != NULL) {
1637    // the cache already exists
1638    if (!ik_h->idnum_can_increment()) {
1639      // the cache can't grow so we can just get the current values
1640      get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1641    } else {
1642      // cache can grow so we have to be more careful
1643      if (Threads::number_of_threads() == 0 ||
1644          SafepointSynchronize::is_at_safepoint()) {
1645        // we're single threaded or at a safepoint - no locking needed
1646        get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1647      } else {
1648        MutexLocker ml(JmethodIdCreation_lock);
1649        get_jmethod_id_length_value(jmeths, idnum, &length, &id);
1650      }
1651    }
1652  }
1653  // implied else:
1654  // we need to allocate a cache so default length and id values are good
1655
1656  if (jmeths == NULL ||   // no cache yet
1657      length <= idnum ||  // cache is too short
1658      id == NULL) {       // cache doesn't contain entry
1659
1660    // This function can be called by the VMThread so we have to do all
1661    // things that might block on a safepoint before grabbing the lock.
1662    // Otherwise, we can deadlock with the VMThread or have a cache
1663    // consistency issue. These vars keep track of what we might have
1664    // to free after the lock is dropped.
1665    jmethodID  to_dealloc_id     = NULL;
1666    jmethodID* to_dealloc_jmeths = NULL;
1667
1668    // may not allocate new_jmeths or use it if we allocate it
1669    jmethodID* new_jmeths = NULL;
1670    if (length <= idnum) {
1671      // allocate a new cache that might be used
1672      size_t size = MAX2(idnum+1, (size_t)ik_h->idnum_allocated_count());
1673      new_jmeths = NEW_C_HEAP_ARRAY(jmethodID, size+1, mtClass);
1674      memset(new_jmeths, 0, (size+1)*sizeof(jmethodID));
1675      // cache size is stored in element[0], other elements offset by one
1676      new_jmeths[0] = (jmethodID)size;
1677    }
1678
1679    // allocate a new jmethodID that might be used
1680    jmethodID new_id = NULL;
1681    if (method_h->is_old() && !method_h->is_obsolete()) {
1682      // The method passed in is old (but not obsolete), we need to use the current version
1683      Method* current_method = ik_h->method_with_idnum((int)idnum);
1684      assert(current_method != NULL, "old and but not obsolete, so should exist");
1685      new_id = Method::make_jmethod_id(ik_h->class_loader_data(), current_method);
1686    } else {
1687      // It is the current version of the method or an obsolete method,
1688      // use the version passed in
1689      new_id = Method::make_jmethod_id(ik_h->class_loader_data(), method_h());
1690    }
1691
1692    if (Threads::number_of_threads() == 0 ||
1693        SafepointSynchronize::is_at_safepoint()) {
1694      // we're single threaded or at a safepoint - no locking needed
1695      id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1696                                          &to_dealloc_id, &to_dealloc_jmeths);
1697    } else {
1698      MutexLocker ml(JmethodIdCreation_lock);
1699      id = get_jmethod_id_fetch_or_update(ik_h, idnum, new_id, new_jmeths,
1700                                          &to_dealloc_id, &to_dealloc_jmeths);
1701    }
1702
1703    // The lock has been dropped so we can free resources.
1704    // Free up either the old cache or the new cache if we allocated one.
1705    if (to_dealloc_jmeths != NULL) {
1706      FreeHeap(to_dealloc_jmeths);
1707    }
1708    // free up the new ID since it wasn't needed
1709    if (to_dealloc_id != NULL) {
1710      Method::destroy_jmethod_id(ik_h->class_loader_data(), to_dealloc_id);
1711    }
1712  }
1713  return id;
1714}
1715
1716
1717// Common code to fetch the jmethodID from the cache or update the
1718// cache with the new jmethodID. This function should never do anything
1719// that causes the caller to go to a safepoint or we can deadlock with
1720// the VMThread or have cache consistency issues.
1721//
1722jmethodID InstanceKlass::get_jmethod_id_fetch_or_update(
1723            instanceKlassHandle ik_h, size_t idnum, jmethodID new_id,
1724            jmethodID* new_jmeths, jmethodID* to_dealloc_id_p,
1725            jmethodID** to_dealloc_jmeths_p) {
1726  assert(new_id != NULL, "sanity check");
1727  assert(to_dealloc_id_p != NULL, "sanity check");
1728  assert(to_dealloc_jmeths_p != NULL, "sanity check");
1729  assert(Threads::number_of_threads() == 0 ||
1730         SafepointSynchronize::is_at_safepoint() ||
1731         JmethodIdCreation_lock->owned_by_self(), "sanity check");
1732
1733  // reacquire the cache - we are locked, single threaded or at a safepoint
1734  jmethodID* jmeths = ik_h->methods_jmethod_ids_acquire();
1735  jmethodID  id     = NULL;
1736  size_t     length = 0;
1737
1738  if (jmeths == NULL ||                         // no cache yet
1739      (length = (size_t)jmeths[0]) <= idnum) {  // cache is too short
1740    if (jmeths != NULL) {
1741      // copy any existing entries from the old cache
1742      for (size_t index = 0; index < length; index++) {
1743        new_jmeths[index+1] = jmeths[index+1];
1744      }
1745      *to_dealloc_jmeths_p = jmeths;  // save old cache for later delete
1746    }
1747    ik_h->release_set_methods_jmethod_ids(jmeths = new_jmeths);
1748  } else {
1749    // fetch jmethodID (if any) from the existing cache
1750    id = jmeths[idnum+1];
1751    *to_dealloc_jmeths_p = new_jmeths;  // save new cache for later delete
1752  }
1753  if (id == NULL) {
1754    // No matching jmethodID in the existing cache or we have a new
1755    // cache or we just grew the cache. This cache write is done here
1756    // by the first thread to win the foot race because a jmethodID
1757    // needs to be unique once it is generally available.
1758    id = new_id;
1759
1760    // The jmethodID cache can be read while unlocked so we have to
1761    // make sure the new jmethodID is complete before installing it
1762    // in the cache.
1763    OrderAccess::release_store_ptr(&jmeths[idnum+1], id);
1764  } else {
1765    *to_dealloc_id_p = new_id; // save new id for later delete
1766  }
1767  return id;
1768}
1769
1770
1771// Common code to get the jmethodID cache length and the jmethodID
1772// value at index idnum if there is one.
1773//
1774void InstanceKlass::get_jmethod_id_length_value(jmethodID* cache,
1775       size_t idnum, size_t *length_p, jmethodID* id_p) {
1776  assert(cache != NULL, "sanity check");
1777  assert(length_p != NULL, "sanity check");
1778  assert(id_p != NULL, "sanity check");
1779
1780  // cache size is stored in element[0], other elements offset by one
1781  *length_p = (size_t)cache[0];
1782  if (*length_p <= idnum) {  // cache is too short
1783    *id_p = NULL;
1784  } else {
1785    *id_p = cache[idnum+1];  // fetch jmethodID (if any)
1786  }
1787}
1788
1789
1790// Lookup a jmethodID, NULL if not found.  Do no blocking, no allocations, no handles
1791jmethodID InstanceKlass::jmethod_id_or_null(Method* method) {
1792  size_t idnum = (size_t)method->method_idnum();
1793  jmethodID* jmeths = methods_jmethod_ids_acquire();
1794  size_t length;                                // length assigned as debugging crumb
1795  jmethodID id = NULL;
1796  if (jmeths != NULL &&                         // If there is a cache
1797      (length = (size_t)jmeths[0]) > idnum) {   // and if it is long enough,
1798    id = jmeths[idnum+1];                       // Look up the id (may be NULL)
1799  }
1800  return id;
1801}
1802
1803
1804//
1805// Walk the list of dependent nmethods searching for nmethods which
1806// are dependent on the changes that were passed in and mark them for
1807// deoptimization.  Returns the number of nmethods found.
1808//
1809int InstanceKlass::mark_dependent_nmethods(DepChange& changes) {
1810  assert_locked_or_safepoint(CodeCache_lock);
1811  int found = 0;
1812  nmethodBucket* b = _dependencies;
1813  while (b != NULL) {
1814    nmethod* nm = b->get_nmethod();
1815    // since dependencies aren't removed until an nmethod becomes a zombie,
1816    // the dependency list may contain nmethods which aren't alive.
1817    if (nm->is_alive() && !nm->is_marked_for_deoptimization() && nm->check_dependency_on(changes)) {
1818      if (TraceDependencies) {
1819        ResourceMark rm;
1820        tty->print_cr("Marked for deoptimization");
1821        tty->print_cr("  context = %s", this->external_name());
1822        changes.print();
1823        nm->print();
1824        nm->print_dependencies();
1825      }
1826      nm->mark_for_deoptimization();
1827      found++;
1828    }
1829    b = b->next();
1830  }
1831  return found;
1832}
1833
1834
1835//
1836// Add an nmethodBucket to the list of dependencies for this nmethod.
1837// It's possible that an nmethod has multiple dependencies on this klass
1838// so a count is kept for each bucket to guarantee that creation and
1839// deletion of dependencies is consistent.
1840//
1841void InstanceKlass::add_dependent_nmethod(nmethod* nm) {
1842  assert_locked_or_safepoint(CodeCache_lock);
1843  nmethodBucket* b = _dependencies;
1844  nmethodBucket* last = NULL;
1845  while (b != NULL) {
1846    if (nm == b->get_nmethod()) {
1847      b->increment();
1848      return;
1849    }
1850    b = b->next();
1851  }
1852  _dependencies = new nmethodBucket(nm, _dependencies);
1853}
1854
1855
1856//
1857// Decrement count of the nmethod in the dependency list and remove
1858// the bucket competely when the count goes to 0.  This method must
1859// find a corresponding bucket otherwise there's a bug in the
1860// recording of dependecies.
1861//
1862void InstanceKlass::remove_dependent_nmethod(nmethod* nm) {
1863  assert_locked_or_safepoint(CodeCache_lock);
1864  nmethodBucket* b = _dependencies;
1865  nmethodBucket* last = NULL;
1866  while (b != NULL) {
1867    if (nm == b->get_nmethod()) {
1868      if (b->decrement() == 0) {
1869        if (last == NULL) {
1870          _dependencies = b->next();
1871        } else {
1872          last->set_next(b->next());
1873        }
1874        delete b;
1875      }
1876      return;
1877    }
1878    last = b;
1879    b = b->next();
1880  }
1881#ifdef ASSERT
1882  tty->print_cr("### %s can't find dependent nmethod:", this->external_name());
1883  nm->print();
1884#endif // ASSERT
1885  ShouldNotReachHere();
1886}
1887
1888
1889#ifndef PRODUCT
1890void InstanceKlass::print_dependent_nmethods(bool verbose) {
1891  nmethodBucket* b = _dependencies;
1892  int idx = 0;
1893  while (b != NULL) {
1894    nmethod* nm = b->get_nmethod();
1895    tty->print("[%d] count=%d { ", idx++, b->count());
1896    if (!verbose) {
1897      nm->print_on(tty, "nmethod");
1898      tty->print_cr(" } ");
1899    } else {
1900      nm->print();
1901      nm->print_dependencies();
1902      tty->print_cr("--- } ");
1903    }
1904    b = b->next();
1905  }
1906}
1907
1908
1909bool InstanceKlass::is_dependent_nmethod(nmethod* nm) {
1910  nmethodBucket* b = _dependencies;
1911  while (b != NULL) {
1912    if (nm == b->get_nmethod()) {
1913      return true;
1914    }
1915    b = b->next();
1916  }
1917  return false;
1918}
1919#endif //PRODUCT
1920
1921
1922// Garbage collection
1923
1924#ifdef ASSERT
1925template <class T> void assert_is_in(T *p) {
1926  T heap_oop = oopDesc::load_heap_oop(p);
1927  if (!oopDesc::is_null(heap_oop)) {
1928    oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1929    assert(Universe::heap()->is_in(o), "should be in heap");
1930  }
1931}
1932template <class T> void assert_is_in_closed_subset(T *p) {
1933  T heap_oop = oopDesc::load_heap_oop(p);
1934  if (!oopDesc::is_null(heap_oop)) {
1935    oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1936    assert(Universe::heap()->is_in_closed_subset(o),
1937           err_msg("should be in closed *p " INTPTR_FORMAT " " INTPTR_FORMAT, (address)p, (address)o));
1938  }
1939}
1940template <class T> void assert_is_in_reserved(T *p) {
1941  T heap_oop = oopDesc::load_heap_oop(p);
1942  if (!oopDesc::is_null(heap_oop)) {
1943    oop o = oopDesc::decode_heap_oop_not_null(heap_oop);
1944    assert(Universe::heap()->is_in_reserved(o), "should be in reserved");
1945  }
1946}
1947template <class T> void assert_nothing(T *p) {}
1948
1949#else
1950template <class T> void assert_is_in(T *p) {}
1951template <class T> void assert_is_in_closed_subset(T *p) {}
1952template <class T> void assert_is_in_reserved(T *p) {}
1953template <class T> void assert_nothing(T *p) {}
1954#endif // ASSERT
1955
1956//
1957// Macros that iterate over areas of oops which are specialized on type of
1958// oop pointer either narrow or wide, depending on UseCompressedOops
1959//
1960// Parameters are:
1961//   T         - type of oop to point to (either oop or narrowOop)
1962//   start_p   - starting pointer for region to iterate over
1963//   count     - number of oops or narrowOops to iterate over
1964//   do_oop    - action to perform on each oop (it's arbitrary C code which
1965//               makes it more efficient to put in a macro rather than making
1966//               it a template function)
1967//   assert_fn - assert function which is template function because performance
1968//               doesn't matter when enabled.
1969#define InstanceKlass_SPECIALIZED_OOP_ITERATE( \
1970  T, start_p, count, do_oop,                \
1971  assert_fn)                                \
1972{                                           \
1973  T* p         = (T*)(start_p);             \
1974  T* const end = p + (count);               \
1975  while (p < end) {                         \
1976    (assert_fn)(p);                         \
1977    do_oop;                                 \
1978    ++p;                                    \
1979  }                                         \
1980}
1981
1982#define InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE( \
1983  T, start_p, count, do_oop,                \
1984  assert_fn)                                \
1985{                                           \
1986  T* const start = (T*)(start_p);           \
1987  T*       p     = start + (count);         \
1988  while (start < p) {                       \
1989    --p;                                    \
1990    (assert_fn)(p);                         \
1991    do_oop;                                 \
1992  }                                         \
1993}
1994
1995#define InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE( \
1996  T, start_p, count, low, high,             \
1997  do_oop, assert_fn)                        \
1998{                                           \
1999  T* const l = (T*)(low);                   \
2000  T* const h = (T*)(high);                  \
2001  assert(mask_bits((intptr_t)l, sizeof(T)-1) == 0 && \
2002         mask_bits((intptr_t)h, sizeof(T)-1) == 0,   \
2003         "bounded region must be properly aligned"); \
2004  T* p       = (T*)(start_p);               \
2005  T* end     = p + (count);                 \
2006  if (p < l) p = l;                         \
2007  if (end > h) end = h;                     \
2008  while (p < end) {                         \
2009    (assert_fn)(p);                         \
2010    do_oop;                                 \
2011    ++p;                                    \
2012  }                                         \
2013}
2014
2015
2016// The following macros call specialized macros, passing either oop or
2017// narrowOop as the specialization type.  These test the UseCompressedOops
2018// flag.
2019#define InstanceKlass_OOP_MAP_ITERATE(obj, do_oop, assert_fn)            \
2020{                                                                        \
2021  /* Compute oopmap block range. The common case                         \
2022     is nonstatic_oop_map_size == 1. */                                  \
2023  OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
2024  OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
2025  if (UseCompressedOops) {                                               \
2026    while (map < end_map) {                                              \
2027      InstanceKlass_SPECIALIZED_OOP_ITERATE(narrowOop,                   \
2028        obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2029        do_oop, assert_fn)                                               \
2030      ++map;                                                             \
2031    }                                                                    \
2032  } else {                                                               \
2033    while (map < end_map) {                                              \
2034      InstanceKlass_SPECIALIZED_OOP_ITERATE(oop,                         \
2035        obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2036        do_oop, assert_fn)                                               \
2037      ++map;                                                             \
2038    }                                                                    \
2039  }                                                                      \
2040}
2041
2042#define InstanceKlass_OOP_MAP_REVERSE_ITERATE(obj, do_oop, assert_fn)    \
2043{                                                                        \
2044  OopMapBlock* const start_map = start_of_nonstatic_oop_maps();          \
2045  OopMapBlock* map             = start_map + nonstatic_oop_map_count();  \
2046  if (UseCompressedOops) {                                               \
2047    while (start_map < map) {                                            \
2048      --map;                                                             \
2049      InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(narrowOop,           \
2050        obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2051        do_oop, assert_fn)                                               \
2052    }                                                                    \
2053  } else {                                                               \
2054    while (start_map < map) {                                            \
2055      --map;                                                             \
2056      InstanceKlass_SPECIALIZED_OOP_REVERSE_ITERATE(oop,                 \
2057        obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2058        do_oop, assert_fn)                                               \
2059    }                                                                    \
2060  }                                                                      \
2061}
2062
2063#define InstanceKlass_BOUNDED_OOP_MAP_ITERATE(obj, low, high, do_oop,    \
2064                                              assert_fn)                 \
2065{                                                                        \
2066  /* Compute oopmap block range. The common case is                      \
2067     nonstatic_oop_map_size == 1, so we accept the                       \
2068     usually non-existent extra overhead of examining                    \
2069     all the maps. */                                                    \
2070  OopMapBlock* map           = start_of_nonstatic_oop_maps();            \
2071  OopMapBlock* const end_map = map + nonstatic_oop_map_count();          \
2072  if (UseCompressedOops) {                                               \
2073    while (map < end_map) {                                              \
2074      InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(narrowOop,           \
2075        obj->obj_field_addr<narrowOop>(map->offset()), map->count(),     \
2076        low, high,                                                       \
2077        do_oop, assert_fn)                                               \
2078      ++map;                                                             \
2079    }                                                                    \
2080  } else {                                                               \
2081    while (map < end_map) {                                              \
2082      InstanceKlass_SPECIALIZED_BOUNDED_OOP_ITERATE(oop,                 \
2083        obj->obj_field_addr<oop>(map->offset()), map->count(),           \
2084        low, high,                                                       \
2085        do_oop, assert_fn)                                               \
2086      ++map;                                                             \
2087    }                                                                    \
2088  }                                                                      \
2089}
2090
2091void InstanceKlass::oop_follow_contents(oop obj) {
2092  assert(obj != NULL, "can't follow the content of NULL object");
2093  MarkSweep::follow_klass(obj->klass());
2094  InstanceKlass_OOP_MAP_ITERATE( \
2095    obj, \
2096    MarkSweep::mark_and_push(p), \
2097    assert_is_in_closed_subset)
2098}
2099
2100#if INCLUDE_ALL_GCS
2101void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
2102                                        oop obj) {
2103  assert(obj != NULL, "can't follow the content of NULL object");
2104  PSParallelCompact::follow_klass(cm, obj->klass());
2105  // Only mark the header and let the scan of the meta-data mark
2106  // everything else.
2107  InstanceKlass_OOP_MAP_ITERATE( \
2108    obj, \
2109    PSParallelCompact::mark_and_push(cm, p), \
2110    assert_is_in)
2111}
2112#endif // INCLUDE_ALL_GCS
2113
2114// closure's do_metadata() method dictates whether the given closure should be
2115// applied to the klass ptr in the object header.
2116
2117#define if_do_metadata_checked(closure, nv_suffix)                    \
2118  /* Make sure the non-virtual and the virtual versions match. */     \
2119  assert(closure->do_metadata##nv_suffix() == closure->do_metadata(), \
2120      "Inconsistency in do_metadata");                                \
2121  if (closure->do_metadata##nv_suffix())
2122
2123#define InstanceKlass_OOP_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)        \
2124                                                                             \
2125int InstanceKlass::oop_oop_iterate##nv_suffix(oop obj, OopClosureType* closure) { \
2126  SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2127  /* header */                                                          \
2128  if_do_metadata_checked(closure, nv_suffix) {                          \
2129    closure->do_klass##nv_suffix(obj->klass());                         \
2130  }                                                                     \
2131  InstanceKlass_OOP_MAP_ITERATE(                                        \
2132    obj,                                                                \
2133    SpecializationStats::                                               \
2134      record_do_oop_call##nv_suffix(SpecializationStats::ik);           \
2135    (closure)->do_oop##nv_suffix(p),                                    \
2136    assert_is_in_closed_subset)                                         \
2137  return size_helper();                                                 \
2138}
2139
2140#if INCLUDE_ALL_GCS
2141#define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
2142                                                                                \
2143int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
2144                                              OopClosureType* closure) {        \
2145  SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik); \
2146  /* header */                                                                  \
2147  if_do_metadata_checked(closure, nv_suffix) {                                  \
2148    closure->do_klass##nv_suffix(obj->klass());                                 \
2149  }                                                                             \
2150  /* instance variables */                                                      \
2151  InstanceKlass_OOP_MAP_REVERSE_ITERATE(                                        \
2152    obj,                                                                        \
2153    SpecializationStats::record_do_oop_call##nv_suffix(SpecializationStats::ik);\
2154    (closure)->do_oop##nv_suffix(p),                                            \
2155    assert_is_in_closed_subset)                                                 \
2156   return size_helper();                                                        \
2157}
2158#endif // INCLUDE_ALL_GCS
2159
2160#define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
2161                                                                        \
2162int InstanceKlass::oop_oop_iterate##nv_suffix##_m(oop obj,              \
2163                                                  OopClosureType* closure, \
2164                                                  MemRegion mr) {          \
2165  SpecializationStats::record_iterate_call##nv_suffix(SpecializationStats::ik);\
2166  if_do_metadata_checked(closure, nv_suffix) {                           \
2167    if (mr.contains(obj)) {                                              \
2168      closure->do_klass##nv_suffix(obj->klass());                        \
2169    }                                                                    \
2170  }                                                                      \
2171  InstanceKlass_BOUNDED_OOP_MAP_ITERATE(                                 \
2172    obj, mr.start(), mr.end(),                                           \
2173    (closure)->do_oop##nv_suffix(p),                                     \
2174    assert_is_in_closed_subset)                                          \
2175  return size_helper();                                                  \
2176}
2177
2178ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2179ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
2180ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2181ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
2182#if INCLUDE_ALL_GCS
2183ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2184ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
2185#endif // INCLUDE_ALL_GCS
2186
2187int InstanceKlass::oop_adjust_pointers(oop obj) {
2188  int size = size_helper();
2189  InstanceKlass_OOP_MAP_ITERATE( \
2190    obj, \
2191    MarkSweep::adjust_pointer(p), \
2192    assert_is_in)
2193  return size;
2194}
2195
2196#if INCLUDE_ALL_GCS
2197void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
2198  InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
2199    obj, \
2200    if (PSScavenge::should_scavenge(p)) { \
2201      pm->claim_or_forward_depth(p); \
2202    }, \
2203    assert_nothing )
2204}
2205
2206int InstanceKlass::oop_update_pointers(ParCompactionManager* cm, oop obj) {
2207  int size = size_helper();
2208  InstanceKlass_OOP_MAP_ITERATE( \
2209    obj, \
2210    PSParallelCompact::adjust_pointer(p), \
2211    assert_is_in)
2212  return size;
2213}
2214
2215#endif // INCLUDE_ALL_GCS
2216
2217void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
2218  assert(is_loader_alive(is_alive), "this klass should be live");
2219  if (is_interface()) {
2220    if (ClassUnloading) {
2221      Klass* impl = implementor();
2222      if (impl != NULL) {
2223        if (!impl->is_loader_alive(is_alive)) {
2224          // remove this guy
2225          Klass** klass = adr_implementor();
2226          assert(klass != NULL, "null klass");
2227          if (klass != NULL) {
2228            *klass = NULL;
2229          }
2230        }
2231      }
2232    }
2233  }
2234}
2235
2236void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
2237  for (int m = 0; m < methods()->length(); m++) {
2238    MethodData* mdo = methods()->at(m)->method_data();
2239    if (mdo != NULL) {
2240      mdo->clean_method_data(is_alive);
2241    }
2242  }
2243}
2244
2245
2246static void remove_unshareable_in_class(Klass* k) {
2247  // remove klass's unshareable info
2248  k->remove_unshareable_info();
2249}
2250
2251void InstanceKlass::remove_unshareable_info() {
2252  Klass::remove_unshareable_info();
2253  // Unlink the class
2254  if (is_linked()) {
2255    unlink_class();
2256  }
2257  init_implementor();
2258
2259  constants()->remove_unshareable_info();
2260
2261  for (int i = 0; i < methods()->length(); i++) {
2262    Method* m = methods()->at(i);
2263    m->remove_unshareable_info();
2264  }
2265
2266  // do array classes also.
2267  array_klasses_do(remove_unshareable_in_class);
2268}
2269
2270void restore_unshareable_in_class(Klass* k, TRAPS) {
2271  k->restore_unshareable_info(CHECK);
2272}
2273
2274void InstanceKlass::restore_unshareable_info(TRAPS) {
2275  Klass::restore_unshareable_info(CHECK);
2276  instanceKlassHandle ik(THREAD, this);
2277
2278  Array<Method*>* methods = ik->methods();
2279  int num_methods = methods->length();
2280  for (int index2 = 0; index2 < num_methods; ++index2) {
2281    methodHandle m(THREAD, methods->at(index2));
2282    m->restore_unshareable_info(CHECK);
2283  }
2284  if (JvmtiExport::has_redefined_a_class()) {
2285    // Reinitialize vtable because RedefineClasses may have changed some
2286    // entries in this vtable for super classes so the CDS vtable might
2287    // point to old or obsolete entries.  RedefineClasses doesn't fix up
2288    // vtables in the shared system dictionary, only the main one.
2289    // It also redefines the itable too so fix that too.
2290    ResourceMark rm(THREAD);
2291    ik->vtable()->initialize_vtable(false, CHECK);
2292    ik->itable()->initialize_itable(false, CHECK);
2293  }
2294
2295  // restore constant pool resolved references
2296  ik->constants()->restore_unshareable_info(CHECK);
2297
2298  ik->array_klasses_do(restore_unshareable_in_class, CHECK);
2299}
2300
2301static void clear_all_breakpoints(Method* m) {
2302  m->clear_all_breakpoints();
2303}
2304
2305
2306void InstanceKlass::notify_unload_class(InstanceKlass* ik) {
2307  // notify the debugger
2308  if (JvmtiExport::should_post_class_unload()) {
2309    JvmtiExport::post_class_unload(ik);
2310  }
2311
2312  // notify ClassLoadingService of class unload
2313  ClassLoadingService::notify_class_unloaded(ik);
2314}
2315
2316void InstanceKlass::release_C_heap_structures(InstanceKlass* ik) {
2317  // Clean up C heap
2318  ik->release_C_heap_structures();
2319  ik->constants()->release_C_heap_structures();
2320}
2321
2322void InstanceKlass::release_C_heap_structures() {
2323
2324  // Can't release the constant pool here because the constant pool can be
2325  // deallocated separately from the InstanceKlass for default methods and
2326  // redefine classes.
2327
2328  // Deallocate oop map cache
2329  if (_oop_map_cache != NULL) {
2330    delete _oop_map_cache;
2331    _oop_map_cache = NULL;
2332  }
2333
2334  // Deallocate JNI identifiers for jfieldIDs
2335  JNIid::deallocate(jni_ids());
2336  set_jni_ids(NULL);
2337
2338  jmethodID* jmeths = methods_jmethod_ids_acquire();
2339  if (jmeths != (jmethodID*)NULL) {
2340    release_set_methods_jmethod_ids(NULL);
2341    FreeHeap(jmeths);
2342  }
2343
2344  // Deallocate MemberNameTable
2345  {
2346    Mutex* lock_or_null = SafepointSynchronize::is_at_safepoint() ? NULL : MemberNameTable_lock;
2347    MutexLockerEx ml(lock_or_null, Mutex::_no_safepoint_check_flag);
2348    MemberNameTable* mnt = member_names();
2349    if (mnt != NULL) {
2350      delete mnt;
2351      set_member_names(NULL);
2352    }
2353  }
2354
2355  // release dependencies
2356  nmethodBucket* b = _dependencies;
2357  _dependencies = NULL;
2358  while (b != NULL) {
2359    nmethodBucket* next = b->next();
2360    delete b;
2361    b = next;
2362  }
2363
2364  // Deallocate breakpoint records
2365  if (breakpoints() != 0x0) {
2366    methods_do(clear_all_breakpoints);
2367    assert(breakpoints() == 0x0, "should have cleared breakpoints");
2368  }
2369
2370  // deallocate information about previous versions
2371  if (_previous_versions != NULL) {
2372    for (int i = _previous_versions->length() - 1; i >= 0; i--) {
2373      PreviousVersionNode * pv_node = _previous_versions->at(i);
2374      delete pv_node;
2375    }
2376    delete _previous_versions;
2377    _previous_versions = NULL;
2378  }
2379
2380  // deallocate the cached class file
2381  if (_cached_class_file != NULL) {
2382    os::free(_cached_class_file, mtClass);
2383    _cached_class_file = NULL;
2384  }
2385
2386  // Decrement symbol reference counts associated with the unloaded class.
2387  if (_name != NULL) _name->decrement_refcount();
2388  // unreference array name derived from this class name (arrays of an unloaded
2389  // class can't be referenced anymore).
2390  if (_array_name != NULL)  _array_name->decrement_refcount();
2391  if (_source_debug_extension != NULL) FREE_C_HEAP_ARRAY(char, _source_debug_extension, mtClass);
2392
2393  assert(_total_instanceKlass_count >= 1, "Sanity check");
2394  Atomic::dec(&_total_instanceKlass_count);
2395}
2396
2397void InstanceKlass::set_source_debug_extension(char* array, int length) {
2398  if (array == NULL) {
2399    _source_debug_extension = NULL;
2400  } else {
2401    // Adding one to the attribute length in order to store a null terminator
2402    // character could cause an overflow because the attribute length is
2403    // already coded with an u4 in the classfile, but in practice, it's
2404    // unlikely to happen.
2405    assert((length+1) > length, "Overflow checking");
2406    char* sde = NEW_C_HEAP_ARRAY(char, (length + 1), mtClass);
2407    for (int i = 0; i < length; i++) {
2408      sde[i] = array[i];
2409    }
2410    sde[length] = '\0';
2411    _source_debug_extension = sde;
2412  }
2413}
2414
2415address InstanceKlass::static_field_addr(int offset) {
2416  return (address)(offset + InstanceMirrorKlass::offset_of_static_fields() + cast_from_oop<intptr_t>(java_mirror()));
2417}
2418
2419
2420const char* InstanceKlass::signature_name() const {
2421  int hash_len = 0;
2422  char hash_buf[40];
2423
2424  // If this is an anonymous class, append a hash to make the name unique
2425  if (is_anonymous()) {
2426    intptr_t hash = (java_mirror() != NULL) ? java_mirror()->identity_hash() : 0;
2427    sprintf(hash_buf, "/" UINTX_FORMAT, (uintx)hash);
2428    hash_len = (int)strlen(hash_buf);
2429  }
2430
2431  // Get the internal name as a c string
2432  const char* src = (const char*) (name()->as_C_string());
2433  const int src_length = (int)strlen(src);
2434
2435  char* dest = NEW_RESOURCE_ARRAY(char, src_length + hash_len + 3);
2436
2437  // Add L as type indicator
2438  int dest_index = 0;
2439  dest[dest_index++] = 'L';
2440
2441  // Add the actual class name
2442  for (int src_index = 0; src_index < src_length; ) {
2443    dest[dest_index++] = src[src_index++];
2444  }
2445
2446  // If we have a hash, append it
2447  for (int hash_index = 0; hash_index < hash_len; ) {
2448    dest[dest_index++] = hash_buf[hash_index++];
2449  }
2450
2451  // Add the semicolon and the NULL
2452  dest[dest_index++] = ';';
2453  dest[dest_index] = '\0';
2454  return dest;
2455}
2456
2457// different verisons of is_same_class_package
2458bool InstanceKlass::is_same_class_package(Klass* class2) {
2459  Klass* class1 = this;
2460  oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2461  Symbol* classname1 = class1->name();
2462
2463  if (class2->oop_is_objArray()) {
2464    class2 = ObjArrayKlass::cast(class2)->bottom_klass();
2465  }
2466  oop classloader2;
2467  if (class2->oop_is_instance()) {
2468    classloader2 = InstanceKlass::cast(class2)->class_loader();
2469  } else {
2470    assert(class2->oop_is_typeArray(), "should be type array");
2471    classloader2 = NULL;
2472  }
2473  Symbol* classname2 = class2->name();
2474
2475  return InstanceKlass::is_same_class_package(classloader1, classname1,
2476                                              classloader2, classname2);
2477}
2478
2479bool InstanceKlass::is_same_class_package(oop classloader2, Symbol* classname2) {
2480  Klass* class1 = this;
2481  oop classloader1 = InstanceKlass::cast(class1)->class_loader();
2482  Symbol* classname1 = class1->name();
2483
2484  return InstanceKlass::is_same_class_package(classloader1, classname1,
2485                                              classloader2, classname2);
2486}
2487
2488// return true if two classes are in the same package, classloader
2489// and classname information is enough to determine a class's package
2490bool InstanceKlass::is_same_class_package(oop class_loader1, Symbol* class_name1,
2491                                          oop class_loader2, Symbol* class_name2) {
2492  if (class_loader1 != class_loader2) {
2493    return false;
2494  } else if (class_name1 == class_name2) {
2495    return true;                // skip painful bytewise comparison
2496  } else {
2497    ResourceMark rm;
2498
2499    // The Symbol*'s are in UTF8 encoding. Since we only need to check explicitly
2500    // for ASCII characters ('/', 'L', '['), we can keep them in UTF8 encoding.
2501    // Otherwise, we just compare jbyte values between the strings.
2502    const jbyte *name1 = class_name1->base();
2503    const jbyte *name2 = class_name2->base();
2504
2505    const jbyte *last_slash1 = UTF8::strrchr(name1, class_name1->utf8_length(), '/');
2506    const jbyte *last_slash2 = UTF8::strrchr(name2, class_name2->utf8_length(), '/');
2507
2508    if ((last_slash1 == NULL) || (last_slash2 == NULL)) {
2509      // One of the two doesn't have a package.  Only return true
2510      // if the other one also doesn't have a package.
2511      return last_slash1 == last_slash2;
2512    } else {
2513      // Skip over '['s
2514      if (*name1 == '[') {
2515        do {
2516          name1++;
2517        } while (*name1 == '[');
2518        if (*name1 != 'L') {
2519          // Something is terribly wrong.  Shouldn't be here.
2520          return false;
2521        }
2522      }
2523      if (*name2 == '[') {
2524        do {
2525          name2++;
2526        } while (*name2 == '[');
2527        if (*name2 != 'L') {
2528          // Something is terribly wrong.  Shouldn't be here.
2529          return false;
2530        }
2531      }
2532
2533      // Check that package part is identical
2534      int length1 = last_slash1 - name1;
2535      int length2 = last_slash2 - name2;
2536
2537      return UTF8::equal(name1, length1, name2, length2);
2538    }
2539  }
2540}
2541
2542// Returns true iff super_method can be overridden by a method in targetclassname
2543// See JSL 3rd edition 8.4.6.1
2544// Assumes name-signature match
2545// "this" is InstanceKlass of super_method which must exist
2546// note that the InstanceKlass of the method in the targetclassname has not always been created yet
2547bool InstanceKlass::is_override(methodHandle super_method, Handle targetclassloader, Symbol* targetclassname, TRAPS) {
2548   // Private methods can not be overridden
2549   if (super_method->is_private()) {
2550     return false;
2551   }
2552   // If super method is accessible, then override
2553   if ((super_method->is_protected()) ||
2554       (super_method->is_public())) {
2555     return true;
2556   }
2557   // Package-private methods are not inherited outside of package
2558   assert(super_method->is_package_private(), "must be package private");
2559   return(is_same_class_package(targetclassloader(), targetclassname));
2560}
2561
2562/* defined for now in jvm.cpp, for historical reasons *--
2563Klass* InstanceKlass::compute_enclosing_class_impl(instanceKlassHandle self,
2564                                                     Symbol*& simple_name_result, TRAPS) {
2565  ...
2566}
2567*/
2568
2569// tell if two classes have the same enclosing class (at package level)
2570bool InstanceKlass::is_same_package_member_impl(instanceKlassHandle class1,
2571                                                Klass* class2_oop, TRAPS) {
2572  if (class2_oop == class1())                       return true;
2573  if (!class2_oop->oop_is_instance())  return false;
2574  instanceKlassHandle class2(THREAD, class2_oop);
2575
2576  // must be in same package before we try anything else
2577  if (!class1->is_same_class_package(class2->class_loader(), class2->name()))
2578    return false;
2579
2580  // As long as there is an outer1.getEnclosingClass,
2581  // shift the search outward.
2582  instanceKlassHandle outer1 = class1;
2583  for (;;) {
2584    // As we walk along, look for equalities between outer1 and class2.
2585    // Eventually, the walks will terminate as outer1 stops
2586    // at the top-level class around the original class.
2587    bool ignore_inner_is_member;
2588    Klass* next = outer1->compute_enclosing_class(&ignore_inner_is_member,
2589                                                    CHECK_false);
2590    if (next == NULL)  break;
2591    if (next == class2())  return true;
2592    outer1 = instanceKlassHandle(THREAD, next);
2593  }
2594
2595  // Now do the same for class2.
2596  instanceKlassHandle outer2 = class2;
2597  for (;;) {
2598    bool ignore_inner_is_member;
2599    Klass* next = outer2->compute_enclosing_class(&ignore_inner_is_member,
2600                                                    CHECK_false);
2601    if (next == NULL)  break;
2602    // Might as well check the new outer against all available values.
2603    if (next == class1())  return true;
2604    if (next == outer1())  return true;
2605    outer2 = instanceKlassHandle(THREAD, next);
2606  }
2607
2608  // If by this point we have not found an equality between the
2609  // two classes, we know they are in separate package members.
2610  return false;
2611}
2612
2613
2614jint InstanceKlass::compute_modifier_flags(TRAPS) const {
2615  jint access = access_flags().as_int();
2616
2617  // But check if it happens to be member class.
2618  instanceKlassHandle ik(THREAD, this);
2619  InnerClassesIterator iter(ik);
2620  for (; !iter.done(); iter.next()) {
2621    int ioff = iter.inner_class_info_index();
2622    // Inner class attribute can be zero, skip it.
2623    // Strange but true:  JVM spec. allows null inner class refs.
2624    if (ioff == 0) continue;
2625
2626    // only look at classes that are already loaded
2627    // since we are looking for the flags for our self.
2628    Symbol* inner_name = ik->constants()->klass_name_at(ioff);
2629    if ((ik->name() == inner_name)) {
2630      // This is really a member class.
2631      access = iter.inner_access_flags();
2632      break;
2633    }
2634  }
2635  // Remember to strip ACC_SUPER bit
2636  return (access & (~JVM_ACC_SUPER)) & JVM_ACC_WRITTEN_FLAGS;
2637}
2638
2639jint InstanceKlass::jvmti_class_status() const {
2640  jint result = 0;
2641
2642  if (is_linked()) {
2643    result |= JVMTI_CLASS_STATUS_VERIFIED | JVMTI_CLASS_STATUS_PREPARED;
2644  }
2645
2646  if (is_initialized()) {
2647    assert(is_linked(), "Class status is not consistent");
2648    result |= JVMTI_CLASS_STATUS_INITIALIZED;
2649  }
2650  if (is_in_error_state()) {
2651    result |= JVMTI_CLASS_STATUS_ERROR;
2652  }
2653  return result;
2654}
2655
2656Method* InstanceKlass::method_at_itable(Klass* holder, int index, TRAPS) {
2657  itableOffsetEntry* ioe = (itableOffsetEntry*)start_of_itable();
2658  int method_table_offset_in_words = ioe->offset()/wordSize;
2659  int nof_interfaces = (method_table_offset_in_words - itable_offset_in_words())
2660                       / itableOffsetEntry::size();
2661
2662  for (int cnt = 0 ; ; cnt ++, ioe ++) {
2663    // If the interface isn't implemented by the receiver class,
2664    // the VM should throw IncompatibleClassChangeError.
2665    if (cnt >= nof_interfaces) {
2666      THROW_NULL(vmSymbols::java_lang_IncompatibleClassChangeError());
2667    }
2668
2669    Klass* ik = ioe->interface_klass();
2670    if (ik == holder) break;
2671  }
2672
2673  itableMethodEntry* ime = ioe->first_method_entry(this);
2674  Method* m = ime[index].method();
2675  if (m == NULL) {
2676    THROW_NULL(vmSymbols::java_lang_AbstractMethodError());
2677  }
2678  return m;
2679}
2680
2681
2682#if INCLUDE_JVMTI
2683// update default_methods for redefineclasses for methods that are
2684// not yet in the vtable due to concurrent subclass define and superinterface
2685// redefinition
2686// Note: those in the vtable, should have been updated via adjust_method_entries
2687void InstanceKlass::adjust_default_methods(Method** old_methods, Method** new_methods,
2688                                           int methods_length, bool* trace_name_printed) {
2689  // search the default_methods for uses of either obsolete or EMCP methods
2690  if (default_methods() != NULL) {
2691    for (int j = 0; j < methods_length; j++) {
2692      Method* old_method = old_methods[j];
2693      Method* new_method = new_methods[j];
2694
2695      for (int index = 0; index < default_methods()->length(); index ++) {
2696        if (default_methods()->at(index) == old_method) {
2697          default_methods()->at_put(index, new_method);
2698          if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
2699            if (!(*trace_name_printed)) {
2700              // RC_TRACE_MESG macro has an embedded ResourceMark
2701              RC_TRACE_MESG(("adjust: klassname=%s default methods from name=%s",
2702                             external_name(),
2703                             old_method->method_holder()->external_name()));
2704              *trace_name_printed = true;
2705            }
2706            RC_TRACE(0x00100000, ("default method update: %s(%s) ",
2707                                  new_method->name()->as_C_string(),
2708                                  new_method->signature()->as_C_string()));
2709          }
2710        }
2711      }
2712    }
2713  }
2714}
2715#endif // INCLUDE_JVMTI
2716
2717// On-stack replacement stuff
2718void InstanceKlass::add_osr_nmethod(nmethod* n) {
2719  // only one compilation can be active
2720  NEEDS_CLEANUP
2721  // This is a short non-blocking critical region, so the no safepoint check is ok.
2722  OsrList_lock->lock_without_safepoint_check();
2723  assert(n->is_osr_method(), "wrong kind of nmethod");
2724  n->set_osr_link(osr_nmethods_head());
2725  set_osr_nmethods_head(n);
2726  // Raise the highest osr level if necessary
2727  if (TieredCompilation) {
2728    Method* m = n->method();
2729    m->set_highest_osr_comp_level(MAX2(m->highest_osr_comp_level(), n->comp_level()));
2730  }
2731  // Remember to unlock again
2732  OsrList_lock->unlock();
2733
2734  // Get rid of the osr methods for the same bci that have lower levels.
2735  if (TieredCompilation) {
2736    for (int l = CompLevel_limited_profile; l < n->comp_level(); l++) {
2737      nmethod *inv = lookup_osr_nmethod(n->method(), n->osr_entry_bci(), l, true);
2738      if (inv != NULL && inv->is_in_use()) {
2739        inv->make_not_entrant();
2740      }
2741    }
2742  }
2743}
2744
2745
2746void InstanceKlass::remove_osr_nmethod(nmethod* n) {
2747  // This is a short non-blocking critical region, so the no safepoint check is ok.
2748  OsrList_lock->lock_without_safepoint_check();
2749  assert(n->is_osr_method(), "wrong kind of nmethod");
2750  nmethod* last = NULL;
2751  nmethod* cur  = osr_nmethods_head();
2752  int max_level = CompLevel_none;  // Find the max comp level excluding n
2753  Method* m = n->method();
2754  // Search for match
2755  while(cur != NULL && cur != n) {
2756    if (TieredCompilation && m == cur->method()) {
2757      // Find max level before n
2758      max_level = MAX2(max_level, cur->comp_level());
2759    }
2760    last = cur;
2761    cur = cur->osr_link();
2762  }
2763  nmethod* next = NULL;
2764  if (cur == n) {
2765    next = cur->osr_link();
2766    if (last == NULL) {
2767      // Remove first element
2768      set_osr_nmethods_head(next);
2769    } else {
2770      last->set_osr_link(next);
2771    }
2772  }
2773  n->set_osr_link(NULL);
2774  if (TieredCompilation) {
2775    cur = next;
2776    while (cur != NULL) {
2777      // Find max level after n
2778      if (m == cur->method()) {
2779        max_level = MAX2(max_level, cur->comp_level());
2780      }
2781      cur = cur->osr_link();
2782    }
2783    m->set_highest_osr_comp_level(max_level);
2784  }
2785  // Remember to unlock again
2786  OsrList_lock->unlock();
2787}
2788
2789nmethod* InstanceKlass::lookup_osr_nmethod(const Method* m, int bci, int comp_level, bool match_level) const {
2790  // This is a short non-blocking critical region, so the no safepoint check is ok.
2791  OsrList_lock->lock_without_safepoint_check();
2792  nmethod* osr = osr_nmethods_head();
2793  nmethod* best = NULL;
2794  while (osr != NULL) {
2795    assert(osr->is_osr_method(), "wrong kind of nmethod found in chain");
2796    // There can be a time when a c1 osr method exists but we are waiting
2797    // for a c2 version. When c2 completes its osr nmethod we will trash
2798    // the c1 version and only be able to find the c2 version. However
2799    // while we overflow in the c1 code at back branches we don't want to
2800    // try and switch to the same code as we are already running
2801
2802    if (osr->method() == m &&
2803        (bci == InvocationEntryBci || osr->osr_entry_bci() == bci)) {
2804      if (match_level) {
2805        if (osr->comp_level() == comp_level) {
2806          // Found a match - return it.
2807          OsrList_lock->unlock();
2808          return osr;
2809        }
2810      } else {
2811        if (best == NULL || (osr->comp_level() > best->comp_level())) {
2812          if (osr->comp_level() == CompLevel_highest_tier) {
2813            // Found the best possible - return it.
2814            OsrList_lock->unlock();
2815            return osr;
2816          }
2817          best = osr;
2818        }
2819      }
2820    }
2821    osr = osr->osr_link();
2822  }
2823  OsrList_lock->unlock();
2824  if (best != NULL && best->comp_level() >= comp_level && match_level == false) {
2825    return best;
2826  }
2827  return NULL;
2828}
2829
2830void InstanceKlass::add_member_name(int index, Handle mem_name) {
2831  jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
2832  MutexLocker ml(MemberNameTable_lock);
2833  assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
2834  DEBUG_ONLY(No_Safepoint_Verifier nsv);
2835
2836  if (_member_names == NULL) {
2837    _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable(idnum_allocated_count());
2838  }
2839  _member_names->add_member_name(index, mem_name_wref);
2840}
2841
2842oop InstanceKlass::get_member_name(int index) {
2843  MutexLocker ml(MemberNameTable_lock);
2844  assert(0 <= index && index < idnum_allocated_count(), "index is out of bounds");
2845  DEBUG_ONLY(No_Safepoint_Verifier nsv);
2846
2847  if (_member_names == NULL) {
2848    return NULL;
2849  }
2850  oop mem_name =_member_names->get_member_name(index);
2851  return mem_name;
2852}
2853
2854// -----------------------------------------------------------------------------------------------------
2855// Printing
2856
2857#ifndef PRODUCT
2858
2859#define BULLET  " - "
2860
2861static const char* state_names[] = {
2862  "allocated", "loaded", "linked", "being_initialized", "fully_initialized", "initialization_error"
2863};
2864
2865static void print_vtable(intptr_t* start, int len, outputStream* st) {
2866  for (int i = 0; i < len; i++) {
2867    intptr_t e = start[i];
2868    st->print("%d : " INTPTR_FORMAT, i, e);
2869    if (e != 0 && ((Metadata*)e)->is_metaspace_object()) {
2870      st->print(" ");
2871      ((Metadata*)e)->print_value_on(st);
2872    }
2873    st->cr();
2874  }
2875}
2876
2877void InstanceKlass::print_on(outputStream* st) const {
2878  assert(is_klass(), "must be klass");
2879  Klass::print_on(st);
2880
2881  st->print(BULLET"instance size:     %d", size_helper());                        st->cr();
2882  st->print(BULLET"klass size:        %d", size());                               st->cr();
2883  st->print(BULLET"access:            "); access_flags().print_on(st);            st->cr();
2884  st->print(BULLET"state:             "); st->print_cr("%s", state_names[_init_state]);
2885  st->print(BULLET"name:              "); name()->print_value_on(st);             st->cr();
2886  st->print(BULLET"super:             "); super()->print_value_on_maybe_null(st); st->cr();
2887  st->print(BULLET"sub:               ");
2888  Klass* sub = subklass();
2889  int n;
2890  for (n = 0; sub != NULL; n++, sub = sub->next_sibling()) {
2891    if (n < MaxSubklassPrintSize) {
2892      sub->print_value_on(st);
2893      st->print("   ");
2894    }
2895  }
2896  if (n >= MaxSubklassPrintSize) st->print("(%d more klasses...)", n - MaxSubklassPrintSize);
2897  st->cr();
2898
2899  if (is_interface()) {
2900    st->print_cr(BULLET"nof implementors:  %d", nof_implementors());
2901    if (nof_implementors() == 1) {
2902      st->print_cr(BULLET"implementor:    ");
2903      st->print("   ");
2904      implementor()->print_value_on(st);
2905      st->cr();
2906    }
2907  }
2908
2909  st->print(BULLET"arrays:            "); array_klasses()->print_value_on_maybe_null(st); st->cr();
2910  st->print(BULLET"methods:           "); methods()->print_value_on(st);                  st->cr();
2911  if (Verbose || WizardMode) {
2912    Array<Method*>* method_array = methods();
2913    for (int i = 0; i < method_array->length(); i++) {
2914      st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
2915    }
2916  }
2917  st->print(BULLET"method ordering:   "); method_ordering()->print_value_on(st);      st->cr();
2918  st->print(BULLET"default_methods:   "); default_methods()->print_value_on(st);      st->cr();
2919  if (Verbose && default_methods() != NULL) {
2920    Array<Method*>* method_array = default_methods();
2921    for (int i = 0; i < method_array->length(); i++) {
2922      st->print("%d : ", i); method_array->at(i)->print_value(); st->cr();
2923    }
2924  }
2925  if (default_vtable_indices() != NULL) {
2926    st->print(BULLET"default vtable indices:   "); default_vtable_indices()->print_value_on(st);       st->cr();
2927  }
2928  st->print(BULLET"local interfaces:  "); local_interfaces()->print_value_on(st);      st->cr();
2929  st->print(BULLET"trans. interfaces: "); transitive_interfaces()->print_value_on(st); st->cr();
2930  st->print(BULLET"constants:         "); constants()->print_value_on(st);         st->cr();
2931  if (class_loader_data() != NULL) {
2932    st->print(BULLET"class loader data:  ");
2933    class_loader_data()->print_value_on(st);
2934    st->cr();
2935  }
2936  st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
2937  if (source_file_name() != NULL) {
2938    st->print(BULLET"source file:       ");
2939    source_file_name()->print_value_on(st);
2940    st->cr();
2941  }
2942  if (source_debug_extension() != NULL) {
2943    st->print(BULLET"source debug extension:       ");
2944    st->print("%s", source_debug_extension());
2945    st->cr();
2946  }
2947  st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
2948  st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
2949  st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
2950  st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
2951  {
2952    bool have_pv = false;
2953    PreviousVersionWalker pvw(Thread::current(), (InstanceKlass*)this);
2954    for (PreviousVersionNode * pv_node = pvw.next_previous_version();
2955         pv_node != NULL; pv_node = pvw.next_previous_version()) {
2956      if (!have_pv)
2957        st->print(BULLET"previous version:  ");
2958      have_pv = true;
2959      pv_node->prev_constant_pool()->print_value_on(st);
2960    }
2961    if (have_pv) st->cr();
2962  } // pvw is cleaned up
2963
2964  if (generic_signature() != NULL) {
2965    st->print(BULLET"generic signature: ");
2966    generic_signature()->print_value_on(st);
2967    st->cr();
2968  }
2969  st->print(BULLET"inner classes:     "); inner_classes()->print_value_on(st);     st->cr();
2970  st->print(BULLET"java mirror:       "); java_mirror()->print_value_on(st);       st->cr();
2971  st->print(BULLET"vtable length      %d  (start addr: " INTPTR_FORMAT ")", vtable_length(), start_of_vtable());  st->cr();
2972  if (vtable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_vtable(), vtable_length(), st);
2973  st->print(BULLET"itable length      %d (start addr: " INTPTR_FORMAT ")", itable_length(), start_of_itable()); st->cr();
2974  if (itable_length() > 0 && (Verbose || WizardMode))  print_vtable(start_of_itable(), itable_length(), st);
2975  st->print_cr(BULLET"---- static fields (%d words):", static_field_size());
2976  FieldPrinter print_static_field(st);
2977  ((InstanceKlass*)this)->do_local_static_fields(&print_static_field);
2978  st->print_cr(BULLET"---- non-static fields (%d words):", nonstatic_field_size());
2979  FieldPrinter print_nonstatic_field(st);
2980  ((InstanceKlass*)this)->do_nonstatic_fields(&print_nonstatic_field);
2981
2982  st->print(BULLET"non-static oop maps: ");
2983  OopMapBlock* map     = start_of_nonstatic_oop_maps();
2984  OopMapBlock* end_map = map + nonstatic_oop_map_count();
2985  while (map < end_map) {
2986    st->print("%d-%d ", map->offset(), map->offset() + heapOopSize*(map->count() - 1));
2987    map++;
2988  }
2989  st->cr();
2990}
2991
2992#endif //PRODUCT
2993
2994void InstanceKlass::print_value_on(outputStream* st) const {
2995  assert(is_klass(), "must be klass");
2996  if (Verbose || WizardMode)  access_flags().print_on(st);
2997  name()->print_value_on(st);
2998}
2999
3000#ifndef PRODUCT
3001
3002void FieldPrinter::do_field(fieldDescriptor* fd) {
3003  _st->print(BULLET);
3004   if (_obj == NULL) {
3005     fd->print_on(_st);
3006     _st->cr();
3007   } else {
3008     fd->print_on_for(_st, _obj);
3009     _st->cr();
3010   }
3011}
3012
3013
3014void InstanceKlass::oop_print_on(oop obj, outputStream* st) {
3015  Klass::oop_print_on(obj, st);
3016
3017  if (this == SystemDictionary::String_klass()) {
3018    typeArrayOop value  = java_lang_String::value(obj);
3019    juint        offset = java_lang_String::offset(obj);
3020    juint        length = java_lang_String::length(obj);
3021    if (value != NULL &&
3022        value->is_typeArray() &&
3023        offset          <= (juint) value->length() &&
3024        offset + length <= (juint) value->length()) {
3025      st->print(BULLET"string: ");
3026      java_lang_String::print(obj, st);
3027      st->cr();
3028      if (!WizardMode)  return;  // that is enough
3029    }
3030  }
3031
3032  st->print_cr(BULLET"---- fields (total size %d words):", oop_size(obj));
3033  FieldPrinter print_field(st, obj);
3034  do_nonstatic_fields(&print_field);
3035
3036  if (this == SystemDictionary::Class_klass()) {
3037    st->print(BULLET"signature: ");
3038    java_lang_Class::print_signature(obj, st);
3039    st->cr();
3040    Klass* mirrored_klass = java_lang_Class::as_Klass(obj);
3041    st->print(BULLET"fake entry for mirror: ");
3042    mirrored_klass->print_value_on_maybe_null(st);
3043    st->cr();
3044    Klass* array_klass = java_lang_Class::array_klass(obj);
3045    st->print(BULLET"fake entry for array: ");
3046    array_klass->print_value_on_maybe_null(st);
3047    st->cr();
3048    st->print_cr(BULLET"fake entry for oop_size: %d", java_lang_Class::oop_size(obj));
3049    st->print_cr(BULLET"fake entry for static_oop_field_count: %d", java_lang_Class::static_oop_field_count(obj));
3050    Klass* real_klass = java_lang_Class::as_Klass(obj);
3051    if (real_klass != NULL && real_klass->oop_is_instance()) {
3052      InstanceKlass::cast(real_klass)->do_local_static_fields(&print_field);
3053    }
3054  } else if (this == SystemDictionary::MethodType_klass()) {
3055    st->print(BULLET"signature: ");
3056    java_lang_invoke_MethodType::print_signature(obj, st);
3057    st->cr();
3058  }
3059}
3060
3061#endif //PRODUCT
3062
3063void InstanceKlass::oop_print_value_on(oop obj, outputStream* st) {
3064  st->print("a ");
3065  name()->print_value_on(st);
3066  obj->print_address_on(st);
3067  if (this == SystemDictionary::String_klass()
3068      && java_lang_String::value(obj) != NULL) {
3069    ResourceMark rm;
3070    int len = java_lang_String::length(obj);
3071    int plen = (len < 24 ? len : 12);
3072    char* str = java_lang_String::as_utf8_string(obj, 0, plen);
3073    st->print(" = \"%s\"", str);
3074    if (len > plen)
3075      st->print("...[%d]", len);
3076  } else if (this == SystemDictionary::Class_klass()) {
3077    Klass* k = java_lang_Class::as_Klass(obj);
3078    st->print(" = ");
3079    if (k != NULL) {
3080      k->print_value_on(st);
3081    } else {
3082      const char* tname = type2name(java_lang_Class::primitive_type(obj));
3083      st->print("%s", tname ? tname : "type?");
3084    }
3085  } else if (this == SystemDictionary::MethodType_klass()) {
3086    st->print(" = ");
3087    java_lang_invoke_MethodType::print_signature(obj, st);
3088  } else if (java_lang_boxing_object::is_instance(obj)) {
3089    st->print(" = ");
3090    java_lang_boxing_object::print(obj, st);
3091  } else if (this == SystemDictionary::LambdaForm_klass()) {
3092    oop vmentry = java_lang_invoke_LambdaForm::vmentry(obj);
3093    if (vmentry != NULL) {
3094      st->print(" => ");
3095      vmentry->print_value_on(st);
3096    }
3097  } else if (this == SystemDictionary::MemberName_klass()) {
3098    Metadata* vmtarget = java_lang_invoke_MemberName::vmtarget(obj);
3099    if (vmtarget != NULL) {
3100      st->print(" = ");
3101      vmtarget->print_value_on(st);
3102    } else {
3103      java_lang_invoke_MemberName::clazz(obj)->print_value_on(st);
3104      st->print(".");
3105      java_lang_invoke_MemberName::name(obj)->print_value_on(st);
3106    }
3107  }
3108}
3109
3110const char* InstanceKlass::internal_name() const {
3111  return external_name();
3112}
3113
3114#if INCLUDE_SERVICES
3115// Size Statistics
3116void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
3117  Klass::collect_statistics(sz);
3118
3119  sz->_inst_size  = HeapWordSize * size_helper();
3120  sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
3121  sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
3122  sz->_nonstatic_oopmap_bytes = HeapWordSize *
3123        ((is_interface() || is_anonymous()) ?
3124         align_object_offset(nonstatic_oop_map_size()) :
3125         nonstatic_oop_map_size());
3126
3127  int n = 0;
3128  n += (sz->_methods_array_bytes         = sz->count_array(methods()));
3129  n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
3130  n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
3131  n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
3132  n += (sz->_fields_bytes                = sz->count_array(fields()));
3133  n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
3134  sz->_ro_bytes += n;
3135
3136  const ConstantPool* cp = constants();
3137  if (cp) {
3138    cp->collect_statistics(sz);
3139  }
3140
3141  const Annotations* anno = annotations();
3142  if (anno) {
3143    anno->collect_statistics(sz);
3144  }
3145
3146  const Array<Method*>* methods_array = methods();
3147  if (methods()) {
3148    for (int i = 0; i < methods_array->length(); i++) {
3149      Method* method = methods_array->at(i);
3150      if (method) {
3151        sz->_method_count ++;
3152        method->collect_statistics(sz);
3153      }
3154    }
3155  }
3156}
3157#endif // INCLUDE_SERVICES
3158
3159// Verification
3160
3161class VerifyFieldClosure: public OopClosure {
3162 protected:
3163  template <class T> void do_oop_work(T* p) {
3164    oop obj = oopDesc::load_decode_heap_oop(p);
3165    if (!obj->is_oop_or_null()) {
3166      tty->print_cr("Failed: " PTR_FORMAT " -> " PTR_FORMAT, p, (address)obj);
3167      Universe::print();
3168      guarantee(false, "boom");
3169    }
3170  }
3171 public:
3172  virtual void do_oop(oop* p)       { VerifyFieldClosure::do_oop_work(p); }
3173  virtual void do_oop(narrowOop* p) { VerifyFieldClosure::do_oop_work(p); }
3174};
3175
3176void InstanceKlass::verify_on(outputStream* st) {
3177#ifndef PRODUCT
3178  // Avoid redundant verifies, this really should be in product.
3179  if (_verify_count == Universe::verify_count()) return;
3180  _verify_count = Universe::verify_count();
3181#endif
3182
3183  // Verify Klass
3184  Klass::verify_on(st);
3185
3186  // Verify that klass is present in ClassLoaderData
3187  guarantee(class_loader_data()->contains_klass(this),
3188            "this class isn't found in class loader data");
3189
3190  // Verify vtables
3191  if (is_linked()) {
3192    ResourceMark rm;
3193    // $$$ This used to be done only for m/s collections.  Doing it
3194    // always seemed a valid generalization.  (DLD -- 6/00)
3195    vtable()->verify(st);
3196  }
3197
3198  // Verify first subklass
3199  if (subklass() != NULL) {
3200    guarantee(subklass()->is_klass(), "should be klass");
3201  }
3202
3203  // Verify siblings
3204  Klass* super = this->super();
3205  Klass* sib = next_sibling();
3206  if (sib != NULL) {
3207    if (sib == this) {
3208      fatal(err_msg("subclass points to itself " PTR_FORMAT, sib));
3209    }
3210
3211    guarantee(sib->is_klass(), "should be klass");
3212    guarantee(sib->super() == super, "siblings should have same superklass");
3213  }
3214
3215  // Verify implementor fields
3216  Klass* im = implementor();
3217  if (im != NULL) {
3218    guarantee(is_interface(), "only interfaces should have implementor set");
3219    guarantee(im->is_klass(), "should be klass");
3220    guarantee(!im->is_interface() || im == this,
3221      "implementors cannot be interfaces");
3222  }
3223
3224  // Verify local interfaces
3225  if (local_interfaces()) {
3226    Array<Klass*>* local_interfaces = this->local_interfaces();
3227    for (int j = 0; j < local_interfaces->length(); j++) {
3228      Klass* e = local_interfaces->at(j);
3229      guarantee(e->is_klass() && e->is_interface(), "invalid local interface");
3230    }
3231  }
3232
3233  // Verify transitive interfaces
3234  if (transitive_interfaces() != NULL) {
3235    Array<Klass*>* transitive_interfaces = this->transitive_interfaces();
3236    for (int j = 0; j < transitive_interfaces->length(); j++) {
3237      Klass* e = transitive_interfaces->at(j);
3238      guarantee(e->is_klass() && e->is_interface(), "invalid transitive interface");
3239    }
3240  }
3241
3242  // Verify methods
3243  if (methods() != NULL) {
3244    Array<Method*>* methods = this->methods();
3245    for (int j = 0; j < methods->length(); j++) {
3246      guarantee(methods->at(j)->is_method(), "non-method in methods array");
3247    }
3248    for (int j = 0; j < methods->length() - 1; j++) {
3249      Method* m1 = methods->at(j);
3250      Method* m2 = methods->at(j + 1);
3251      guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3252    }
3253  }
3254
3255  // Verify method ordering
3256  if (method_ordering() != NULL) {
3257    Array<int>* method_ordering = this->method_ordering();
3258    int length = method_ordering->length();
3259    if (JvmtiExport::can_maintain_original_method_order() ||
3260        ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
3261      guarantee(length == methods()->length(), "invalid method ordering length");
3262      jlong sum = 0;
3263      for (int j = 0; j < length; j++) {
3264        int original_index = method_ordering->at(j);
3265        guarantee(original_index >= 0, "invalid method ordering index");
3266        guarantee(original_index < length, "invalid method ordering index");
3267        sum += original_index;
3268      }
3269      // Verify sum of indices 0,1,...,length-1
3270      guarantee(sum == ((jlong)length*(length-1))/2, "invalid method ordering sum");
3271    } else {
3272      guarantee(length == 0, "invalid method ordering length");
3273    }
3274  }
3275
3276  // Verify default methods
3277  if (default_methods() != NULL) {
3278    Array<Method*>* methods = this->default_methods();
3279    for (int j = 0; j < methods->length(); j++) {
3280      guarantee(methods->at(j)->is_method(), "non-method in methods array");
3281    }
3282    for (int j = 0; j < methods->length() - 1; j++) {
3283      Method* m1 = methods->at(j);
3284      Method* m2 = methods->at(j + 1);
3285      guarantee(m1->name()->fast_compare(m2->name()) <= 0, "methods not sorted correctly");
3286    }
3287  }
3288
3289  // Verify JNI static field identifiers
3290  if (jni_ids() != NULL) {
3291    jni_ids()->verify(this);
3292  }
3293
3294  // Verify other fields
3295  if (array_klasses() != NULL) {
3296    guarantee(array_klasses()->is_klass(), "should be klass");
3297  }
3298  if (constants() != NULL) {
3299    guarantee(constants()->is_constantPool(), "should be constant pool");
3300  }
3301  const Klass* host = host_klass();
3302  if (host != NULL) {
3303    guarantee(host->is_klass(), "should be klass");
3304  }
3305}
3306
3307void InstanceKlass::oop_verify_on(oop obj, outputStream* st) {
3308  Klass::oop_verify_on(obj, st);
3309  VerifyFieldClosure blk;
3310  obj->oop_iterate_no_header(&blk);
3311}
3312
3313
3314// JNIid class for jfieldIDs only
3315// Note to reviewers:
3316// These JNI functions are just moved over to column 1 and not changed
3317// in the compressed oops workspace.
3318JNIid::JNIid(Klass* holder, int offset, JNIid* next) {
3319  _holder = holder;
3320  _offset = offset;
3321  _next = next;
3322  debug_only(_is_static_field_id = false;)
3323}
3324
3325
3326JNIid* JNIid::find(int offset) {
3327  JNIid* current = this;
3328  while (current != NULL) {
3329    if (current->offset() == offset) return current;
3330    current = current->next();
3331  }
3332  return NULL;
3333}
3334
3335void JNIid::deallocate(JNIid* current) {
3336  while (current != NULL) {
3337    JNIid* next = current->next();
3338    delete current;
3339    current = next;
3340  }
3341}
3342
3343
3344void JNIid::verify(Klass* holder) {
3345  int first_field_offset  = InstanceMirrorKlass::offset_of_static_fields();
3346  int end_field_offset;
3347  end_field_offset = first_field_offset + (InstanceKlass::cast(holder)->static_field_size() * wordSize);
3348
3349  JNIid* current = this;
3350  while (current != NULL) {
3351    guarantee(current->holder() == holder, "Invalid klass in JNIid");
3352#ifdef ASSERT
3353    int o = current->offset();
3354    if (current->is_static_field_id()) {
3355      guarantee(o >= first_field_offset  && o < end_field_offset,  "Invalid static field offset in JNIid");
3356    }
3357#endif
3358    current = current->next();
3359  }
3360}
3361
3362
3363#ifdef ASSERT
3364void InstanceKlass::set_init_state(ClassState state) {
3365  bool good_state = is_shared() ? (_init_state <= state)
3366                                               : (_init_state < state);
3367  assert(good_state || state == allocated, "illegal state transition");
3368  _init_state = (u1)state;
3369}
3370#endif
3371
3372
3373// RedefineClasses() support for previous versions:
3374
3375// Purge previous versions
3376static void purge_previous_versions_internal(InstanceKlass* ik, int emcp_method_count) {
3377  if (ik->previous_versions() != NULL) {
3378    // This klass has previous versions so see what we can cleanup
3379    // while it is safe to do so.
3380
3381    int deleted_count = 0;    // leave debugging breadcrumbs
3382    int live_count = 0;
3383    ClassLoaderData* loader_data = ik->class_loader_data() == NULL ?
3384                       ClassLoaderData::the_null_class_loader_data() :
3385                       ik->class_loader_data();
3386
3387    // RC_TRACE macro has an embedded ResourceMark
3388    RC_TRACE(0x00000200, ("purge: %s: previous version length=%d",
3389      ik->external_name(), ik->previous_versions()->length()));
3390
3391    for (int i = ik->previous_versions()->length() - 1; i >= 0; i--) {
3392      // check the previous versions array
3393      PreviousVersionNode * pv_node = ik->previous_versions()->at(i);
3394      ConstantPool* cp_ref = pv_node->prev_constant_pool();
3395      assert(cp_ref != NULL, "cp ref was unexpectedly cleared");
3396
3397      ConstantPool* pvcp = cp_ref;
3398      if (!pvcp->on_stack()) {
3399        // If the constant pool isn't on stack, none of the methods
3400        // are executing.  Delete all the methods, the constant pool and
3401        // and this previous version node.
3402        GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3403        if (method_refs != NULL) {
3404          for (int j = method_refs->length() - 1; j >= 0; j--) {
3405            Method* method = method_refs->at(j);
3406            assert(method != NULL, "method ref was unexpectedly cleared");
3407            method_refs->remove_at(j);
3408            // method will be freed with associated class.
3409          }
3410        }
3411        // Remove the constant pool
3412        delete pv_node;
3413        // Since we are traversing the array backwards, we don't have to
3414        // do anything special with the index.
3415        ik->previous_versions()->remove_at(i);
3416        deleted_count++;
3417        continue;
3418      } else {
3419        RC_TRACE(0x00000200, ("purge: previous version @%d is alive", i));
3420        assert(pvcp->pool_holder() != NULL, "Constant pool with no holder");
3421        guarantee (!loader_data->is_unloading(), "unloaded classes can't be on the stack");
3422        live_count++;
3423      }
3424
3425      // At least one method is live in this previous version, clean out
3426      // the others or mark them as obsolete.
3427      GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3428      if (method_refs != NULL) {
3429        RC_TRACE(0x00000200, ("purge: previous methods length=%d",
3430          method_refs->length()));
3431        for (int j = method_refs->length() - 1; j >= 0; j--) {
3432          Method* method = method_refs->at(j);
3433          assert(method != NULL, "method ref was unexpectedly cleared");
3434
3435          // Remove the emcp method if it's not executing
3436          // If it's been made obsolete by a redefinition of a non-emcp
3437          // method, mark it as obsolete but leave it to clean up later.
3438          if (!method->on_stack()) {
3439            method_refs->remove_at(j);
3440          } else if (emcp_method_count == 0) {
3441            method->set_is_obsolete();
3442          } else {
3443            // RC_TRACE macro has an embedded ResourceMark
3444            RC_TRACE(0x00000200,
3445              ("purge: %s(%s): prev method @%d in version @%d is alive",
3446              method->name()->as_C_string(),
3447              method->signature()->as_C_string(), j, i));
3448            if (method->method_data() != NULL) {
3449              // Clean out any weak method links
3450              method->method_data()->clean_weak_method_links();
3451            }
3452          }
3453        }
3454      }
3455    }
3456    assert(ik->previous_versions()->length() == live_count, "sanity check");
3457    RC_TRACE(0x00000200,
3458      ("purge: previous version stats: live=%d, deleted=%d", live_count,
3459      deleted_count));
3460  }
3461
3462  Array<Method*>* methods = ik->methods();
3463  int num_methods = methods->length();
3464  for (int index2 = 0; index2 < num_methods; ++index2) {
3465    if (methods->at(index2)->method_data() != NULL) {
3466      methods->at(index2)->method_data()->clean_weak_method_links();
3467    }
3468  }
3469}
3470
3471// External interface for use during class unloading.
3472void InstanceKlass::purge_previous_versions(InstanceKlass* ik) {
3473  // Call with >0 emcp methods since they are not currently being redefined.
3474  purge_previous_versions_internal(ik, 1);
3475}
3476
3477
3478// Potentially add an information node that contains pointers to the
3479// interesting parts of the previous version of the_class.
3480// This is also where we clean out any unused references.
3481// Note that while we delete nodes from the _previous_versions
3482// array, we never delete the array itself until the klass is
3483// unloaded. The has_been_redefined() query depends on that fact.
3484//
3485void InstanceKlass::add_previous_version(instanceKlassHandle ikh,
3486       BitMap* emcp_methods, int emcp_method_count) {
3487  assert(Thread::current()->is_VM_thread(),
3488         "only VMThread can add previous versions");
3489
3490  if (_previous_versions == NULL) {
3491    // This is the first previous version so make some space.
3492    // Start with 2 elements under the assumption that the class
3493    // won't be redefined much.
3494    _previous_versions =  new (ResourceObj::C_HEAP, mtClass)
3495                            GrowableArray<PreviousVersionNode *>(2, true);
3496  }
3497
3498  ConstantPool* cp_ref = ikh->constants();
3499
3500  // RC_TRACE macro has an embedded ResourceMark
3501  RC_TRACE(0x00000400, ("adding previous version ref for %s @%d, EMCP_cnt=%d "
3502                        "on_stack=%d",
3503    ikh->external_name(), _previous_versions->length(), emcp_method_count,
3504    cp_ref->on_stack()));
3505
3506  // If the constant pool for this previous version of the class
3507  // is not marked as being on the stack, then none of the methods
3508  // in this previous version of the class are on the stack so
3509  // we don't need to create a new PreviousVersionNode. However,
3510  // we still need to examine older previous versions below.
3511  Array<Method*>* old_methods = ikh->methods();
3512
3513  if (cp_ref->on_stack()) {
3514    PreviousVersionNode * pv_node = NULL;
3515    if (emcp_method_count == 0) {
3516      // non-shared ConstantPool gets a reference
3517      pv_node = new PreviousVersionNode(cp_ref, NULL);
3518      RC_TRACE(0x00000400,
3519          ("add: all methods are obsolete; flushing any EMCP refs"));
3520    } else {
3521      int local_count = 0;
3522      GrowableArray<Method*>* method_refs = new (ResourceObj::C_HEAP, mtClass)
3523          GrowableArray<Method*>(emcp_method_count, true);
3524      for (int i = 0; i < old_methods->length(); i++) {
3525        if (emcp_methods->at(i)) {
3526            // this old method is EMCP. Save it only if it's on the stack
3527            Method* old_method = old_methods->at(i);
3528            if (old_method->on_stack()) {
3529              method_refs->append(old_method);
3530            }
3531          if (++local_count >= emcp_method_count) {
3532            // no more EMCP methods so bail out now
3533            break;
3534          }
3535        }
3536      }
3537      // non-shared ConstantPool gets a reference
3538      pv_node = new PreviousVersionNode(cp_ref, method_refs);
3539    }
3540    // append new previous version.
3541    _previous_versions->append(pv_node);
3542  }
3543
3544  // Since the caller is the VMThread and we are at a safepoint, this
3545  // is a good time to clear out unused references.
3546
3547  RC_TRACE(0x00000400, ("add: previous version length=%d",
3548    _previous_versions->length()));
3549
3550  // Purge previous versions not executing on the stack
3551  purge_previous_versions_internal(this, emcp_method_count);
3552
3553  int obsolete_method_count = old_methods->length() - emcp_method_count;
3554
3555  if (emcp_method_count != 0 && obsolete_method_count != 0 &&
3556      _previous_versions->length() > 0) {
3557    // We have a mix of obsolete and EMCP methods so we have to
3558    // clear out any matching EMCP method entries the hard way.
3559    int local_count = 0;
3560    for (int i = 0; i < old_methods->length(); i++) {
3561      if (!emcp_methods->at(i)) {
3562        // only obsolete methods are interesting
3563        Method* old_method = old_methods->at(i);
3564        Symbol* m_name = old_method->name();
3565        Symbol* m_signature = old_method->signature();
3566
3567        // we might not have added the last entry
3568        for (int j = _previous_versions->length() - 1; j >= 0; j--) {
3569          // check the previous versions array for non executing obsolete methods
3570          PreviousVersionNode * pv_node = _previous_versions->at(j);
3571
3572          GrowableArray<Method*>* method_refs = pv_node->prev_EMCP_methods();
3573          if (method_refs == NULL) {
3574            // We have run into a PreviousVersion generation where
3575            // all methods were made obsolete during that generation's
3576            // RedefineClasses() operation. At the time of that
3577            // operation, all EMCP methods were flushed so we don't
3578            // have to go back any further.
3579            //
3580            // A NULL method_refs is different than an empty method_refs.
3581            // We cannot infer any optimizations about older generations
3582            // from an empty method_refs for the current generation.
3583            break;
3584          }
3585
3586          for (int k = method_refs->length() - 1; k >= 0; k--) {
3587            Method* method = method_refs->at(k);
3588
3589            if (!method->is_obsolete() &&
3590                method->name() == m_name &&
3591                method->signature() == m_signature) {
3592              // The current RedefineClasses() call has made all EMCP
3593              // versions of this method obsolete so mark it as obsolete
3594              // and remove the reference.
3595              RC_TRACE(0x00000400,
3596                ("add: %s(%s): flush obsolete method @%d in version @%d",
3597                m_name->as_C_string(), m_signature->as_C_string(), k, j));
3598
3599              method->set_is_obsolete();
3600              // Leave obsolete methods on the previous version list to
3601              // clean up later.
3602              break;
3603            }
3604          }
3605
3606          // The previous loop may not find a matching EMCP method, but
3607          // that doesn't mean that we can optimize and not go any
3608          // further back in the PreviousVersion generations. The EMCP
3609          // method for this generation could have already been deleted,
3610          // but there still may be an older EMCP method that has not
3611          // been deleted.
3612        }
3613
3614        if (++local_count >= obsolete_method_count) {
3615          // no more obsolete methods so bail out now
3616          break;
3617        }
3618      }
3619    }
3620  }
3621} // end add_previous_version()
3622
3623
3624// Determine if InstanceKlass has a previous version.
3625bool InstanceKlass::has_previous_version() const {
3626  return (_previous_versions != NULL && _previous_versions->length() > 0);
3627} // end has_previous_version()
3628
3629
3630Method* InstanceKlass::method_with_idnum(int idnum) {
3631  Method* m = NULL;
3632  if (idnum < methods()->length()) {
3633    m = methods()->at(idnum);
3634  }
3635  if (m == NULL || m->method_idnum() != idnum) {
3636    for (int index = 0; index < methods()->length(); ++index) {
3637      m = methods()->at(index);
3638      if (m->method_idnum() == idnum) {
3639        return m;
3640      }
3641    }
3642    // None found, return null for the caller to handle.
3643    return NULL;
3644  }
3645  return m;
3646}
3647
3648jint InstanceKlass::get_cached_class_file_len() {
3649  return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file);
3650}
3651
3652unsigned char * InstanceKlass::get_cached_class_file_bytes() {
3653  return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file);
3654}
3655
3656
3657// Construct a PreviousVersionNode entry for the array hung off
3658// the InstanceKlass.
3659PreviousVersionNode::PreviousVersionNode(ConstantPool* prev_constant_pool,
3660  GrowableArray<Method*>* prev_EMCP_methods) {
3661
3662  _prev_constant_pool = prev_constant_pool;
3663  _prev_EMCP_methods = prev_EMCP_methods;
3664}
3665
3666
3667// Destroy a PreviousVersionNode
3668PreviousVersionNode::~PreviousVersionNode() {
3669  if (_prev_constant_pool != NULL) {
3670    _prev_constant_pool = NULL;
3671  }
3672
3673  if (_prev_EMCP_methods != NULL) {
3674    delete _prev_EMCP_methods;
3675  }
3676}
3677
3678// Construct a helper for walking the previous versions array
3679PreviousVersionWalker::PreviousVersionWalker(Thread* thread, InstanceKlass *ik) {
3680  _thread = thread;
3681  _previous_versions = ik->previous_versions();
3682  _current_index = 0;
3683  _current_p = NULL;
3684  _current_constant_pool_handle = constantPoolHandle(thread, ik->constants());
3685}
3686
3687
3688// Return the interesting information for the next previous version
3689// of the klass. Returns NULL if there are no more previous versions.
3690PreviousVersionNode* PreviousVersionWalker::next_previous_version() {
3691  if (_previous_versions == NULL) {
3692    // no previous versions so nothing to return
3693    return NULL;
3694  }
3695
3696  _current_p = NULL;  // reset to NULL
3697  _current_constant_pool_handle = NULL;
3698
3699  int length = _previous_versions->length();
3700
3701  while (_current_index < length) {
3702    PreviousVersionNode * pv_node = _previous_versions->at(_current_index++);
3703
3704    // Save a handle to the constant pool for this previous version,
3705    // which keeps all the methods from being deallocated.
3706    _current_constant_pool_handle = constantPoolHandle(_thread, pv_node->prev_constant_pool());
3707    _current_p = pv_node;
3708    return pv_node;
3709  }
3710
3711  return NULL;
3712} // end next_previous_version()
3713