Path: blob/master/src/hotspot/share/classfile/defaultMethods.cpp
40949 views
/*1* Copyright (c) 2012, 2021, 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 "classfile/systemDictionary.hpp"29#include "classfile/vmClasses.hpp"30#include "classfile/vmSymbols.hpp"31#include "logging/log.hpp"32#include "logging/logStream.hpp"33#include "memory/allocation.hpp"34#include "memory/metadataFactory.hpp"35#include "memory/resourceArea.hpp"36#include "memory/universe.hpp"37#include "prims/jvmtiExport.hpp"38#include "runtime/arguments.hpp"39#include "runtime/handles.inline.hpp"40#include "runtime/signature.hpp"41#include "runtime/thread.hpp"42#include "oops/instanceKlass.hpp"43#include "oops/klass.hpp"44#include "oops/method.hpp"45#include "utilities/accessFlags.hpp"46#include "utilities/exceptions.hpp"47#include "utilities/ostream.hpp"48#include "utilities/pair.hpp"49#include "utilities/resourceHash.hpp"5051typedef enum { QUALIFIED, DISQUALIFIED } QualifiedState;5253static void print_slot(outputStream* str, Symbol* name, Symbol* signature) {54str->print("%s%s", name->as_C_string(), signature->as_C_string());55}5657static void print_method(outputStream* str, Method* mo, bool with_class=true) {58if (with_class) {59str->print("%s.", mo->klass_name()->as_C_string());60}61print_slot(str, mo->name(), mo->signature());62}6364/**65* Perform a depth-first iteration over the class hierarchy, applying66* algorithmic logic as it goes.67*68* This class is one half of the inheritance hierarchy analysis mechanism.69* It is meant to be used in conjunction with another class, the algorithm,70* which is indicated by the ALGO template parameter. This class can be71* paired with any algorithm class that provides the required methods.72*73* This class contains all the mechanics for iterating over the class hierarchy74* starting at a particular root, without recursing (thus limiting stack growth75* from this point). It visits each superclass (if present) and superinterface76* in a depth-first manner, with callbacks to the ALGO class as each class is77* encountered (visit()), The algorithm can cut-off further exploration of a78* particular branch by returning 'false' from a visit() call.79*80* The ALGO class, must provide a visit() method, which each of which will be81* called once for each node in the inheritance tree during the iteration. In82* addition, it can provide a memory block via new_node_data(), which it can83* use for node-specific storage (and access via the current_data() and84* data_at_depth(int) methods).85*86* Bare minimum needed to be an ALGO class:87* class Algo : public HierarchyVisitor<Algo> {88* void* new_node_data() { return NULL; }89* void free_node_data(void* data) { return; }90* bool visit() { return true; }91* };92*/93template <class ALGO>94class HierarchyVisitor : StackObj {95private:9697class Node : public ResourceObj {98public:99InstanceKlass* _class;100bool _super_was_visited;101int _interface_index;102void* _algorithm_data;103104Node(InstanceKlass* cls, void* data, bool visit_super)105: _class(cls), _super_was_visited(!visit_super),106_interface_index(0), _algorithm_data(data) {}107108void update(InstanceKlass* cls, void* data, bool visit_super) {109_class = cls;110_super_was_visited = !visit_super;111_interface_index = 0;112_algorithm_data = data;113}114int number_of_interfaces() { return _class->local_interfaces()->length(); }115int interface_index() { return _interface_index; }116void set_super_visited() { _super_was_visited = true; }117void increment_visited_interface() { ++_interface_index; }118void set_all_interfaces_visited() {119_interface_index = number_of_interfaces();120}121bool has_visited_super() { return _super_was_visited; }122bool has_visited_all_interfaces() {123return interface_index() >= number_of_interfaces();124}125InstanceKlass* interface_at(int index) {126return _class->local_interfaces()->at(index);127}128InstanceKlass* next_super() { return _class->java_super(); }129InstanceKlass* next_interface() {130return interface_at(interface_index());131}132};133134bool _visited_Object;135136GrowableArray<Node*> _path;137GrowableArray<Node*> _free_nodes;138139Node* current_top() const { return _path.top(); }140bool has_more_nodes() const { return _path.length() > 0; }141void push(InstanceKlass* cls, ALGO* algo) {142assert(cls != NULL, "Requires a valid instance class");143if (cls == vmClasses::Object_klass()) {144_visited_Object = true;145}146void* data = algo->new_node_data();147Node* node;148if (_free_nodes.is_empty()) { // Add a new node149node = new Node(cls, data, has_super(cls));150} else { // Reuse existing node and data151node = _free_nodes.pop();152node->update(cls, data, has_super(cls));153}154_path.push(node);155}156void pop() {157Node* node = _path.pop();158// Make the node available for reuse159_free_nodes.push(node);160}161162// Since the starting point can be an interface, we must ensure we catch163// j.l.Object as the super once in those cases. The _visited_Object flag164// only ensures we don't then repeatedly enqueue Object for each interface165// in the class hierarchy.166bool has_super(InstanceKlass* cls) {167return cls->super() != NULL && (!_visited_Object || !cls->is_interface());168}169170Node* node_at_depth(int i) const {171return (i >= _path.length()) ? NULL : _path.at(_path.length() - i - 1);172}173174protected:175176// Resets the visitor177void reset() {178_visited_Object = false;179}180181// Accessors available to the algorithm182int current_depth() const { return _path.length() - 1; }183184InstanceKlass* class_at_depth(int i) {185Node* n = node_at_depth(i);186return n == NULL ? NULL : n->_class;187}188InstanceKlass* current_class() { return class_at_depth(0); }189190void* data_at_depth(int i) {191Node* n = node_at_depth(i);192return n == NULL ? NULL : n->_algorithm_data;193}194void* current_data() { return data_at_depth(0); }195196public:197HierarchyVisitor() : _visited_Object(false), _path() {}198199void run(InstanceKlass* root) {200ALGO* algo = static_cast<ALGO*>(this);201202push(root, algo);203bool top_needs_visit = true;204do {205Node* top = current_top();206if (top_needs_visit) {207if (algo->visit() == false) {208// algorithm does not want to continue along this path. Arrange209// it so that this state is immediately popped off the stack210top->set_super_visited();211top->set_all_interfaces_visited();212}213top_needs_visit = false;214}215216if (top->has_visited_super() && top->has_visited_all_interfaces()) {217algo->free_node_data(top->_algorithm_data);218pop();219} else {220InstanceKlass* next = NULL;221if (top->has_visited_super() == false) {222next = top->next_super();223top->set_super_visited();224} else {225next = top->next_interface();226top->increment_visited_interface();227}228assert(next != NULL, "Otherwise we shouldn't be here");229push(next, algo);230top_needs_visit = true;231}232} while (has_more_nodes());233}234};235236class PrintHierarchy : public HierarchyVisitor<PrintHierarchy> {237private:238outputStream* _st;239public:240bool visit() {241InstanceKlass* cls = current_class();242streamIndentor si(_st, current_depth() * 2);243_st->indent().print_cr("%s", cls->name()->as_C_string());244return true;245}246247void* new_node_data() { return NULL; }248void free_node_data(void* data) { return; }249250PrintHierarchy(outputStream* st = tty) : _st(st) {}251};252253// Used to register InstanceKlass objects and all related metadata structures254// (Methods, ConstantPools) as "in-use" by the current thread so that they can't255// be deallocated by class redefinition while we're using them. The classes are256// de-registered when this goes out of scope.257//258// Once a class is registered, we need not bother with methodHandles or259// constantPoolHandles for it's associated metadata.260class KeepAliveRegistrar : public StackObj {261private:262Thread* _thread;263GrowableArray<ConstantPool*> _keep_alive;264265public:266KeepAliveRegistrar(Thread* thread) : _thread(thread), _keep_alive(6) {267assert(thread == Thread::current(), "Must be current thread");268}269270~KeepAliveRegistrar() {271for (int i = _keep_alive.length() - 1; i >= 0; --i) {272ConstantPool* cp = _keep_alive.at(i);273int idx = _thread->metadata_handles()->find_from_end(cp);274assert(idx > 0, "Must be in the list");275_thread->metadata_handles()->remove_at(idx);276}277}278279// Register a class as 'in-use' by the thread. It's fine to register a class280// multiple times (though perhaps inefficient)281void register_class(InstanceKlass* ik) {282ConstantPool* cp = ik->constants();283_keep_alive.push(cp);284_thread->metadata_handles()->push(cp);285}286};287288class KeepAliveVisitor : public HierarchyVisitor<KeepAliveVisitor> {289private:290KeepAliveRegistrar* _registrar;291292public:293KeepAliveVisitor(KeepAliveRegistrar* registrar) : _registrar(registrar) {}294295void* new_node_data() { return NULL; }296void free_node_data(void* data) { return; }297298bool visit() {299_registrar->register_class(current_class());300return true;301}302};303304305// A method family contains a set of all methods that implement a single306// erased method. As members of the set are collected while walking over the307// hierarchy, they are tagged with a qualification state. The qualification308// state for an erased method is set to disqualified if there exists a path309// from the root of hierarchy to the method that contains an interleaving310// erased method defined in an interface.311312class MethodState {313public:314Method* _method;315QualifiedState _state;316317MethodState() : _method(NULL), _state(DISQUALIFIED) {}318MethodState(Method* method, QualifiedState state) : _method(method), _state(state) {}319};320321class MethodFamily : public ResourceObj {322private:323324GrowableArray<MethodState> _members;325326Method* _selected_target; // Filled in later, if a unique target exists327Symbol* _exception_message; // If no unique target is found328Symbol* _exception_name; // If no unique target is found329330MethodState* find_method(Method* method) {331for (int i = 0; i < _members.length(); i++) {332if (_members.at(i)._method == method) {333return &_members.at(i);334}335}336return NULL;337}338339void add_method(Method* method, QualifiedState state) {340MethodState method_state(method, state);341_members.append(method_state);342}343344Symbol* generate_no_defaults_message() const;345Symbol* generate_method_message(Symbol *klass_name, Method* method) const;346Symbol* generate_conflicts_message(GrowableArray<MethodState>* methods) const;347348public:349350MethodFamily()351: _selected_target(NULL), _exception_message(NULL), _exception_name(NULL) {}352353void set_target_if_empty(Method* m) {354if (_selected_target == NULL && !m->is_overpass()) {355_selected_target = m;356}357}358359void record_method(Method* m, QualifiedState state) {360// If not in the set, add it. If it's already in the set, then leave it361// as is if state is qualified, or set it to disqualified if state is362// disqualified.363MethodState* method_state = find_method(m);364if (method_state == NULL) {365add_method(m, state);366} else if (state == DISQUALIFIED) {367method_state->_state = DISQUALIFIED;368}369}370371bool has_target() const { return _selected_target != NULL; }372bool throws_exception() { return _exception_message != NULL; }373374Method* get_selected_target() { return _selected_target; }375Symbol* get_exception_message() { return _exception_message; }376Symbol* get_exception_name() { return _exception_name; }377378// Either sets the target or the exception error message379void determine_target_or_set_exception_message(InstanceKlass* root) {380if (has_target() || throws_exception()) {381return;382}383384// Qualified methods are maximally-specific methods385// These include public, instance concrete (=default) and abstract methods386int num_defaults = 0;387int default_index = -1;388for (int i = 0; i < _members.length(); i++) {389MethodState &member = _members.at(i);390if (member._state == QUALIFIED) {391if (member._method->is_default_method()) {392num_defaults++;393default_index = i;394}395}396}397398if (num_defaults == 1) {399assert(_members.at(default_index)._state == QUALIFIED, "");400_selected_target = _members.at(default_index)._method;401} else {402generate_and_set_exception_message(root, num_defaults, default_index);403}404}405406void generate_and_set_exception_message(InstanceKlass* root, int num_defaults, int default_index) {407assert(num_defaults != 1, "invariant - should've been handled calling method");408409GrowableArray<Method*> qualified_methods;410for (int i = 0; i < _members.length(); i++) {411MethodState& member = _members.at(i);412if (member._state == QUALIFIED) {413qualified_methods.push(member._method);414}415}416if (num_defaults == 0) {417// If the root klass has a static method with matching name and signature418// then do not generate an overpass method because it will hide the419// static method during resolution.420if (qualified_methods.length() == 0) {421_exception_message = generate_no_defaults_message();422} else {423assert(root != NULL, "Null root class");424_exception_message = generate_method_message(root->name(), qualified_methods.at(0));425}426_exception_name = vmSymbols::java_lang_AbstractMethodError();427} else {428_exception_message = generate_conflicts_message(&_members);429_exception_name = vmSymbols::java_lang_IncompatibleClassChangeError();430LogTarget(Debug, defaultmethods) lt;431if (lt.is_enabled()) {432LogStream ls(lt);433_exception_message->print_value_on(&ls);434ls.cr();435}436}437}438439void print_selected(outputStream* str, int indent) const {440assert(has_target(), "Should be called otherwise");441streamIndentor si(str, indent * 2);442str->indent().print("Selected method: ");443print_method(str, _selected_target);444Klass* method_holder = _selected_target->method_holder();445if (!method_holder->is_interface()) {446str->print(" : in superclass");447}448str->cr();449}450451void print_exception(outputStream* str, int indent) {452assert(throws_exception(), "Should be called otherwise");453assert(_exception_name != NULL, "exception_name should be set");454streamIndentor si(str, indent * 2);455str->indent().print_cr("%s: %s", _exception_name->as_C_string(), _exception_message->as_C_string());456}457};458459Symbol* MethodFamily::generate_no_defaults_message() const {460return SymbolTable::new_symbol("No qualifying defaults found");461}462463Symbol* MethodFamily::generate_method_message(Symbol *klass_name, Method* method) const {464stringStream ss;465ss.print("Method ");466Symbol* name = method->name();467Symbol* signature = method->signature();468ss.write((const char*)klass_name->bytes(), klass_name->utf8_length());469ss.print(".");470ss.write((const char*)name->bytes(), name->utf8_length());471ss.write((const char*)signature->bytes(), signature->utf8_length());472ss.print(" is abstract");473return SymbolTable::new_symbol(ss.base(), (int)ss.size());474}475476Symbol* MethodFamily::generate_conflicts_message(GrowableArray<MethodState>* methods) const {477stringStream ss;478ss.print("Conflicting default methods:");479for (int i = 0; i < methods->length(); ++i) {480Method *method = methods->at(i)._method;481Symbol *klass = method->klass_name();482Symbol *name = method->name();483ss.print(" ");484ss.write((const char*) klass->bytes(), klass->utf8_length());485ss.print(".");486ss.write((const char*) name->bytes(), name->utf8_length());487}488return SymbolTable::new_symbol(ss.base(), (int)ss.size());489}490491492class StateRestorerScope;493494// StatefulMethodFamily is a wrapper around a MethodFamily that maintains the495// qualification state during hierarchy visitation, and applies that state496// when adding members to the MethodFamily497class StatefulMethodFamily : public ResourceObj {498friend class StateRestorer;499private:500QualifiedState _qualification_state;501502void set_qualification_state(QualifiedState state) {503_qualification_state = state;504}505506protected:507MethodFamily _method_family;508509public:510StatefulMethodFamily() {511_qualification_state = QUALIFIED;512}513514void set_target_if_empty(Method* m) { _method_family.set_target_if_empty(m); }515516MethodFamily* get_method_family() { return &_method_family; }517518void record_method_and_dq_further(StateRestorerScope* scope, Method* mo);519};520521// Because we use an iterative algorithm when iterating over the type522// hierarchy, we can't use traditional scoped objects which automatically do523// cleanup in the destructor when the scope is exited. StateRestorerScope (and524// StateRestorer) provides a similar functionality, but for when you want a525// scoped object in non-stack memory (such as in resource memory, as we do526// here). You've just got to remember to call 'restore_state()' on the scope when527// leaving it (and marks have to be explicitly added). The scope is reusable after528// 'restore_state()' has been called.529class StateRestorer : public ResourceObj {530public:531StatefulMethodFamily* _method;532QualifiedState _state_to_restore;533534StateRestorer() : _method(NULL), _state_to_restore(DISQUALIFIED) {}535536void restore_state() { _method->set_qualification_state(_state_to_restore); }537};538539class StateRestorerScope : public ResourceObj {540private:541GrowableArray<StateRestorer*> _marks;542GrowableArray<StateRestorer*>* _free_list; // Shared between scopes543public:544StateRestorerScope(GrowableArray<StateRestorer*>* free_list) : _marks(), _free_list(free_list) {}545546static StateRestorerScope* cast(void* data) {547return static_cast<StateRestorerScope*>(data);548}549550void mark(StatefulMethodFamily* family, QualifiedState qualification_state) {551StateRestorer* restorer;552if (!_free_list->is_empty()) {553restorer = _free_list->pop();554} else {555restorer = new StateRestorer();556}557restorer->_method = family;558restorer->_state_to_restore = qualification_state;559_marks.append(restorer);560}561562#ifdef ASSERT563bool is_empty() {564return _marks.is_empty();565}566#endif567568void restore_state() {569while(!_marks.is_empty()) {570StateRestorer* restorer = _marks.pop();571restorer->restore_state();572_free_list->push(restorer);573}574}575};576577void StatefulMethodFamily::record_method_and_dq_further(StateRestorerScope* scope, Method* mo) {578scope->mark(this, _qualification_state);579_method_family.record_method(mo, _qualification_state);580581// Everything found "above"??? this method in the hierarchy walk is set to582// disqualified583set_qualification_state(DISQUALIFIED);584}585586// Represents a location corresponding to a vtable slot for methods that587// neither the class nor any of it's ancestors provide an implementaion.588// Default methods may be present to fill this slot.589class EmptyVtableSlot : public ResourceObj {590private:591Symbol* _name;592Symbol* _signature;593int _size_of_parameters;594MethodFamily* _binding;595596public:597EmptyVtableSlot(Method* method)598: _name(method->name()), _signature(method->signature()),599_size_of_parameters(method->size_of_parameters()), _binding(NULL) {}600601Symbol* name() const { return _name; }602Symbol* signature() const { return _signature; }603int size_of_parameters() const { return _size_of_parameters; }604605void bind_family(MethodFamily* lm) { _binding = lm; }606bool is_bound() { return _binding != NULL; }607MethodFamily* get_binding() { return _binding; }608609void print_on(outputStream* str) const {610print_slot(str, name(), signature());611}612};613614static bool already_in_vtable_slots(GrowableArray<EmptyVtableSlot*>* slots, Method* m) {615bool found = false;616for (int j = 0; j < slots->length(); ++j) {617if (slots->at(j)->name() == m->name() &&618slots->at(j)->signature() == m->signature() ) {619found = true;620break;621}622}623return found;624}625626static void find_empty_vtable_slots(GrowableArray<EmptyVtableSlot*>* slots,627InstanceKlass* klass, const GrowableArray<Method*>* mirandas) {628629assert(klass != NULL, "Must be valid class");630631// All miranda methods are obvious candidates632for (int i = 0; i < mirandas->length(); ++i) {633Method* m = mirandas->at(i);634if (!already_in_vtable_slots(slots, m)) {635slots->append(new EmptyVtableSlot(m));636}637}638639// Also any overpasses in our superclasses, that we haven't implemented.640// (can't use the vtable because it is not guaranteed to be initialized yet)641InstanceKlass* super = klass->java_super();642while (super != NULL) {643for (int i = 0; i < super->methods()->length(); ++i) {644Method* m = super->methods()->at(i);645if (m->is_overpass() || m->is_static()) {646// m is a method that would have been a miranda if not for the647// default method processing that occurred on behalf of our superclass,648// so it's a method we want to re-examine in this new context. That is,649// unless we have a real implementation of it in the current class.650if (!already_in_vtable_slots(slots, m)) {651Method *impl = klass->lookup_method(m->name(), m->signature());652if (impl == NULL || impl->is_overpass() || impl->is_static()) {653slots->append(new EmptyVtableSlot(m));654}655}656}657}658659// also any default methods in our superclasses660if (super->default_methods() != NULL) {661for (int i = 0; i < super->default_methods()->length(); ++i) {662Method* m = super->default_methods()->at(i);663// m is a method that would have been a miranda if not for the664// default method processing that occurred on behalf of our superclass,665// so it's a method we want to re-examine in this new context. That is,666// unless we have a real implementation of it in the current class.667if (!already_in_vtable_slots(slots, m)) {668Method* impl = klass->lookup_method(m->name(), m->signature());669if (impl == NULL || impl->is_overpass() || impl->is_static()) {670slots->append(new EmptyVtableSlot(m));671}672}673}674}675super = super->java_super();676}677678LogTarget(Debug, defaultmethods) lt;679if (lt.is_enabled()) {680lt.print("Slots that need filling:");681ResourceMark rm;682LogStream ls(lt);683streamIndentor si(&ls);684for (int i = 0; i < slots->length(); ++i) {685ls.indent();686slots->at(i)->print_on(&ls);687ls.cr();688}689}690}691692// Iterates over the superinterface type hierarchy looking for all methods693// with a specific erased signature.694class FindMethodsByErasedSig : public HierarchyVisitor<FindMethodsByErasedSig> {695private:696// Context data697Symbol* _method_name;698Symbol* _method_signature;699StatefulMethodFamily* _family;700bool _cur_class_is_interface;701// Free lists, used as an optimization702GrowableArray<StateRestorerScope*> _free_scopes;703GrowableArray<StateRestorer*> _free_restorers;704public:705FindMethodsByErasedSig() : _free_scopes(6), _free_restorers(6) {};706707void prepare(Symbol* name, Symbol* signature, bool is_interf) {708reset();709_method_name = name;710_method_signature = signature;711_family = NULL;712_cur_class_is_interface = is_interf;713}714715void get_discovered_family(MethodFamily** family) {716if (_family != NULL) {717*family = _family->get_method_family();718} else {719*family = NULL;720}721}722723void* new_node_data() {724if (!_free_scopes.is_empty()) {725StateRestorerScope* free_scope = _free_scopes.pop();726assert(free_scope->is_empty(), "StateRestorerScope::_marks array not empty");727return free_scope;728}729return new StateRestorerScope(&_free_restorers);730}731void free_node_data(void* node_data) {732StateRestorerScope* scope = StateRestorerScope::cast(node_data);733scope->restore_state();734// Reuse scopes735_free_scopes.push(scope);736}737738// Find all methods on this hierarchy that match this739// method's erased (name, signature)740bool visit() {741StateRestorerScope* scope = StateRestorerScope::cast(current_data());742InstanceKlass* iklass = current_class();743744Method* m = iklass->find_method(_method_name, _method_signature);745// Private interface methods are not candidates for default methods.746// invokespecial to private interface methods doesn't use default method logic.747// Private class methods are not candidates for default methods.748// Private methods do not override default methods, so need to perform749// default method inheritance without including private methods.750// The overpasses are your supertypes' errors, we do not include them.751// Non-public methods in java.lang.Object are not candidates for default752// methods.753// Future: take access controls into account for superclass methods754if (m != NULL && !m->is_static() && !m->is_overpass() && !m->is_private() &&755(!_cur_class_is_interface || !SystemDictionary::is_nonpublic_Object_method(m))) {756if (_family == NULL) {757_family = new StatefulMethodFamily();758}759760if (iklass->is_interface()) {761_family->record_method_and_dq_further(scope, m);762} else {763// This is the rule that methods in classes "win" (bad word) over764// methods in interfaces. This works because of single inheritance.765// Private methods in classes do not "win", they will be found766// first on searching, but overriding for invokevirtual needs767// to find default method candidates for the same signature768_family->set_target_if_empty(m);769}770}771return true;772}773774};775776777778static void create_defaults_and_exceptions(779GrowableArray<EmptyVtableSlot*>* slots, InstanceKlass* klass, TRAPS);780781static void generate_erased_defaults(782FindMethodsByErasedSig* visitor,783InstanceKlass* klass, EmptyVtableSlot* slot, bool is_intf) {784785// the visitor needs to be initialized or re-initialized before use786// - this facilitates reusing the same visitor instance on multiple787// generation passes as an optimization788visitor->prepare(slot->name(), slot->signature(), is_intf);789// sets up a set of methods with the same exact erased signature790visitor->run(klass);791792MethodFamily* family;793visitor->get_discovered_family(&family);794if (family != NULL) {795family->determine_target_or_set_exception_message(klass);796slot->bind_family(family);797}798}799800static void merge_in_new_methods(InstanceKlass* klass,801GrowableArray<Method*>* new_methods, TRAPS);802static void create_default_methods( InstanceKlass* klass,803GrowableArray<Method*>* new_methods, TRAPS);804805// This is the guts of the default methods implementation. This is called just806// after the classfile has been parsed if some ancestor has default methods.807//808// First it finds any name/signature slots that need any implementation (either809// because they are miranda or a superclass's implementation is an overpass810// itself). For each slot, iterate over the hierarchy, to see if they contain a811// signature that matches the slot we are looking at.812//813// For each slot filled, we either record the default method candidate in the814// klass default_methods list or, only to handle exception cases, we create an815// overpass method that throws an exception and add it to the klass methods list.816// The JVM does not create bridges nor handle generic signatures here.817void DefaultMethods::generate_default_methods(818InstanceKlass* klass, const GrowableArray<Method*>* mirandas, TRAPS) {819assert(klass != NULL, "invariant");820assert(klass != vmClasses::Object_klass(), "Shouldn't be called for Object");821822// This resource mark is the bound for all memory allocation that takes823// place during default method processing. After this goes out of scope,824// all (Resource) objects' memory will be reclaimed. Be careful if adding an825// embedded resource mark under here as that memory can't be used outside826// whatever scope it's in.827ResourceMark rm(THREAD);828829// Keep entire hierarchy alive for the duration of the computation830constantPoolHandle cp(THREAD, klass->constants());831KeepAliveRegistrar keepAlive(THREAD);832KeepAliveVisitor loadKeepAlive(&keepAlive);833loadKeepAlive.run(klass);834835LogTarget(Debug, defaultmethods) lt;836if (lt.is_enabled()) {837ResourceMark rm(THREAD);838lt.print("%s %s requires default method processing",839klass->is_interface() ? "Interface" : "Class",840klass->name()->as_klass_external_name());841LogStream ls(lt);842PrintHierarchy printer(&ls);843printer.run(klass);844}845846GrowableArray<EmptyVtableSlot*> empty_slots;847find_empty_vtable_slots(&empty_slots, klass, mirandas);848849if (empty_slots.length() > 0) {850FindMethodsByErasedSig findMethodsByErasedSig;851for (int i = 0; i < empty_slots.length(); ++i) {852EmptyVtableSlot* slot = empty_slots.at(i);853LogTarget(Debug, defaultmethods) lt;854if (lt.is_enabled()) {855LogStream ls(lt);856streamIndentor si(&ls, 2);857ls.indent().print("Looking for default methods for slot ");858slot->print_on(&ls);859ls.cr();860}861generate_erased_defaults(&findMethodsByErasedSig, klass, slot, klass->is_interface());862}863log_debug(defaultmethods)("Creating defaults and overpasses...");864create_defaults_and_exceptions(&empty_slots, klass, CHECK);865}866log_debug(defaultmethods)("Default method processing complete");867}868869static int assemble_method_error(870BytecodeConstantPool* cp, BytecodeBuffer* buffer, Symbol* errorName, Symbol* message) {871872Symbol* init = vmSymbols::object_initializer_name();873Symbol* sig = vmSymbols::string_void_signature();874875BytecodeAssembler assem(buffer, cp);876877assem._new(errorName);878assem.dup();879assem.load_string(message);880assem.invokespecial(errorName, init, sig);881assem.athrow();882883return 3; // max stack size: [ exception, exception, string ]884}885886static Method* new_method(887BytecodeConstantPool* cp, BytecodeBuffer* bytecodes, Symbol* name,888Symbol* sig, AccessFlags flags, int max_stack, int params,889ConstMethod::MethodType mt, TRAPS) {890891address code_start = 0;892int code_length = 0;893InlineTableSizes sizes;894895if (bytecodes != NULL && bytecodes->length() > 0) {896code_start = static_cast<address>(bytecodes->adr_at(0));897code_length = bytecodes->length();898}899900Method* m = Method::allocate(cp->pool_holder()->class_loader_data(),901code_length, flags, &sizes,902mt, CHECK_NULL);903904m->set_constants(NULL); // This will get filled in later905m->set_name_index(cp->utf8(name));906m->set_signature_index(cp->utf8(sig));907m->compute_from_signature(sig);908m->set_size_of_parameters(params);909m->set_max_stack(max_stack);910m->set_max_locals(params);911m->constMethod()->set_stackmap_data(NULL);912m->set_code(code_start);913914return m;915}916917static void switchover_constant_pool(BytecodeConstantPool* bpool,918InstanceKlass* klass, GrowableArray<Method*>* new_methods, TRAPS) {919920if (new_methods->length() > 0) {921ConstantPool* cp = bpool->create_constant_pool(CHECK);922if (cp != klass->constants()) {923// Copy resolved hidden class into new constant pool.924if (klass->is_hidden()) {925cp->klass_at_put(klass->this_class_index(), klass);926}927klass->class_loader_data()->add_to_deallocate_list(klass->constants());928klass->set_constants(cp);929cp->set_pool_holder(klass);930931for (int i = 0; i < new_methods->length(); ++i) {932new_methods->at(i)->set_constants(cp);933}934for (int i = 0; i < klass->methods()->length(); ++i) {935Method* mo = klass->methods()->at(i);936mo->set_constants(cp);937}938}939}940}941942// Create default_methods list for the current class.943// With the VM only processing erased signatures, the VM only944// creates an overpass in a conflict case or a case with no candidates.945// This allows virtual methods to override the overpass, but ensures946// that a local method search will find the exception rather than an abstract947// or default method that is not a valid candidate.948//949// Note that if overpass method are ever created that are not exception950// throwing methods then the loader constraint checking logic for vtable and951// itable creation needs to be changed to check loader constraints for the952// overpass methods that do not throw exceptions.953static void create_defaults_and_exceptions(GrowableArray<EmptyVtableSlot*>* slots,954InstanceKlass* klass, TRAPS) {955956GrowableArray<Method*> overpasses;957GrowableArray<Method*> defaults;958BytecodeConstantPool bpool(klass->constants());959960BytecodeBuffer* buffer = NULL; // Lazily create a reusable buffer961for (int i = 0; i < slots->length(); ++i) {962EmptyVtableSlot* slot = slots->at(i);963964if (slot->is_bound()) {965MethodFamily* method = slot->get_binding();966967LogTarget(Debug, defaultmethods) lt;968if (lt.is_enabled()) {969ResourceMark rm(THREAD);970LogStream ls(lt);971ls.print("for slot: ");972slot->print_on(&ls);973ls.cr();974if (method->has_target()) {975method->print_selected(&ls, 1);976} else if (method->throws_exception()) {977method->print_exception(&ls, 1);978}979}980981if (method->has_target()) {982Method* selected = method->get_selected_target();983if (selected->method_holder()->is_interface()) {984assert(!selected->is_private(), "pushing private interface method as default");985defaults.push(selected);986}987} else if (method->throws_exception()) {988if (buffer == NULL) {989buffer = new BytecodeBuffer();990} else {991buffer->clear();992}993int max_stack = assemble_method_error(&bpool, buffer,994method->get_exception_name(), method->get_exception_message());995AccessFlags flags = accessFlags_from(996JVM_ACC_PUBLIC | JVM_ACC_SYNTHETIC | JVM_ACC_BRIDGE);997Method* m = new_method(&bpool, buffer, slot->name(), slot->signature(),998flags, max_stack, slot->size_of_parameters(),999ConstMethod::OVERPASS, CHECK);1000// We push to the methods list:1001// overpass methods which are exception throwing methods1002if (m != NULL) {1003overpasses.push(m);1004}1005}1006}1007}100810091010log_debug(defaultmethods)("Created %d overpass methods", overpasses.length());1011log_debug(defaultmethods)("Created %d default methods", defaults.length());10121013if (overpasses.length() > 0) {1014switchover_constant_pool(&bpool, klass, &overpasses, CHECK);1015merge_in_new_methods(klass, &overpasses, CHECK);1016}1017if (defaults.length() > 0) {1018create_default_methods(klass, &defaults, CHECK);1019}1020}10211022static void create_default_methods(InstanceKlass* klass,1023GrowableArray<Method*>* new_methods, TRAPS) {10241025int new_size = new_methods->length();1026Array<Method*>* total_default_methods = MetadataFactory::new_array<Method*>(1027klass->class_loader_data(), new_size, NULL, CHECK);1028for (int index = 0; index < new_size; index++ ) {1029total_default_methods->at_put(index, new_methods->at(index));1030}1031Method::sort_methods(total_default_methods, /*set_idnums=*/false);10321033klass->set_default_methods(total_default_methods);1034// Create an array for mapping default methods to their vtable indices in1035// this class, since default methods vtable indices are the indices for1036// the defining class.1037klass->create_new_default_vtable_indices(new_size, CHECK);1038}10391040static void sort_methods(GrowableArray<Method*>* methods) {1041// Note that this must sort using the same key as is used for sorting1042// methods in InstanceKlass.1043bool sorted = true;1044for (int i = methods->length() - 1; i > 0; --i) {1045for (int j = 0; j < i; ++j) {1046Method* m1 = methods->at(j);1047Method* m2 = methods->at(j + 1);1048if ((uintptr_t)m1->name() > (uintptr_t)m2->name()) {1049methods->at_put(j, m2);1050methods->at_put(j + 1, m1);1051sorted = false;1052}1053}1054if (sorted) break;1055sorted = true;1056}1057#ifdef ASSERT1058uintptr_t prev = 0;1059for (int i = 0; i < methods->length(); ++i) {1060Method* mh = methods->at(i);1061uintptr_t nv = (uintptr_t)mh->name();1062assert(nv >= prev, "Incorrect overpass method ordering");1063prev = nv;1064}1065#endif1066}10671068static void merge_in_new_methods(InstanceKlass* klass,1069GrowableArray<Method*>* new_methods, TRAPS) {10701071enum { ANNOTATIONS, PARAMETERS, DEFAULTS, NUM_ARRAYS };10721073Array<Method*>* original_methods = klass->methods();1074Array<int>* original_ordering = klass->method_ordering();1075Array<int>* merged_ordering = Universe::the_empty_int_array();10761077int new_size = klass->methods()->length() + new_methods->length();10781079Array<Method*>* merged_methods = MetadataFactory::new_array<Method*>(1080klass->class_loader_data(), new_size, NULL, CHECK);10811082// original_ordering might be empty if this class has no methods of its own1083if (JvmtiExport::can_maintain_original_method_order() || Arguments::is_dumping_archive()) {1084merged_ordering = MetadataFactory::new_array<int>(1085klass->class_loader_data(), new_size, CHECK);1086}1087int method_order_index = klass->methods()->length();10881089sort_methods(new_methods);10901091// Perform grand merge of existing methods and new methods1092int orig_idx = 0;1093int new_idx = 0;10941095for (int i = 0; i < new_size; ++i) {1096Method* orig_method = NULL;1097Method* new_method = NULL;1098if (orig_idx < original_methods->length()) {1099orig_method = original_methods->at(orig_idx);1100}1101if (new_idx < new_methods->length()) {1102new_method = new_methods->at(new_idx);1103}11041105if (orig_method != NULL &&1106(new_method == NULL || orig_method->name() < new_method->name())) {1107merged_methods->at_put(i, orig_method);1108original_methods->at_put(orig_idx, NULL);1109if (merged_ordering->length() > 0) {1110assert(original_ordering != NULL && original_ordering->length() > 0,1111"should have original order information for this method");1112merged_ordering->at_put(i, original_ordering->at(orig_idx));1113}1114++orig_idx;1115} else {1116merged_methods->at_put(i, new_method);1117if (merged_ordering->length() > 0) {1118merged_ordering->at_put(i, method_order_index++);1119}1120++new_idx;1121}1122// update idnum for new location1123merged_methods->at(i)->set_method_idnum(i);1124merged_methods->at(i)->set_orig_method_idnum(i);1125}11261127// Verify correct order1128#ifdef ASSERT1129uintptr_t prev = 0;1130for (int i = 0; i < merged_methods->length(); ++i) {1131Method* mo = merged_methods->at(i);1132uintptr_t nv = (uintptr_t)mo->name();1133assert(nv >= prev, "Incorrect method ordering");1134prev = nv;1135}1136#endif11371138// Replace klass methods with new merged lists1139klass->set_methods(merged_methods);1140klass->set_initial_method_idnum(new_size);1141klass->set_method_ordering(merged_ordering);11421143// Free metadata1144ClassLoaderData* cld = klass->class_loader_data();1145if (original_methods->length() > 0) {1146MetadataFactory::free_array(cld, original_methods);1147}1148if (original_ordering != NULL && original_ordering->length() > 0) {1149MetadataFactory::free_array(cld, original_ordering);1150}1151}115211531154