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