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