Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/classfile/defaultMethods.cpp
32285 views
/*1* Copyright (c) 2012, 2018, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "classfile/bytecodeAssembler.hpp"26#include "classfile/defaultMethods.hpp"27#include "classfile/symbolTable.hpp"28#include "memory/allocation.hpp"29#include "memory/metadataFactory.hpp"30#include "memory/resourceArea.hpp"31#include "runtime/signature.hpp"32#include "runtime/thread.hpp"33#include "oops/instanceKlass.hpp"34#include "oops/klass.hpp"35#include "oops/method.hpp"36#include "utilities/accessFlags.hpp"37#include "utilities/exceptions.hpp"38#include "utilities/ostream.hpp"39#include "utilities/pair.hpp"40#include "utilities/resourceHash.hpp"4142typedef enum { QUALIFIED, DISQUALIFIED } QualifiedState;4344// Because we use an iterative algorithm when iterating over the type45// hierarchy, we can't use traditional scoped objects which automatically do46// cleanup in the destructor when the scope is exited. PseudoScope (and47// PseudoScopeMark) provides a similar functionality, but for when you want a48// scoped object in non-stack memory (such as in resource memory, as we do49// here). You've just got to remember to call 'destroy()' on the scope when50// leaving it (and marks have to be explicitly added).51class PseudoScopeMark : public ResourceObj {52public:53virtual void destroy() = 0;54};5556class PseudoScope : public ResourceObj {57private:58GrowableArray<PseudoScopeMark*> _marks;59public:6061static PseudoScope* cast(void* data) {62return static_cast<PseudoScope*>(data);63}6465void add_mark(PseudoScopeMark* psm) {66_marks.append(psm);67}6869void destroy() {70for (int i = 0; i < _marks.length(); ++i) {71_marks.at(i)->destroy();72}73}74};7576#ifndef PRODUCT77static void print_slot(outputStream* str, Symbol* name, Symbol* signature) {78ResourceMark rm;79str->print("%s%s", name->as_C_string(), signature->as_C_string());80}8182static void print_method(outputStream* str, Method* mo, bool with_class=true) {83ResourceMark rm;84if (with_class) {85str->print("%s.", mo->klass_name()->as_C_string());86}87print_slot(str, mo->name(), mo->signature());88}89#endif // ndef PRODUCT9091/**92* Perform a depth-first iteration over the class hierarchy, applying93* algorithmic logic as it goes.94*95* This class is one half of the inheritance hierarchy analysis mechanism.96* It is meant to be used in conjunction with another class, the algorithm,97* which is indicated by the ALGO template parameter. This class can be98* paired with any algorithm class that provides the required methods.99*100* This class contains all the mechanics for iterating over the class hierarchy101* starting at a particular root, without recursing (thus limiting stack growth102* from this point). It visits each superclass (if present) and superinterface103* in a depth-first manner, with callbacks to the ALGO class as each class is104* encountered (visit()), The algorithm can cut-off further exploration of a105* particular branch by returning 'false' from a visit() call.106*107* The ALGO class, must provide a visit() method, which each of which will be108* called once for each node in the inheritance tree during the iteration. In109* addition, it can provide a memory block via new_node_data(InstanceKlass*),110* which it can use for node-specific storage (and access via the111* current_data() and data_at_depth(int) methods).112*113* Bare minimum needed to be an ALGO class:114* class Algo : public HierarchyVisitor<Algo> {115* void* new_node_data(InstanceKlass* cls) { return NULL; }116* void free_node_data(void* data) { return; }117* bool visit() { return true; }118* };119*/120template <class ALGO>121class HierarchyVisitor : StackObj {122private:123124class Node : public ResourceObj {125public:126InstanceKlass* _class;127bool _super_was_visited;128int _interface_index;129void* _algorithm_data;130131Node(InstanceKlass* cls, void* data, bool visit_super)132: _class(cls), _super_was_visited(!visit_super),133_interface_index(0), _algorithm_data(data) {}134135int number_of_interfaces() { return _class->local_interfaces()->length(); }136int interface_index() { return _interface_index; }137void set_super_visited() { _super_was_visited = true; }138void increment_visited_interface() { ++_interface_index; }139void set_all_interfaces_visited() {140_interface_index = number_of_interfaces();141}142bool has_visited_super() { return _super_was_visited; }143bool has_visited_all_interfaces() {144return interface_index() >= number_of_interfaces();145}146InstanceKlass* interface_at(int index) {147return InstanceKlass::cast(_class->local_interfaces()->at(index));148}149InstanceKlass* next_super() { return _class->java_super(); }150InstanceKlass* next_interface() {151return interface_at(interface_index());152}153};154155bool _cancelled;156GrowableArray<Node*> _path;157158Node* current_top() const { return _path.top(); }159bool has_more_nodes() const { return !_path.is_empty(); }160void push(InstanceKlass* cls, void* data) {161assert(cls != NULL, "Requires a valid instance class");162Node* node = new Node(cls, data, has_super(cls));163_path.push(node);164}165void pop() { _path.pop(); }166167void reset_iteration() {168_cancelled = false;169_path.clear();170}171bool is_cancelled() const { return _cancelled; }172173// This code used to skip interface classes because their only174// superclass was j.l.Object which would be also covered by class175// superclass hierarchy walks. Now that the starting point can be176// an interface, we must ensure we catch j.l.Object as the super.177static bool has_super(InstanceKlass* cls) {178return cls->super() != NULL;179}180181Node* node_at_depth(int i) const {182return (i >= _path.length()) ? NULL : _path.at(_path.length() - i - 1);183}184185protected:186187// Accessors available to the algorithm188int current_depth() const { return _path.length() - 1; }189190InstanceKlass* class_at_depth(int i) {191Node* n = node_at_depth(i);192return n == NULL ? NULL : n->_class;193}194InstanceKlass* current_class() { return class_at_depth(0); }195196void* data_at_depth(int i) {197Node* n = node_at_depth(i);198return n == NULL ? NULL : n->_algorithm_data;199}200void* current_data() { return data_at_depth(0); }201202void cancel_iteration() { _cancelled = true; }203204public:205206void run(InstanceKlass* root) {207ALGO* algo = static_cast<ALGO*>(this);208209reset_iteration();210211void* algo_data = algo->new_node_data(root);212push(root, algo_data);213bool top_needs_visit = true;214215do {216Node* top = current_top();217if (top_needs_visit) {218if (algo->visit() == false) {219// algorithm does not want to continue along this path. Arrange220// it so that this state is immediately popped off the stack221top->set_super_visited();222top->set_all_interfaces_visited();223}224top_needs_visit = false;225}226227if (top->has_visited_super() && top->has_visited_all_interfaces()) {228algo->free_node_data(top->_algorithm_data);229pop();230} else {231InstanceKlass* next = NULL;232if (top->has_visited_super() == false) {233next = top->next_super();234top->set_super_visited();235} else {236next = top->next_interface();237top->increment_visited_interface();238}239assert(next != NULL, "Otherwise we shouldn't be here");240algo_data = algo->new_node_data(next);241push(next, algo_data);242top_needs_visit = true;243}244} while (!is_cancelled() && has_more_nodes());245}246};247248#ifndef PRODUCT249class PrintHierarchy : public HierarchyVisitor<PrintHierarchy> {250public:251252bool visit() {253InstanceKlass* cls = current_class();254streamIndentor si(tty, current_depth() * 2);255tty->indent().print_cr("%s", cls->name()->as_C_string());256return true;257}258259void* new_node_data(InstanceKlass* cls) { return NULL; }260void free_node_data(void* data) { return; }261};262#endif // ndef PRODUCT263264// Used to register InstanceKlass objects and all related metadata structures265// (Methods, ConstantPools) as "in-use" by the current thread so that they can't266// be deallocated by class redefinition while we're using them. The classes are267// de-registered when this goes out of scope.268//269// Once a class is registered, we need not bother with methodHandles or270// constantPoolHandles for it's associated metadata.271class KeepAliveRegistrar : public StackObj {272private:273Thread* _thread;274GrowableArray<ConstantPool*> _keep_alive;275276public:277KeepAliveRegistrar(Thread* thread) : _thread(thread), _keep_alive(20) {278assert(thread == Thread::current(), "Must be current thread");279}280281~KeepAliveRegistrar() {282for (int i = _keep_alive.length() - 1; i >= 0; --i) {283ConstantPool* cp = _keep_alive.at(i);284int idx = _thread->metadata_handles()->find_from_end(cp);285assert(idx > 0, "Must be in the list");286_thread->metadata_handles()->remove_at(idx);287}288}289290// Register a class as 'in-use' by the thread. It's fine to register a class291// multiple times (though perhaps inefficient)292void register_class(InstanceKlass* ik) {293ConstantPool* cp = ik->constants();294_keep_alive.push(cp);295_thread->metadata_handles()->push(cp);296}297};298299class KeepAliveVisitor : public HierarchyVisitor<KeepAliveVisitor> {300private:301KeepAliveRegistrar* _registrar;302303public:304KeepAliveVisitor(KeepAliveRegistrar* registrar) : _registrar(registrar) {}305306void* new_node_data(InstanceKlass* cls) { return NULL; }307void free_node_data(void* data) { return; }308309bool visit() {310_registrar->register_class(current_class());311return true;312}313};314315316// A method family contains a set of all methods that implement a single317// erased method. As members of the set are collected while walking over the318// hierarchy, they are tagged with a qualification state. The qualification319// state for an erased method is set to disqualified if there exists a path320// from the root of hierarchy to the method that contains an interleaving321// erased method defined in an interface.322323class MethodFamily : public ResourceObj {324private:325326GrowableArray<Pair<Method*,QualifiedState> > _members;327ResourceHashtable<Method*, int> _member_index;328329Method* _selected_target; // Filled in later, if a unique target exists330Symbol* _exception_message; // If no unique target is found331Symbol* _exception_name; // If no unique target is found332333bool contains_method(Method* method) {334int* lookup = _member_index.get(method);335return lookup != NULL;336}337338void add_method(Method* method, QualifiedState state) {339Pair<Method*,QualifiedState> entry(method, state);340_member_index.put(method, _members.length());341_members.append(entry);342}343344void disqualify_method(Method* method) {345int* index = _member_index.get(method);346guarantee(index != NULL && *index >= 0 && *index < _members.length(), "bad index");347_members.at(*index).second = DISQUALIFIED;348}349350Symbol* generate_no_defaults_message(TRAPS) const;351Symbol* generate_method_message(Symbol *klass_name, Method* method, TRAPS) const;352Symbol* generate_conflicts_message(GrowableArray<Method*>* methods, TRAPS) const;353354public:355356MethodFamily()357: _selected_target(NULL), _exception_message(NULL), _exception_name(NULL) {}358359void set_target_if_empty(Method* m) {360if (_selected_target == NULL && !m->is_overpass()) {361_selected_target = m;362}363}364365void record_qualified_method(Method* m) {366// If the method already exists in the set as qualified, this operation is367// redundant. If it already exists as disqualified, then we leave it as368// disqualfied. Thus we only add to the set if it's not already in the369// set.370if (!contains_method(m)) {371add_method(m, QUALIFIED);372}373}374375void record_disqualified_method(Method* m) {376// If not in the set, add it as disqualified. If it's already in the set,377// then set the state to disqualified no matter what the previous state was.378if (!contains_method(m)) {379add_method(m, DISQUALIFIED);380} else {381disqualify_method(m);382}383}384385bool has_target() const { return _selected_target != NULL; }386bool throws_exception() { return _exception_message != NULL; }387388Method* get_selected_target() { return _selected_target; }389Symbol* get_exception_message() { return _exception_message; }390Symbol* get_exception_name() { return _exception_name; }391392// Either sets the target or the exception error message393void determine_target(InstanceKlass* root, TRAPS) {394if (has_target() || throws_exception()) {395return;396}397398// Qualified methods are maximally-specific methods399// These include public, instance concrete (=default) and abstract methods400GrowableArray<Method*> qualified_methods;401int num_defaults = 0;402int default_index = -1;403int qualified_index = -1;404for (int i = 0; i < _members.length(); ++i) {405Pair<Method*,QualifiedState> entry = _members.at(i);406if (entry.second == QUALIFIED) {407qualified_methods.append(entry.first);408qualified_index++;409if (entry.first->is_default_method()) {410num_defaults++;411default_index = qualified_index;412413}414}415}416417if (num_defaults == 0) {418// If the root klass has a static method with matching name and signature419// then do not generate an overpass method because it will hide the420// static method during resolution.421if (qualified_methods.length() == 0) {422_exception_message = generate_no_defaults_message(CHECK);423} else {424assert(root != NULL, "Null root class");425_exception_message = generate_method_message(root->name(), qualified_methods.at(0), CHECK);426}427_exception_name = vmSymbols::java_lang_AbstractMethodError();428429// If only one qualified method is default, select that430} else if (num_defaults == 1) {431_selected_target = qualified_methods.at(default_index);432433} else if (num_defaults > 1) {434_exception_message = generate_conflicts_message(&qualified_methods,CHECK);435_exception_name = vmSymbols::java_lang_IncompatibleClassChangeError();436if (TraceDefaultMethods) {437_exception_message->print_value_on(tty);438tty->cr();439}440}441}442443bool contains_signature(Symbol* query) {444for (int i = 0; i < _members.length(); ++i) {445if (query == _members.at(i).first->signature()) {446return true;447}448}449return false;450}451452#ifndef PRODUCT453void print_sig_on(outputStream* str, Symbol* signature, int indent) const {454streamIndentor si(str, indent * 2);455456str->indent().print_cr("Logical Method %s:", signature->as_C_string());457458streamIndentor si2(str);459for (int i = 0; i < _members.length(); ++i) {460str->indent();461print_method(str, _members.at(i).first);462if (_members.at(i).second == DISQUALIFIED) {463str->print(" (disqualified)");464}465str->cr();466}467468if (_selected_target != NULL) {469print_selected(str, 1);470}471}472473void print_selected(outputStream* str, int indent) const {474assert(has_target(), "Should be called otherwise");475streamIndentor si(str, indent * 2);476str->indent().print("Selected method: ");477print_method(str, _selected_target);478Klass* method_holder = _selected_target->method_holder();479if (!method_holder->is_interface()) {480tty->print(" : in superclass");481}482str->cr();483}484485void print_exception(outputStream* str, int indent) {486assert(throws_exception(), "Should be called otherwise");487assert(_exception_name != NULL, "exception_name should be set");488streamIndentor si(str, indent * 2);489str->indent().print_cr("%s: %s", _exception_name->as_C_string(), _exception_message->as_C_string());490}491#endif // ndef PRODUCT492};493494Symbol* MethodFamily::generate_no_defaults_message(TRAPS) const {495return SymbolTable::new_symbol("No qualifying defaults found", THREAD);496}497498Symbol* MethodFamily::generate_method_message(Symbol *klass_name, Method* method, TRAPS) const {499stringStream ss;500ss.print("Method ");501Symbol* name = method->name();502Symbol* signature = method->signature();503ss.write((const char*)klass_name->bytes(), klass_name->utf8_length());504ss.print(".");505ss.write((const char*)name->bytes(), name->utf8_length());506ss.write((const char*)signature->bytes(), signature->utf8_length());507ss.print(" is abstract");508return SymbolTable::new_symbol(ss.base(), (int)ss.size(), THREAD);509}510511Symbol* MethodFamily::generate_conflicts_message(GrowableArray<Method*>* methods, TRAPS) const {512stringStream ss;513ss.print("Conflicting default methods:");514for (int i = 0; i < methods->length(); ++i) {515Method* method = methods->at(i);516Symbol* klass = method->klass_name();517Symbol* name = method->name();518ss.print(" ");519ss.write((const char*)klass->bytes(), klass->utf8_length());520ss.print(".");521ss.write((const char*)name->bytes(), name->utf8_length());522}523return SymbolTable::new_symbol(ss.base(), (int)ss.size(), THREAD);524}525526527class StateRestorer;528529// StatefulMethodFamily is a wrapper around a MethodFamily that maintains the530// qualification state during hierarchy visitation, and applies that state531// when adding members to the MethodFamily532class StatefulMethodFamily : public ResourceObj {533friend class StateRestorer;534private:535QualifiedState _qualification_state;536537void set_qualification_state(QualifiedState state) {538_qualification_state = state;539}540541protected:542MethodFamily* _method_family;543544public:545StatefulMethodFamily() {546_method_family = new MethodFamily();547_qualification_state = QUALIFIED;548}549550StatefulMethodFamily(MethodFamily* mf) {551_method_family = mf;552_qualification_state = QUALIFIED;553}554555void set_target_if_empty(Method* m) { _method_family->set_target_if_empty(m); }556557MethodFamily* get_method_family() { return _method_family; }558559StateRestorer* record_method_and_dq_further(Method* mo);560};561562class StateRestorer : public PseudoScopeMark {563private:564StatefulMethodFamily* _method;565QualifiedState _state_to_restore;566public:567StateRestorer(StatefulMethodFamily* dm, QualifiedState state)568: _method(dm), _state_to_restore(state) {}569~StateRestorer() { destroy(); }570void restore_state() { _method->set_qualification_state(_state_to_restore); }571virtual void destroy() { restore_state(); }572};573574StateRestorer* StatefulMethodFamily::record_method_and_dq_further(Method* mo) {575StateRestorer* mark = new StateRestorer(this, _qualification_state);576if (_qualification_state == QUALIFIED) {577_method_family->record_qualified_method(mo);578} else {579_method_family->record_disqualified_method(mo);580}581// Everything found "above"??? this method in the hierarchy walk is set to582// disqualified583set_qualification_state(DISQUALIFIED);584return mark;585}586587// Represents a location corresponding to a vtable slot for methods that588// neither the class nor any of it's ancestors provide an implementaion.589// Default methods may be present to fill this slot.590class EmptyVtableSlot : public ResourceObj {591private:592Symbol* _name;593Symbol* _signature;594int _size_of_parameters;595MethodFamily* _binding;596597public:598EmptyVtableSlot(Method* method)599: _name(method->name()), _signature(method->signature()),600_size_of_parameters(method->size_of_parameters()), _binding(NULL) {}601602Symbol* name() const { return _name; }603Symbol* signature() const { return _signature; }604int size_of_parameters() const { return _size_of_parameters; }605606void bind_family(MethodFamily* lm) { _binding = lm; }607bool is_bound() { return _binding != NULL; }608MethodFamily* get_binding() { return _binding; }609610#ifndef PRODUCT611void print_on(outputStream* str) const {612print_slot(str, name(), signature());613}614#endif // ndef PRODUCT615};616617static bool already_in_vtable_slots(GrowableArray<EmptyVtableSlot*>* slots, Method* m) {618bool found = false;619for (int j = 0; j < slots->length(); ++j) {620if (slots->at(j)->name() == m->name() &&621slots->at(j)->signature() == m->signature() ) {622found = true;623break;624}625}626return found;627}628629static GrowableArray<EmptyVtableSlot*>* find_empty_vtable_slots(630InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) {631632assert(klass != NULL, "Must be valid class");633634GrowableArray<EmptyVtableSlot*>* slots = new GrowableArray<EmptyVtableSlot*>();635636// All miranda methods are obvious candidates637for (int i = 0; i < mirandas->length(); ++i) {638Method* m = mirandas->at(i);639if (!already_in_vtable_slots(slots, m)) {640slots->append(new EmptyVtableSlot(m));641}642}643644// Also any overpasses in our superclasses, that we haven't implemented.645// (can't use the vtable because it is not guaranteed to be initialized yet)646InstanceKlass* super = klass->java_super();647while (super != NULL) {648for (int i = 0; i < super->methods()->length(); ++i) {649Method* m = super->methods()->at(i);650if (m->is_overpass() || m->is_static()) {651// m is a method that would have been a miranda if not for the652// default method processing that occurred on behalf of our superclass,653// so it's a method we want to re-examine in this new context. That is,654// unless we have a real implementation of it in the current class.655Method* impl = klass->lookup_method(m->name(), m->signature());656if (impl == NULL || impl->is_overpass() || impl->is_static()) {657if (!already_in_vtable_slots(slots, m)) {658slots->append(new EmptyVtableSlot(m));659}660}661}662}663664// also any default methods in our superclasses665if (super->default_methods() != NULL) {666for (int i = 0; i < super->default_methods()->length(); ++i) {667Method* m = super->default_methods()->at(i);668// m is a method that would have been a miranda if not for the669// default method processing that occurred on behalf of our superclass,670// so it's a method we want to re-examine in this new context. That is,671// unless we have a real implementation of it in the current class.672Method* impl = klass->lookup_method(m->name(), m->signature());673if (impl == NULL || impl->is_overpass() || impl->is_static()) {674if (!already_in_vtable_slots(slots, m)) {675slots->append(new EmptyVtableSlot(m));676}677}678}679}680super = super->java_super();681}682683#ifndef PRODUCT684if (TraceDefaultMethods) {685tty->print_cr("Slots that need filling:");686streamIndentor si(tty);687for (int i = 0; i < slots->length(); ++i) {688tty->indent();689slots->at(i)->print_on(tty);690tty->cr();691}692}693#endif // ndef PRODUCT694return slots;695}696697// Iterates over the superinterface type hierarchy looking for all methods698// with a specific erased signature.699class FindMethodsByErasedSig : public HierarchyVisitor<FindMethodsByErasedSig> {700private:701// Context data702Symbol* _method_name;703Symbol* _method_signature;704StatefulMethodFamily* _family;705706public:707FindMethodsByErasedSig(Symbol* name, Symbol* signature) :708_method_name(name), _method_signature(signature),709_family(NULL) {}710711void get_discovered_family(MethodFamily** family) {712if (_family != NULL) {713*family = _family->get_method_family();714} else {715*family = NULL;716}717}718719void* new_node_data(InstanceKlass* cls) { return new PseudoScope(); }720void free_node_data(void* node_data) {721PseudoScope::cast(node_data)->destroy();722}723724// Find all methods on this hierarchy that match this725// method's erased (name, signature)726bool visit() {727PseudoScope* scope = PseudoScope::cast(current_data());728InstanceKlass* iklass = current_class();729730Method* m = iklass->find_method(_method_name, _method_signature);731// private interface methods are not candidates for default methods732// invokespecial to private interface methods doesn't use default method logic733// private class methods are not candidates for default methods,734// private methods do not override default methods, so need to perform735// default method inheritance without including private methods736// The overpasses are your supertypes' errors, we do not include them737// future: take access controls into account for superclass methods738if (m != NULL && !m->is_static() && !m->is_overpass() && !m->is_private()) {739if (_family == NULL) {740_family = new StatefulMethodFamily();741}742743if (iklass->is_interface()) {744StateRestorer* restorer = _family->record_method_and_dq_further(m);745scope->add_mark(restorer);746} else {747// This is the rule that methods in classes "win" (bad word) over748// methods in interfaces. This works because of single inheritance749// private methods in classes do not "win", they will be found750// first on searching, but overriding for invokevirtual needs751// to find default method candidates for the same signature752_family->set_target_if_empty(m);753}754}755return true;756}757758};759760761762static void create_defaults_and_exceptions(763GrowableArray<EmptyVtableSlot*>* slots, InstanceKlass* klass, TRAPS);764765static void generate_erased_defaults(766InstanceKlass* klass, GrowableArray<EmptyVtableSlot*>* empty_slots,767EmptyVtableSlot* slot, TRAPS) {768769// sets up a set of methods with the same exact erased signature770FindMethodsByErasedSig visitor(slot->name(), slot->signature());771visitor.run(klass);772773MethodFamily* family;774visitor.get_discovered_family(&family);775if (family != NULL) {776family->determine_target(klass, CHECK);777slot->bind_family(family);778}779}780781static void merge_in_new_methods(InstanceKlass* klass,782GrowableArray<Method*>* new_methods, TRAPS);783static void create_default_methods( InstanceKlass* klass,784GrowableArray<Method*>* new_methods, TRAPS);785786// This is the guts of the default methods implementation. This is called just787// after the classfile has been parsed if some ancestor has default methods.788//789// First if finds any name/signature slots that need any implementation (either790// because they are miranda or a superclass's implementation is an overpass791// itself). For each slot, iterate over the hierarchy, to see if they contain a792// signature that matches the slot we are looking at.793//794// For each slot filled, we generate an overpass method that either calls the795// unique default method candidate using invokespecial, or throws an exception796// (in the case of no default method candidates, or more than one valid797// candidate). These methods are then added to the class's method list.798// The JVM does not create bridges nor handle generic signatures here.799void DefaultMethods::generate_default_methods(800InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) {801802// This resource mark is the bound for all memory allocation that takes803// place during default method processing. After this goes out of scope,804// all (Resource) objects' memory will be reclaimed. Be careful if adding an805// embedded resource mark under here as that memory can't be used outside806// whatever scope it's in.807ResourceMark rm(THREAD);808809// Keep entire hierarchy alive for the duration of the computation810KeepAliveRegistrar keepAlive(THREAD);811KeepAliveVisitor loadKeepAlive(&keepAlive);812loadKeepAlive.run(klass);813814#ifndef PRODUCT815if (TraceDefaultMethods) {816ResourceMark rm; // be careful with these!817tty->print_cr("%s %s requires default method processing",818klass->is_interface() ? "Interface" : "Class",819klass->name()->as_klass_external_name());820PrintHierarchy printer;821printer.run(klass);822}823#endif // ndef PRODUCT824825GrowableArray<EmptyVtableSlot*>* empty_slots =826find_empty_vtable_slots(klass, mirandas, CHECK);827828for (int i = 0; i < empty_slots->length(); ++i) {829EmptyVtableSlot* slot = empty_slots->at(i);830#ifndef PRODUCT831if (TraceDefaultMethods) {832streamIndentor si(tty, 2);833tty->indent().print("Looking for default methods for slot ");834slot->print_on(tty);835tty->cr();836}837#endif // ndef PRODUCT838839generate_erased_defaults(klass, empty_slots, slot, CHECK);840}841#ifndef PRODUCT842if (TraceDefaultMethods) {843tty->print_cr("Creating defaults and overpasses...");844}845#endif // ndef PRODUCT846847create_defaults_and_exceptions(empty_slots, klass, CHECK);848849#ifndef PRODUCT850if (TraceDefaultMethods) {851tty->print_cr("Default method processing complete");852}853#endif // ndef PRODUCT854}855856static int assemble_method_error(857BytecodeConstantPool* cp, BytecodeBuffer* buffer, Symbol* errorName, Symbol* message, TRAPS) {858859Symbol* init = vmSymbols::object_initializer_name();860Symbol* sig = vmSymbols::string_void_signature();861862BytecodeAssembler assem(buffer, cp);863864assem._new(errorName);865assem.dup();866assem.load_string(message);867assem.invokespecial(errorName, init, sig);868assem.athrow();869870return 3; // max stack size: [ exception, exception, string ]871}872873static Method* new_method(874BytecodeConstantPool* cp, BytecodeBuffer* bytecodes, Symbol* name,875Symbol* sig, AccessFlags flags, int max_stack, int params,876ConstMethod::MethodType mt, TRAPS) {877878address code_start = 0;879int code_length = 0;880InlineTableSizes sizes;881882if (bytecodes != NULL && bytecodes->length() > 0) {883code_start = static_cast<address>(bytecodes->adr_at(0));884code_length = bytecodes->length();885}886887Method* m = Method::allocate(cp->pool_holder()->class_loader_data(),888code_length, flags, &sizes,889mt, CHECK_NULL);890891m->set_constants(NULL); // This will get filled in later892m->set_name_index(cp->utf8(name));893m->set_signature_index(cp->utf8(sig));894ResultTypeFinder rtf(sig);895m->constMethod()->set_result_type(rtf.type());896m->set_size_of_parameters(params);897m->set_max_stack(max_stack);898m->set_max_locals(params);899m->constMethod()->set_stackmap_data(NULL);900m->set_code(code_start);901902return m;903}904905static void switchover_constant_pool(BytecodeConstantPool* bpool,906InstanceKlass* klass, GrowableArray<Method*>* new_methods, TRAPS) {907908if (new_methods->length() > 0) {909ConstantPool* cp = bpool->create_constant_pool(CHECK);910if (cp != klass->constants()) {911klass->class_loader_data()->add_to_deallocate_list(klass->constants());912klass->set_constants(cp);913cp->set_pool_holder(klass);914915for (int i = 0; i < new_methods->length(); ++i) {916new_methods->at(i)->set_constants(cp);917}918for (int i = 0; i < klass->methods()->length(); ++i) {919Method* mo = klass->methods()->at(i);920mo->set_constants(cp);921}922}923}924}925926// Create default_methods list for the current class.927// With the VM only processing erased signatures, the VM only928// creates an overpass in a conflict case or a case with no candidates.929// This allows virtual methods to override the overpass, but ensures930// that a local method search will find the exception rather than an abstract931// or default method that is not a valid candidate.932static void create_defaults_and_exceptions(933GrowableArray<EmptyVtableSlot*>* slots,934InstanceKlass* klass, TRAPS) {935936GrowableArray<Method*> overpasses;937GrowableArray<Method*> defaults;938BytecodeConstantPool bpool(klass->constants());939940for (int i = 0; i < slots->length(); ++i) {941EmptyVtableSlot* slot = slots->at(i);942943if (slot->is_bound()) {944MethodFamily* method = slot->get_binding();945BytecodeBuffer buffer;946947#ifndef PRODUCT948if (TraceDefaultMethods) {949tty->print("for slot: ");950slot->print_on(tty);951tty->cr();952if (method->has_target()) {953method->print_selected(tty, 1);954} else if (method->throws_exception()) {955method->print_exception(tty, 1);956}957}958#endif // ndef PRODUCT959960if (method->has_target()) {961Method* selected = method->get_selected_target();962if (selected->method_holder()->is_interface()) {963defaults.push(selected);964}965} else if (method->throws_exception()) {966int max_stack = assemble_method_error(&bpool, &buffer,967method->get_exception_name(), method->get_exception_message(), CHECK);968AccessFlags flags = accessFlags_from(969JVM_ACC_PUBLIC | JVM_ACC_SYNTHETIC | JVM_ACC_BRIDGE);970Method* m = new_method(&bpool, &buffer, slot->name(), slot->signature(),971flags, max_stack, slot->size_of_parameters(),972ConstMethod::OVERPASS, CHECK);973// We push to the methods list:974// overpass methods which are exception throwing methods975if (m != NULL) {976overpasses.push(m);977}978}979}980}981982#ifndef PRODUCT983if (TraceDefaultMethods) {984tty->print_cr("Created %d overpass methods", overpasses.length());985tty->print_cr("Created %d default methods", defaults.length());986}987#endif // ndef PRODUCT988989if (overpasses.length() > 0) {990switchover_constant_pool(&bpool, klass, &overpasses, CHECK);991merge_in_new_methods(klass, &overpasses, CHECK);992}993if (defaults.length() > 0) {994create_default_methods(klass, &defaults, CHECK);995}996}997998static void create_default_methods( InstanceKlass* klass,999GrowableArray<Method*>* new_methods, TRAPS) {10001001int new_size = new_methods->length();1002Array<Method*>* total_default_methods = MetadataFactory::new_array<Method*>(1003klass->class_loader_data(), new_size, NULL, CHECK);1004for (int index = 0; index < new_size; index++ ) {1005total_default_methods->at_put(index, new_methods->at(index));1006}1007Method::sort_methods(total_default_methods, false, false);10081009klass->set_default_methods(total_default_methods);1010}10111012static void sort_methods(GrowableArray<Method*>* methods) {1013// Note that this must sort using the same key as is used for sorting1014// methods in InstanceKlass.1015bool sorted = true;1016for (int i = methods->length() - 1; i > 0; --i) {1017for (int j = 0; j < i; ++j) {1018Method* m1 = methods->at(j);1019Method* m2 = methods->at(j + 1);1020if ((uintptr_t)m1->name() > (uintptr_t)m2->name()) {1021methods->at_put(j, m2);1022methods->at_put(j + 1, m1);1023sorted = false;1024}1025}1026if (sorted) break;1027sorted = true;1028}1029#ifdef ASSERT1030uintptr_t prev = 0;1031for (int i = 0; i < methods->length(); ++i) {1032Method* mh = methods->at(i);1033uintptr_t nv = (uintptr_t)mh->name();1034assert(nv >= prev, "Incorrect overpass method ordering");1035prev = nv;1036}1037#endif1038}10391040static void merge_in_new_methods(InstanceKlass* klass,1041GrowableArray<Method*>* new_methods, TRAPS) {10421043enum { ANNOTATIONS, PARAMETERS, DEFAULTS, NUM_ARRAYS };10441045Array<Method*>* original_methods = klass->methods();1046Array<int>* original_ordering = klass->method_ordering();1047Array<int>* merged_ordering = Universe::the_empty_int_array();10481049int new_size = klass->methods()->length() + new_methods->length();10501051Array<Method*>* merged_methods = MetadataFactory::new_array<Method*>(1052klass->class_loader_data(), new_size, NULL, CHECK);10531054// original_ordering might be empty if this class has no methods of its own1055if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {1056merged_ordering = MetadataFactory::new_array<int>(1057klass->class_loader_data(), new_size, CHECK);1058}1059int method_order_index = klass->methods()->length();10601061sort_methods(new_methods);10621063// Perform grand merge of existing methods and new methods1064int orig_idx = 0;1065int new_idx = 0;10661067for (int i = 0; i < new_size; ++i) {1068Method* orig_method = NULL;1069Method* new_method = NULL;1070if (orig_idx < original_methods->length()) {1071orig_method = original_methods->at(orig_idx);1072}1073if (new_idx < new_methods->length()) {1074new_method = new_methods->at(new_idx);1075}10761077if (orig_method != NULL &&1078(new_method == NULL || orig_method->name() < new_method->name())) {1079merged_methods->at_put(i, orig_method);1080original_methods->at_put(orig_idx, NULL);1081if (merged_ordering->length() > 0) {1082assert(original_ordering != NULL && original_ordering->length() > 0,1083"should have original order information for this method");1084merged_ordering->at_put(i, original_ordering->at(orig_idx));1085}1086++orig_idx;1087} else {1088merged_methods->at_put(i, new_method);1089if (merged_ordering->length() > 0) {1090merged_ordering->at_put(i, method_order_index++);1091}1092++new_idx;1093}1094// update idnum for new location1095merged_methods->at(i)->set_method_idnum(i);1096merged_methods->at(i)->set_orig_method_idnum(i);1097}10981099// Verify correct order1100#ifdef ASSERT1101uintptr_t prev = 0;1102for (int i = 0; i < merged_methods->length(); ++i) {1103Method* mo = merged_methods->at(i);1104uintptr_t nv = (uintptr_t)mo->name();1105assert(nv >= prev, "Incorrect method ordering");1106prev = nv;1107}1108#endif11091110// Replace klass methods with new merged lists1111klass->set_methods(merged_methods);1112klass->set_initial_method_idnum(new_size);1113klass->set_method_ordering(merged_ordering);11141115// Free metadata1116ClassLoaderData* cld = klass->class_loader_data();1117if (original_methods->length() > 0) {1118MetadataFactory::free_array(cld, original_methods);1119}1120if (original_ordering != NULL && original_ordering->length() > 0) {1121MetadataFactory::free_array(cld, original_ordering);1122}1123}112411251126