1 /*
2  * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.
8  *
9  * This code is distributed in the hope that it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12  * version 2 for more details (a copy is included in the LICENSE file that
13  * accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License version
16  * 2 along with this work; if not, write to the Free Software Foundation,
17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18  *
19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20  * or visit www.oracle.com if you need additional information or have any
21  * questions.
22  *
23  */
24 
25 #include "precompiled.hpp"
26 #include "classfile/bytecodeAssembler.hpp"
27 #include "classfile/defaultMethods.hpp"
28 #include "classfile/symbolTable.hpp"
29 #include "classfile/systemDictionary.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"
50 
51 typedef enum { QUALIFIED, DISQUALIFIED } QualifiedState;
52 
print_slot(outputStream * str,Symbol * name,Symbol * signature)53 static void print_slot(outputStream* str, Symbol* name, Symbol* signature) {
54   str->print("%s%s", name->as_C_string(), signature->as_C_string());
55 }
56 
print_method(outputStream * str,Method * mo,bool with_class=true)57 static void print_method(outputStream* str, Method* mo, bool with_class=true) {
58   if (with_class) {
59     str->print("%s.", mo->klass_name()->as_C_string());
60   }
61   print_slot(str, mo->name(), mo->signature());
62 }
63 
64 /**
65  * Perform a depth-first iteration over the class hierarchy, applying
66  * 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 be
71  * paired with any algorithm class that provides the required methods.
72  *
73  * This class contains all the mechanics for iterating over the class hierarchy
74  * starting at a particular root, without recursing (thus limiting stack growth
75  * from this point).  It visits each superclass (if present) and superinterface
76  * in a depth-first manner, with callbacks to the ALGO class as each class is
77  * encountered (visit()), The algorithm can cut-off further exploration of a
78  * particular branch by returning 'false' from a visit() call.
79  *
80  * The ALGO class, must provide a visit() method, which each of which will be
81  * called once for each node in the inheritance tree during the iteration.  In
82  * addition, it can provide a memory block via new_node_data(), which it can
83  * use for node-specific storage (and access via the current_data() and
84  * 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  */
93 template <class ALGO>
94 class HierarchyVisitor : StackObj {
95  private:
96 
97   class Node : public ResourceObj {
98    public:
99     InstanceKlass* _class;
100     bool _super_was_visited;
101     int _interface_index;
102     void* _algorithm_data;
103 
Node(InstanceKlass * cls,void * data,bool visit_super)104     Node(InstanceKlass* cls, void* data, bool visit_super)
105         : _class(cls), _super_was_visited(!visit_super),
106           _interface_index(0), _algorithm_data(data) {}
107 
update(InstanceKlass * cls,void * data,bool visit_super)108     void 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     }
number_of_interfaces()114     int number_of_interfaces() { return _class->local_interfaces()->length(); }
interface_index()115     int interface_index() { return _interface_index; }
set_super_visited()116     void set_super_visited() { _super_was_visited = true; }
increment_visited_interface()117     void increment_visited_interface() { ++_interface_index; }
set_all_interfaces_visited()118     void set_all_interfaces_visited() {
119       _interface_index = number_of_interfaces();
120     }
has_visited_super()121     bool has_visited_super() { return _super_was_visited; }
has_visited_all_interfaces()122     bool has_visited_all_interfaces() {
123       return interface_index() >= number_of_interfaces();
124     }
interface_at(int index)125     InstanceKlass* interface_at(int index) {
126       return _class->local_interfaces()->at(index);
127     }
next_super()128     InstanceKlass* next_super() { return _class->java_super(); }
next_interface()129     InstanceKlass* next_interface() {
130       return interface_at(interface_index());
131     }
132   };
133 
134   bool _visited_Object;
135 
136   GrowableArray<Node*> _path;
137   GrowableArray<Node*> _free_nodes;
138 
current_top() const139   Node* current_top() const { return _path.top(); }
has_more_nodes() const140   bool has_more_nodes() const { return _path.length() > 0; }
push(InstanceKlass * cls,ALGO * algo)141   void push(InstanceKlass* cls, ALGO* algo) {
142     assert(cls != NULL, "Requires a valid instance class");
143     if (cls == SystemDictionary::Object_klass()) {
144       _visited_Object = true;
145     }
146     void* data = algo->new_node_data();
147     Node* node;
148     if (_free_nodes.is_empty()) { // Add a new node
149       node = new Node(cls, data, has_super(cls));
150     } else { // Reuse existing node and data
151       node = _free_nodes.pop();
152       node->update(cls, data, has_super(cls));
153     }
154     _path.push(node);
155   }
pop()156   void pop() {
157     Node* node = _path.pop();
158     // Make the node available for reuse
159     _free_nodes.push(node);
160   }
161 
162   // Since the starting point can be an interface, we must ensure we catch
163   // j.l.Object as the super once in those cases. The _visited_Object flag
164   // only ensures we don't then repeatedly enqueue Object for each interface
165   // in the class hierarchy.
has_super(InstanceKlass * cls)166   bool has_super(InstanceKlass* cls) {
167     return cls->super() != NULL && (!_visited_Object || !cls->is_interface());
168   }
169 
node_at_depth(int i) const170   Node* node_at_depth(int i) const {
171     return (i >= _path.length()) ? NULL : _path.at(_path.length() - i - 1);
172   }
173 
174  protected:
175 
176   // Resets the visitor
reset()177   void reset() {
178     _visited_Object = false;
179   }
180 
181   // Accessors available to the algorithm
current_depth() const182   int current_depth() const { return _path.length() - 1; }
183 
class_at_depth(int i)184   InstanceKlass* class_at_depth(int i) {
185     Node* n = node_at_depth(i);
186     return n == NULL ? NULL : n->_class;
187   }
current_class()188   InstanceKlass* current_class() { return class_at_depth(0); }
189 
data_at_depth(int i)190   void* data_at_depth(int i) {
191     Node* n = node_at_depth(i);
192     return n == NULL ? NULL : n->_algorithm_data;
193   }
current_data()194   void* current_data() { return data_at_depth(0); }
195 
196  public:
HierarchyVisitor()197   HierarchyVisitor() : _visited_Object(false), _path() {}
198 
run(InstanceKlass * root)199   void run(InstanceKlass* root) {
200     ALGO* algo = static_cast<ALGO*>(this);
201 
202     push(root, algo);
203     bool top_needs_visit = true;
204     do {
205       Node* top = current_top();
206       if (top_needs_visit) {
207         if (algo->visit() == false) {
208           // algorithm does not want to continue along this path.  Arrange
209           // it so that this state is immediately popped off the stack
210           top->set_super_visited();
211           top->set_all_interfaces_visited();
212         }
213         top_needs_visit = false;
214       }
215 
216       if (top->has_visited_super() && top->has_visited_all_interfaces()) {
217         algo->free_node_data(top->_algorithm_data);
218         pop();
219       } else {
220         InstanceKlass* next = NULL;
221         if (top->has_visited_super() == false) {
222           next = top->next_super();
223           top->set_super_visited();
224         } else {
225           next = top->next_interface();
226           top->increment_visited_interface();
227         }
228         assert(next != NULL, "Otherwise we shouldn't be here");
229         push(next, algo);
230         top_needs_visit = true;
231       }
232     } while (has_more_nodes());
233   }
234 };
235 
236 class PrintHierarchy : public HierarchyVisitor<PrintHierarchy> {
237  private:
238    outputStream* _st;
239  public:
visit()240   bool visit() {
241     InstanceKlass* cls = current_class();
242     streamIndentor si(_st, current_depth() * 2);
243     _st->indent().print_cr("%s", cls->name()->as_C_string());
244     return true;
245   }
246 
new_node_data()247   void* new_node_data() { return NULL; }
free_node_data(void * data)248   void free_node_data(void* data) { return; }
249 
PrintHierarchy(outputStream * st=tty)250   PrintHierarchy(outputStream* st = tty) : _st(st) {}
251 };
252 
253 // Used to register InstanceKlass objects and all related metadata structures
254 // (Methods, ConstantPools) as "in-use" by the current thread so that they can't
255 // be deallocated by class redefinition while we're using them.  The classes are
256 // de-registered when this goes out of scope.
257 //
258 // Once a class is registered, we need not bother with methodHandles or
259 // constantPoolHandles for it's associated metadata.
260 class KeepAliveRegistrar : public StackObj {
261  private:
262   Thread* _thread;
263   GrowableArray<ConstantPool*> _keep_alive;
264 
265  public:
KeepAliveRegistrar(Thread * thread)266   KeepAliveRegistrar(Thread* thread) : _thread(thread), _keep_alive(6) {
267     assert(thread == Thread::current(), "Must be current thread");
268   }
269 
~KeepAliveRegistrar()270   ~KeepAliveRegistrar() {
271     for (int i = _keep_alive.length() - 1; i >= 0; --i) {
272       ConstantPool* cp = _keep_alive.at(i);
273       int idx = _thread->metadata_handles()->find_from_end(cp);
274       assert(idx > 0, "Must be in the list");
275       _thread->metadata_handles()->remove_at(idx);
276     }
277   }
278 
279   // Register a class as 'in-use' by the thread.  It's fine to register a class
280   // multiple times (though perhaps inefficient)
register_class(InstanceKlass * ik)281   void register_class(InstanceKlass* ik) {
282     ConstantPool* cp = ik->constants();
283     _keep_alive.push(cp);
284     _thread->metadata_handles()->push(cp);
285   }
286 };
287 
288 class KeepAliveVisitor : public HierarchyVisitor<KeepAliveVisitor> {
289  private:
290   KeepAliveRegistrar* _registrar;
291 
292  public:
KeepAliveVisitor(KeepAliveRegistrar * registrar)293   KeepAliveVisitor(KeepAliveRegistrar* registrar) : _registrar(registrar) {}
294 
new_node_data()295   void* new_node_data() { return NULL; }
free_node_data(void * data)296   void free_node_data(void* data) { return; }
297 
visit()298   bool visit() {
299     _registrar->register_class(current_class());
300     return true;
301   }
302 };
303 
304 
305 // A method family contains a set of all methods that implement a single
306 // erased method. As members of the set are collected while walking over the
307 // hierarchy, they are tagged with a qualification state.  The qualification
308 // state for an erased method is set to disqualified if there exists a path
309 // from the root of hierarchy to the method that contains an interleaving
310 // erased method defined in an interface.
311 
312 class MethodState {
313  public:
314   Method* _method;
315   QualifiedState _state;
316 
MethodState()317   MethodState() : _method(NULL), _state(DISQUALIFIED) {}
MethodState(Method * method,QualifiedState state)318   MethodState(Method* method, QualifiedState state) : _method(method), _state(state) {}
319 };
320 
321 class MethodFamily : public ResourceObj {
322  private:
323 
324   GrowableArray<MethodState> _members;
325 
326   Method* _selected_target;  // Filled in later, if a unique target exists
327   Symbol* _exception_message; // If no unique target is found
328   Symbol* _exception_name;    // If no unique target is found
329 
find_method(Method * method)330   MethodState* find_method(Method* method) {
331     for (int i = 0; i < _members.length(); i++) {
332       if (_members.at(i)._method == method) {
333         return &_members.at(i);
334       }
335     }
336     return NULL;
337   }
338 
add_method(Method * method,QualifiedState state)339   void add_method(Method* method, QualifiedState state) {
340     MethodState method_state(method, state);
341     _members.append(method_state);
342   }
343 
344   Symbol* generate_no_defaults_message(TRAPS) const;
345   Symbol* generate_method_message(Symbol *klass_name, Method* method, TRAPS) const;
346   Symbol* generate_conflicts_message(GrowableArray<MethodState>* methods, TRAPS) const;
347 
348  public:
349 
MethodFamily()350   MethodFamily()
351       : _selected_target(NULL), _exception_message(NULL), _exception_name(NULL) {}
352 
set_target_if_empty(Method * m)353   void set_target_if_empty(Method* m) {
354     if (_selected_target == NULL && !m->is_overpass()) {
355       _selected_target = m;
356     }
357   }
358 
record_method(Method * m,QualifiedState state)359   void record_method(Method* m, QualifiedState state) {
360     // If not in the set, add it.  If it's already in the set, then leave it
361     // as is if state is qualified, or set it to disqualified if state is
362     // disqualified.
363     MethodState* method_state = find_method(m);
364     if (method_state == NULL) {
365       add_method(m, state);
366     } else if (state == DISQUALIFIED) {
367       method_state->_state = DISQUALIFIED;
368     }
369   }
370 
has_target() const371   bool has_target() const { return _selected_target != NULL; }
throws_exception()372   bool throws_exception() { return _exception_message != NULL; }
373 
get_selected_target()374   Method* get_selected_target() { return _selected_target; }
get_exception_message()375   Symbol* get_exception_message() { return _exception_message; }
get_exception_name()376   Symbol* get_exception_name() { return _exception_name; }
377 
378   // Either sets the target or the exception error message
determine_target_or_set_exception_message(InstanceKlass * root,TRAPS)379   void determine_target_or_set_exception_message(InstanceKlass* root, TRAPS) {
380     if (has_target() || throws_exception()) {
381       return;
382     }
383 
384     // Qualified methods are maximally-specific methods
385     // These include public, instance concrete (=default) and abstract methods
386     int num_defaults = 0;
387     int default_index = -1;
388     for (int i = 0; i < _members.length(); i++) {
389       MethodState &member = _members.at(i);
390       if (member._state == QUALIFIED) {
391         if (member._method->is_default_method()) {
392           num_defaults++;
393           default_index = i;
394         }
395       }
396     }
397 
398     if (num_defaults == 1) {
399       assert(_members.at(default_index)._state == QUALIFIED, "");
400       _selected_target = _members.at(default_index)._method;
401     } else {
402       generate_and_set_exception_message(root, num_defaults, default_index, CHECK);
403     }
404   }
405 
generate_and_set_exception_message(InstanceKlass * root,int num_defaults,int default_index,TRAPS)406   void generate_and_set_exception_message(InstanceKlass* root, int num_defaults, int default_index, TRAPS) {
407     assert(num_defaults != 1, "invariant - should've been handled calling method");
408 
409     GrowableArray<Method*> qualified_methods;
410     for (int i = 0; i < _members.length(); i++) {
411       MethodState& member = _members.at(i);
412       if (member._state == QUALIFIED) {
413         qualified_methods.push(member._method);
414       }
415     }
416     if (num_defaults == 0) {
417       // If the root klass has a static method with matching name and signature
418       // then do not generate an overpass method because it will hide the
419       // static method during resolution.
420       if (qualified_methods.length() == 0) {
421         _exception_message = generate_no_defaults_message(CHECK);
422       } else {
423         assert(root != NULL, "Null root class");
424         _exception_message = generate_method_message(root->name(), qualified_methods.at(0), CHECK);
425       }
426       _exception_name = vmSymbols::java_lang_AbstractMethodError();
427     } else {
428       _exception_message = generate_conflicts_message(&_members,CHECK);
429       _exception_name = vmSymbols::java_lang_IncompatibleClassChangeError();
430       LogTarget(Debug, defaultmethods) lt;
431       if (lt.is_enabled()) {
432         LogStream ls(lt);
433         _exception_message->print_value_on(&ls);
434         ls.cr();
435       }
436     }
437   }
438 
print_selected(outputStream * str,int indent) const439   void print_selected(outputStream* str, int indent) const {
440     assert(has_target(), "Should be called otherwise");
441     streamIndentor si(str, indent * 2);
442     str->indent().print("Selected method: ");
443     print_method(str, _selected_target);
444     Klass* method_holder = _selected_target->method_holder();
445     if (!method_holder->is_interface()) {
446       str->print(" : in superclass");
447     }
448     str->cr();
449   }
450 
print_exception(outputStream * str,int indent)451   void print_exception(outputStream* str, int indent) {
452     assert(throws_exception(), "Should be called otherwise");
453     assert(_exception_name != NULL, "exception_name should be set");
454     streamIndentor si(str, indent * 2);
455     str->indent().print_cr("%s: %s", _exception_name->as_C_string(), _exception_message->as_C_string());
456   }
457 };
458 
generate_no_defaults_message(TRAPS) const459 Symbol* MethodFamily::generate_no_defaults_message(TRAPS) const {
460   return SymbolTable::new_symbol("No qualifying defaults found");
461 }
462 
generate_method_message(Symbol * klass_name,Method * method,TRAPS) const463 Symbol* MethodFamily::generate_method_message(Symbol *klass_name, Method* method, TRAPS) const {
464   stringStream ss;
465   ss.print("Method ");
466   Symbol* name = method->name();
467   Symbol* signature = method->signature();
468   ss.write((const char*)klass_name->bytes(), klass_name->utf8_length());
469   ss.print(".");
470   ss.write((const char*)name->bytes(), name->utf8_length());
471   ss.write((const char*)signature->bytes(), signature->utf8_length());
472   ss.print(" is abstract");
473   return SymbolTable::new_symbol(ss.base(), (int)ss.size());
474 }
475 
generate_conflicts_message(GrowableArray<MethodState> * methods,TRAPS) const476 Symbol* MethodFamily::generate_conflicts_message(GrowableArray<MethodState>* methods, TRAPS) const {
477   stringStream ss;
478   ss.print("Conflicting default methods:");
479   for (int i = 0; i < methods->length(); ++i) {
480     Method *method = methods->at(i)._method;
481     Symbol *klass = method->klass_name();
482     Symbol *name = method->name();
483     ss.print(" ");
484     ss.write((const char*) klass->bytes(), klass->utf8_length());
485     ss.print(".");
486     ss.write((const char*) name->bytes(), name->utf8_length());
487   }
488   return SymbolTable::new_symbol(ss.base(), (int)ss.size());
489 }
490 
491 
492 class StateRestorerScope;
493 
494 // StatefulMethodFamily is a wrapper around a MethodFamily that maintains the
495 // qualification state during hierarchy visitation, and applies that state
496 // when adding members to the MethodFamily
497 class StatefulMethodFamily : public ResourceObj {
498   friend class StateRestorer;
499  private:
500   QualifiedState _qualification_state;
501 
set_qualification_state(QualifiedState state)502   void set_qualification_state(QualifiedState state) {
503     _qualification_state = state;
504   }
505 
506  protected:
507   MethodFamily _method_family;
508 
509  public:
StatefulMethodFamily()510   StatefulMethodFamily() {
511    _qualification_state = QUALIFIED;
512   }
513 
set_target_if_empty(Method * m)514   void set_target_if_empty(Method* m) { _method_family.set_target_if_empty(m); }
515 
get_method_family()516   MethodFamily* get_method_family() { return &_method_family; }
517 
518   void record_method_and_dq_further(StateRestorerScope* scope, Method* mo);
519 };
520 
521 // Because we use an iterative algorithm when iterating over the type
522 // hierarchy, we can't use traditional scoped objects which automatically do
523 // cleanup in the destructor when the scope is exited.  StateRestorerScope (and
524 // StateRestorer) provides a similar functionality, but for when you want a
525 // scoped object in non-stack memory (such as in resource memory, as we do
526 // here).  You've just got to remember to call 'restore_state()' on the scope when
527 // leaving it (and marks have to be explicitly added). The scope is reusable after
528 // 'restore_state()' has been called.
529 class StateRestorer : public ResourceObj {
530  public:
531   StatefulMethodFamily* _method;
532   QualifiedState _state_to_restore;
533 
StateRestorer()534   StateRestorer() : _method(NULL), _state_to_restore(DISQUALIFIED) {}
535 
restore_state()536   void restore_state() { _method->set_qualification_state(_state_to_restore); }
537 };
538 
539 class StateRestorerScope : public ResourceObj {
540  private:
541   GrowableArray<StateRestorer*>  _marks;
542   GrowableArray<StateRestorer*>* _free_list; // Shared between scopes
543  public:
StateRestorerScope(GrowableArray<StateRestorer * > * free_list)544   StateRestorerScope(GrowableArray<StateRestorer*>* free_list) : _marks(), _free_list(free_list) {}
545 
cast(void * data)546   static StateRestorerScope* cast(void* data) {
547     return static_cast<StateRestorerScope*>(data);
548   }
549 
mark(StatefulMethodFamily * family,QualifiedState qualification_state)550   void mark(StatefulMethodFamily* family, QualifiedState qualification_state) {
551     StateRestorer* restorer;
552     if (!_free_list->is_empty()) {
553       restorer = _free_list->pop();
554     } else {
555       restorer = new StateRestorer();
556     }
557     restorer->_method = family;
558     restorer->_state_to_restore = qualification_state;
559     _marks.append(restorer);
560   }
561 
562 #ifdef ASSERT
is_empty()563   bool is_empty() {
564     return _marks.is_empty();
565   }
566 #endif
567 
restore_state()568   void restore_state() {
569     while(!_marks.is_empty()) {
570       StateRestorer* restorer = _marks.pop();
571       restorer->restore_state();
572       _free_list->push(restorer);
573     }
574   }
575 };
576 
record_method_and_dq_further(StateRestorerScope * scope,Method * mo)577 void StatefulMethodFamily::record_method_and_dq_further(StateRestorerScope* scope, Method* mo) {
578   scope->mark(this, _qualification_state);
579   _method_family.record_method(mo, _qualification_state);
580 
581   // Everything found "above"??? this method in the hierarchy walk is set to
582   // disqualified
583   set_qualification_state(DISQUALIFIED);
584 }
585 
586 // Represents a location corresponding to a vtable slot for methods that
587 // neither the class nor any of it's ancestors provide an implementaion.
588 // Default methods may be present to fill this slot.
589 class EmptyVtableSlot : public ResourceObj {
590  private:
591   Symbol* _name;
592   Symbol* _signature;
593   int _size_of_parameters;
594   MethodFamily* _binding;
595 
596  public:
EmptyVtableSlot(Method * method)597   EmptyVtableSlot(Method* method)
598       : _name(method->name()), _signature(method->signature()),
599         _size_of_parameters(method->size_of_parameters()), _binding(NULL) {}
600 
name() const601   Symbol* name() const { return _name; }
signature() const602   Symbol* signature() const { return _signature; }
size_of_parameters() const603   int size_of_parameters() const { return _size_of_parameters; }
604 
bind_family(MethodFamily * lm)605   void bind_family(MethodFamily* lm) { _binding = lm; }
is_bound()606   bool is_bound() { return _binding != NULL; }
get_binding()607   MethodFamily* get_binding() { return _binding; }
608 
print_on(outputStream * str) const609   void print_on(outputStream* str) const {
610     print_slot(str, name(), signature());
611   }
612 };
613 
already_in_vtable_slots(GrowableArray<EmptyVtableSlot * > * slots,Method * m)614 static bool already_in_vtable_slots(GrowableArray<EmptyVtableSlot*>* slots, Method* m) {
615   bool found = false;
616   for (int j = 0; j < slots->length(); ++j) {
617     if (slots->at(j)->name() == m->name() &&
618         slots->at(j)->signature() == m->signature() ) {
619       found = true;
620       break;
621     }
622   }
623   return found;
624 }
625 
find_empty_vtable_slots(GrowableArray<EmptyVtableSlot * > * slots,InstanceKlass * klass,const GrowableArray<Method * > * mirandas,TRAPS)626 static void find_empty_vtable_slots(GrowableArray<EmptyVtableSlot*>* slots,
627     InstanceKlass* klass, const GrowableArray<Method*>* mirandas, TRAPS) {
628 
629   assert(klass != NULL, "Must be valid class");
630 
631   // All miranda methods are obvious candidates
632   for (int i = 0; i < mirandas->length(); ++i) {
633     Method* m = mirandas->at(i);
634     if (!already_in_vtable_slots(slots, m)) {
635       slots->append(new EmptyVtableSlot(m));
636     }
637   }
638 
639   // 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)
641   InstanceKlass* super = klass->java_super();
642   while (super != NULL) {
643     for (int i = 0; i < super->methods()->length(); ++i) {
644       Method* m = super->methods()->at(i);
645       if (m->is_overpass() || m->is_static()) {
646         // m is a method that would have been a miranda if not for the
647         // 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.
650         if (!already_in_vtable_slots(slots, m)) {
651           Method *impl = klass->lookup_method(m->name(), m->signature());
652           if (impl == NULL || impl->is_overpass() || impl->is_static()) {
653             slots->append(new EmptyVtableSlot(m));
654           }
655         }
656       }
657     }
658 
659     // also any default methods in our superclasses
660     if (super->default_methods() != NULL) {
661       for (int i = 0; i < super->default_methods()->length(); ++i) {
662         Method* m = super->default_methods()->at(i);
663         // m is a method that would have been a miranda if not for the
664         // 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.
667         if (!already_in_vtable_slots(slots, m)) {
668           Method* impl = klass->lookup_method(m->name(), m->signature());
669           if (impl == NULL || impl->is_overpass() || impl->is_static()) {
670             slots->append(new EmptyVtableSlot(m));
671           }
672         }
673       }
674     }
675     super = super->java_super();
676   }
677 
678   LogTarget(Debug, defaultmethods) lt;
679   if (lt.is_enabled()) {
680     lt.print("Slots that need filling:");
681     ResourceMark rm;
682     LogStream ls(lt);
683     streamIndentor si(&ls);
684     for (int i = 0; i < slots->length(); ++i) {
685       ls.indent();
686       slots->at(i)->print_on(&ls);
687       ls.cr();
688     }
689   }
690 }
691 
692 // Iterates over the superinterface type hierarchy looking for all methods
693 // with a specific erased signature.
694 class FindMethodsByErasedSig : public HierarchyVisitor<FindMethodsByErasedSig> {
695  private:
696   // Context data
697   Symbol* _method_name;
698   Symbol* _method_signature;
699   StatefulMethodFamily*  _family;
700   bool _cur_class_is_interface;
701   // Free lists, used as an optimization
702   GrowableArray<StateRestorerScope*> _free_scopes;
703   GrowableArray<StateRestorer*> _free_restorers;
704  public:
FindMethodsByErasedSig()705   FindMethodsByErasedSig() : _free_scopes(6), _free_restorers(6) {};
706 
prepare(Symbol * name,Symbol * signature,bool is_interf)707   void prepare(Symbol* name, Symbol* signature, bool is_interf) {
708     reset();
709     _method_name = name;
710     _method_signature = signature;
711     _family = NULL;
712     _cur_class_is_interface = is_interf;
713   }
714 
get_discovered_family(MethodFamily ** family)715   void get_discovered_family(MethodFamily** family) {
716       if (_family != NULL) {
717         *family = _family->get_method_family();
718       } else {
719         *family = NULL;
720       }
721   }
722 
new_node_data()723   void* new_node_data() {
724     if (!_free_scopes.is_empty()) {
725       StateRestorerScope* free_scope = _free_scopes.pop();
726       assert(free_scope->is_empty(), "StateRestorerScope::_marks array not empty");
727       return free_scope;
728     }
729     return new StateRestorerScope(&_free_restorers);
730   }
free_node_data(void * node_data)731   void free_node_data(void* node_data) {
732     StateRestorerScope* scope =  StateRestorerScope::cast(node_data);
733     scope->restore_state();
734     // Reuse scopes
735     _free_scopes.push(scope);
736   }
737 
738   // Find all methods on this hierarchy that match this
739   // method's erased (name, signature)
visit()740   bool visit() {
741     StateRestorerScope* scope = StateRestorerScope::cast(current_data());
742     InstanceKlass* iklass = current_class();
743 
744     Method* 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 perform
749     // 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 default
752     // methods.
753     // Future: take access controls into account for superclass methods
754     if (m != NULL && !m->is_static() && !m->is_overpass() && !m->is_private() &&
755      (!_cur_class_is_interface || !SystemDictionary::is_nonpublic_Object_method(m))) {
756       if (_family == NULL) {
757         _family = new StatefulMethodFamily();
758       }
759 
760       if (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) over
764         // methods in interfaces. This works because of single inheritance.
765         // Private methods in classes do not "win", they will be found
766         // first on searching, but overriding for invokevirtual needs
767         // to find default method candidates for the same signature
768         _family->set_target_if_empty(m);
769       }
770     }
771     return true;
772   }
773 
774 };
775 
776 
777 
778 static void create_defaults_and_exceptions(
779     GrowableArray<EmptyVtableSlot*>* slots, InstanceKlass* klass, TRAPS);
780 
generate_erased_defaults(FindMethodsByErasedSig * visitor,InstanceKlass * klass,EmptyVtableSlot * slot,bool is_intf,TRAPS)781 static void generate_erased_defaults(
782     FindMethodsByErasedSig* visitor,
783     InstanceKlass* klass, EmptyVtableSlot* slot, bool is_intf, TRAPS) {
784 
785   // the visitor needs to be initialized or re-initialized before use
786   // - this facilitates reusing the same visitor instance on multiple
787   // generation passes as an optimization
788   visitor->prepare(slot->name(), slot->signature(), is_intf);
789   // sets up a set of methods with the same exact erased signature
790   visitor->run(klass);
791 
792   MethodFamily* family;
793   visitor->get_discovered_family(&family);
794   if (family != NULL) {
795     family->determine_target_or_set_exception_message(klass, CHECK);
796     slot->bind_family(family);
797   }
798 }
799 
800 static void merge_in_new_methods(InstanceKlass* klass,
801     GrowableArray<Method*>* new_methods, TRAPS);
802 static void create_default_methods( InstanceKlass* klass,
803     GrowableArray<Method*>* new_methods, TRAPS);
804 
805 // This is the guts of the default methods implementation.  This is called just
806 // 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 (either
809 // because they are miranda or a superclass's implementation is an overpass
810 // itself).  For each slot, iterate over the hierarchy, to see if they contain a
811 // signature that matches the slot we are looking at.
812 //
813 // For each slot filled, we either record the default method candidate in the
814 // klass default_methods list or, only to handle exception cases, we create an
815 // 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.
generate_default_methods(InstanceKlass * klass,const GrowableArray<Method * > * mirandas,TRAPS)817 void DefaultMethods::generate_default_methods(
818     InstanceKlass* klass, const GrowableArray<Method*>* mirandas, TRAPS) {
819   assert(klass != NULL, "invariant");
820   assert(klass != SystemDictionary::Object_klass(), "Shouldn't be called for Object");
821 
822   // This resource mark is the bound for all memory allocation that takes
823   // place during default method processing.  After this goes out of scope,
824   // all (Resource) objects' memory will be reclaimed.  Be careful if adding an
825   // embedded resource mark under here as that memory can't be used outside
826   // whatever scope it's in.
827   ResourceMark rm(THREAD);
828 
829   // Keep entire hierarchy alive for the duration of the computation
830   constantPoolHandle cp(THREAD, klass->constants());
831   KeepAliveRegistrar keepAlive(THREAD);
832   KeepAliveVisitor loadKeepAlive(&keepAlive);
833   loadKeepAlive.run(klass);
834 
835   LogTarget(Debug, defaultmethods) lt;
836   if (lt.is_enabled()) {
837     ResourceMark rm;
838     lt.print("%s %s requires default method processing",
839              klass->is_interface() ? "Interface" : "Class",
840              klass->name()->as_klass_external_name());
841     LogStream ls(lt);
842     PrintHierarchy printer(&ls);
843     printer.run(klass);
844   }
845 
846   GrowableArray<EmptyVtableSlot*> empty_slots;
847   find_empty_vtable_slots(&empty_slots, klass, mirandas, CHECK);
848 
849   if (empty_slots.length() > 0) {
850     FindMethodsByErasedSig findMethodsByErasedSig;
851     for (int i = 0; i < empty_slots.length(); ++i) {
852       EmptyVtableSlot* slot = empty_slots.at(i);
853       LogTarget(Debug, defaultmethods) lt;
854       if (lt.is_enabled()) {
855         LogStream ls(lt);
856         streamIndentor si(&ls, 2);
857         ls.indent().print("Looking for default methods for slot ");
858         slot->print_on(&ls);
859         ls.cr();
860       }
861       generate_erased_defaults(&findMethodsByErasedSig, klass, slot, klass->is_interface(), CHECK);
862     }
863     log_debug(defaultmethods)("Creating defaults and overpasses...");
864     create_defaults_and_exceptions(&empty_slots, klass, CHECK);
865   }
866   log_debug(defaultmethods)("Default method processing complete");
867 }
868 
assemble_method_error(BytecodeConstantPool * cp,BytecodeBuffer * buffer,Symbol * errorName,Symbol * message,TRAPS)869 static int assemble_method_error(
870     BytecodeConstantPool* cp, BytecodeBuffer* buffer, Symbol* errorName, Symbol* message, TRAPS) {
871 
872   Symbol* init = vmSymbols::object_initializer_name();
873   Symbol* sig = vmSymbols::string_void_signature();
874 
875   BytecodeAssembler assem(buffer, cp);
876 
877   assem._new(errorName);
878   assem.dup();
879   assem.load_string(message);
880   assem.invokespecial(errorName, init, sig);
881   assem.athrow();
882 
883   return 3; // max stack size: [ exception, exception, string ]
884 }
885 
new_method(BytecodeConstantPool * cp,BytecodeBuffer * bytecodes,Symbol * name,Symbol * sig,AccessFlags flags,int max_stack,int params,ConstMethod::MethodType mt,TRAPS)886 static Method* new_method(
887     BytecodeConstantPool* cp, BytecodeBuffer* bytecodes, Symbol* name,
888     Symbol* sig, AccessFlags flags, int max_stack, int params,
889     ConstMethod::MethodType mt, TRAPS) {
890 
891   address code_start = 0;
892   int code_length = 0;
893   InlineTableSizes sizes;
894 
895   if (bytecodes != NULL && bytecodes->length() > 0) {
896     code_start = static_cast<address>(bytecodes->adr_at(0));
897     code_length = bytecodes->length();
898   }
899 
900   Method* m = Method::allocate(cp->pool_holder()->class_loader_data(),
901                                code_length, flags, &sizes,
902                                mt, CHECK_NULL);
903 
904   m->set_constants(NULL); // This will get filled in later
905   m->set_name_index(cp->utf8(name));
906   m->set_signature_index(cp->utf8(sig));
907   m->compute_from_signature(sig);
908   m->set_size_of_parameters(params);
909   m->set_max_stack(max_stack);
910   m->set_max_locals(params);
911   m->constMethod()->set_stackmap_data(NULL);
912   m->set_code(code_start);
913 
914   return m;
915 }
916 
switchover_constant_pool(BytecodeConstantPool * bpool,InstanceKlass * klass,GrowableArray<Method * > * new_methods,TRAPS)917 static void switchover_constant_pool(BytecodeConstantPool* bpool,
918     InstanceKlass* klass, GrowableArray<Method*>* new_methods, TRAPS) {
919 
920   if (new_methods->length() > 0) {
921     ConstantPool* cp = bpool->create_constant_pool(CHECK);
922     if (cp != klass->constants()) {
923       // Copy resolved anonymous class into new constant pool.
924       if (klass->is_unsafe_anonymous() || klass->is_hidden()) {
925         cp->klass_at_put(klass->this_class_index(), klass);
926       }
927       klass->class_loader_data()->add_to_deallocate_list(klass->constants());
928       klass->set_constants(cp);
929       cp->set_pool_holder(klass);
930 
931       for (int i = 0; i < new_methods->length(); ++i) {
932         new_methods->at(i)->set_constants(cp);
933       }
934       for (int i = 0; i < klass->methods()->length(); ++i) {
935         Method* mo = klass->methods()->at(i);
936         mo->set_constants(cp);
937       }
938     }
939   }
940 }
941 
942 // Create default_methods list for the current class.
943 // With the VM only processing erased signatures, the VM only
944 // creates an overpass in a conflict case or a case with no candidates.
945 // This allows virtual methods to override the overpass, but ensures
946 // that a local method search will find the exception rather than an abstract
947 // or default method that is not a valid candidate.
948 //
949 // Note that if overpass method are ever created that are not exception
950 // throwing methods then the loader constraint checking logic for vtable and
951 // itable creation needs to be changed to check loader constraints for the
952 // overpass methods that do not throw exceptions.
create_defaults_and_exceptions(GrowableArray<EmptyVtableSlot * > * slots,InstanceKlass * klass,TRAPS)953 static void create_defaults_and_exceptions(GrowableArray<EmptyVtableSlot*>* slots,
954     InstanceKlass* klass, TRAPS) {
955 
956   GrowableArray<Method*> overpasses;
957   GrowableArray<Method*> defaults;
958   BytecodeConstantPool bpool(klass->constants());
959 
960   BytecodeBuffer* buffer = NULL; // Lazily create a reusable buffer
961   for (int i = 0; i < slots->length(); ++i) {
962     EmptyVtableSlot* slot = slots->at(i);
963 
964     if (slot->is_bound()) {
965       MethodFamily* method = slot->get_binding();
966 
967       LogTarget(Debug, defaultmethods) lt;
968       if (lt.is_enabled()) {
969         ResourceMark rm(THREAD);
970         LogStream ls(lt);
971         ls.print("for slot: ");
972         slot->print_on(&ls);
973         ls.cr();
974         if (method->has_target()) {
975           method->print_selected(&ls, 1);
976         } else if (method->throws_exception()) {
977           method->print_exception(&ls, 1);
978         }
979       }
980 
981       if (method->has_target()) {
982         Method* selected = method->get_selected_target();
983         if (selected->method_holder()->is_interface()) {
984           assert(!selected->is_private(), "pushing private interface method as default");
985           defaults.push(selected);
986         }
987       } else if (method->throws_exception()) {
988         if (buffer == NULL) {
989           buffer = new BytecodeBuffer();
990         } else {
991           buffer->clear();
992         }
993         int max_stack = assemble_method_error(&bpool, buffer,
994            method->get_exception_name(), method->get_exception_message(), CHECK);
995         AccessFlags flags = accessFlags_from(
996           JVM_ACC_PUBLIC | JVM_ACC_SYNTHETIC | JVM_ACC_BRIDGE);
997         Method* m = new_method(&bpool, buffer, slot->name(), slot->signature(),
998           flags, max_stack, slot->size_of_parameters(),
999           ConstMethod::OVERPASS, CHECK);
1000         // We push to the methods list:
1001         // overpass methods which are exception throwing methods
1002         if (m != NULL) {
1003           overpasses.push(m);
1004         }
1005       }
1006     }
1007   }
1008 
1009 
1010   log_debug(defaultmethods)("Created %d overpass methods", overpasses.length());
1011   log_debug(defaultmethods)("Created %d default  methods", defaults.length());
1012 
1013   if (overpasses.length() > 0) {
1014     switchover_constant_pool(&bpool, klass, &overpasses, CHECK);
1015     merge_in_new_methods(klass, &overpasses, CHECK);
1016   }
1017   if (defaults.length() > 0) {
1018     create_default_methods(klass, &defaults, CHECK);
1019   }
1020 }
1021 
create_default_methods(InstanceKlass * klass,GrowableArray<Method * > * new_methods,TRAPS)1022 static void create_default_methods(InstanceKlass* klass,
1023     GrowableArray<Method*>* new_methods, TRAPS) {
1024 
1025   int new_size = new_methods->length();
1026   Array<Method*>* total_default_methods = MetadataFactory::new_array<Method*>(
1027       klass->class_loader_data(), new_size, NULL, CHECK);
1028   for (int index = 0; index < new_size; index++ ) {
1029     total_default_methods->at_put(index, new_methods->at(index));
1030   }
1031   Method::sort_methods(total_default_methods, /*set_idnums=*/false);
1032 
1033   klass->set_default_methods(total_default_methods);
1034 }
1035 
sort_methods(GrowableArray<Method * > * methods)1036 static void sort_methods(GrowableArray<Method*>* methods) {
1037   // Note that this must sort using the same key as is used for sorting
1038   // methods in InstanceKlass.
1039   bool sorted = true;
1040   for (int i = methods->length() - 1; i > 0; --i) {
1041     for (int j = 0; j < i; ++j) {
1042       Method* m1 = methods->at(j);
1043       Method* m2 = methods->at(j + 1);
1044       if ((uintptr_t)m1->name() > (uintptr_t)m2->name()) {
1045         methods->at_put(j, m2);
1046         methods->at_put(j + 1, m1);
1047         sorted = false;
1048       }
1049     }
1050     if (sorted) break;
1051     sorted = true;
1052   }
1053 #ifdef ASSERT
1054   uintptr_t prev = 0;
1055   for (int i = 0; i < methods->length(); ++i) {
1056     Method* mh = methods->at(i);
1057     uintptr_t nv = (uintptr_t)mh->name();
1058     assert(nv >= prev, "Incorrect overpass method ordering");
1059     prev = nv;
1060   }
1061 #endif
1062 }
1063 
merge_in_new_methods(InstanceKlass * klass,GrowableArray<Method * > * new_methods,TRAPS)1064 static void merge_in_new_methods(InstanceKlass* klass,
1065     GrowableArray<Method*>* new_methods, TRAPS) {
1066 
1067   enum { ANNOTATIONS, PARAMETERS, DEFAULTS, NUM_ARRAYS };
1068 
1069   Array<Method*>* original_methods = klass->methods();
1070   Array<int>* original_ordering = klass->method_ordering();
1071   Array<int>* merged_ordering = Universe::the_empty_int_array();
1072 
1073   int new_size = klass->methods()->length() + new_methods->length();
1074 
1075   Array<Method*>* merged_methods = MetadataFactory::new_array<Method*>(
1076       klass->class_loader_data(), new_size, NULL, CHECK);
1077 
1078   // original_ordering might be empty if this class has no methods of its own
1079   if (JvmtiExport::can_maintain_original_method_order() || Arguments::is_dumping_archive()) {
1080     merged_ordering = MetadataFactory::new_array<int>(
1081         klass->class_loader_data(), new_size, CHECK);
1082   }
1083   int method_order_index = klass->methods()->length();
1084 
1085   sort_methods(new_methods);
1086 
1087   // Perform grand merge of existing methods and new methods
1088   int orig_idx = 0;
1089   int new_idx = 0;
1090 
1091   for (int i = 0; i < new_size; ++i) {
1092     Method* orig_method = NULL;
1093     Method* new_method = NULL;
1094     if (orig_idx < original_methods->length()) {
1095       orig_method = original_methods->at(orig_idx);
1096     }
1097     if (new_idx < new_methods->length()) {
1098       new_method = new_methods->at(new_idx);
1099     }
1100 
1101     if (orig_method != NULL &&
1102         (new_method == NULL || orig_method->name() < new_method->name())) {
1103       merged_methods->at_put(i, orig_method);
1104       original_methods->at_put(orig_idx, NULL);
1105       if (merged_ordering->length() > 0) {
1106         assert(original_ordering != NULL && original_ordering->length() > 0,
1107                "should have original order information for this method");
1108         merged_ordering->at_put(i, original_ordering->at(orig_idx));
1109       }
1110       ++orig_idx;
1111     } else {
1112       merged_methods->at_put(i, new_method);
1113       if (merged_ordering->length() > 0) {
1114         merged_ordering->at_put(i, method_order_index++);
1115       }
1116       ++new_idx;
1117     }
1118     // update idnum for new location
1119     merged_methods->at(i)->set_method_idnum(i);
1120     merged_methods->at(i)->set_orig_method_idnum(i);
1121   }
1122 
1123   // Verify correct order
1124 #ifdef ASSERT
1125   uintptr_t prev = 0;
1126   for (int i = 0; i < merged_methods->length(); ++i) {
1127     Method* mo = merged_methods->at(i);
1128     uintptr_t nv = (uintptr_t)mo->name();
1129     assert(nv >= prev, "Incorrect method ordering");
1130     prev = nv;
1131   }
1132 #endif
1133 
1134   // Replace klass methods with new merged lists
1135   klass->set_methods(merged_methods);
1136   klass->set_initial_method_idnum(new_size);
1137   klass->set_method_ordering(merged_ordering);
1138 
1139   // Free metadata
1140   ClassLoaderData* cld = klass->class_loader_data();
1141   if (original_methods->length() > 0) {
1142     MetadataFactory::free_array(cld, original_methods);
1143   }
1144   if (original_ordering != NULL && original_ordering->length() > 0) {
1145     MetadataFactory::free_array(cld, original_ordering);
1146   }
1147 }
1148