Thu, 19 Dec 2013 20:28:45 +0000
8030633: nsk/jvmti/RedefineClasses/StressRedefine failed invalid method ordering length on Solaris
Summary: A method with no declared methods was getting an AME overpass method with the latest change. The method_ordering array was not updated for the new methods.
Reviewed-by: dcubed, acorn, dsamersoff, lfoltan, hseigel
1 /*
2 * Copyright (c) 2012, 2013, 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 */
25 #include "precompiled.hpp"
26 #include "classfile/bytecodeAssembler.hpp"
27 #include "classfile/defaultMethods.hpp"
28 #include "classfile/symbolTable.hpp"
29 #include "memory/allocation.hpp"
30 #include "memory/metadataFactory.hpp"
31 #include "memory/resourceArea.hpp"
32 #include "runtime/signature.hpp"
33 #include "runtime/thread.hpp"
34 #include "oops/instanceKlass.hpp"
35 #include "oops/klass.hpp"
36 #include "oops/method.hpp"
37 #include "utilities/accessFlags.hpp"
38 #include "utilities/exceptions.hpp"
39 #include "utilities/ostream.hpp"
40 #include "utilities/pair.hpp"
41 #include "utilities/resourceHash.hpp"
43 typedef enum { QUALIFIED, DISQUALIFIED } QualifiedState;
45 // Because we use an iterative algorithm when iterating over the type
46 // hierarchy, we can't use traditional scoped objects which automatically do
47 // cleanup in the destructor when the scope is exited. PseudoScope (and
48 // PseudoScopeMark) provides a similar functionality, but for when you want a
49 // scoped object in non-stack memory (such as in resource memory, as we do
50 // here). You've just got to remember to call 'destroy()' on the scope when
51 // leaving it (and marks have to be explicitly added).
52 class PseudoScopeMark : public ResourceObj {
53 public:
54 virtual void destroy() = 0;
55 };
57 class PseudoScope : public ResourceObj {
58 private:
59 GrowableArray<PseudoScopeMark*> _marks;
60 public:
62 static PseudoScope* cast(void* data) {
63 return static_cast<PseudoScope*>(data);
64 }
66 void add_mark(PseudoScopeMark* psm) {
67 _marks.append(psm);
68 }
70 void destroy() {
71 for (int i = 0; i < _marks.length(); ++i) {
72 _marks.at(i)->destroy();
73 }
74 }
75 };
77 #ifndef PRODUCT
78 static void print_slot(outputStream* str, Symbol* name, Symbol* signature) {
79 ResourceMark rm;
80 str->print("%s%s", name->as_C_string(), signature->as_C_string());
81 }
83 static void print_method(outputStream* str, Method* mo, bool with_class=true) {
84 ResourceMark rm;
85 if (with_class) {
86 str->print("%s.", mo->klass_name()->as_C_string());
87 }
88 print_slot(str, mo->name(), mo->signature());
89 }
90 #endif // ndef PRODUCT
92 /**
93 * Perform a depth-first iteration over the class hierarchy, applying
94 * algorithmic logic as it goes.
95 *
96 * This class is one half of the inheritance hierarchy analysis mechanism.
97 * It is meant to be used in conjunction with another class, the algorithm,
98 * which is indicated by the ALGO template parameter. This class can be
99 * paired with any algorithm class that provides the required methods.
100 *
101 * This class contains all the mechanics for iterating over the class hierarchy
102 * starting at a particular root, without recursing (thus limiting stack growth
103 * from this point). It visits each superclass (if present) and superinterface
104 * in a depth-first manner, with callbacks to the ALGO class as each class is
105 * encountered (visit()), The algorithm can cut-off further exploration of a
106 * particular branch by returning 'false' from a visit() call.
107 *
108 * The ALGO class, must provide a visit() method, which each of which will be
109 * called once for each node in the inheritance tree during the iteration. In
110 * addition, it can provide a memory block via new_node_data(InstanceKlass*),
111 * which it can use for node-specific storage (and access via the
112 * current_data() and data_at_depth(int) methods).
113 *
114 * Bare minimum needed to be an ALGO class:
115 * class Algo : public HierarchyVisitor<Algo> {
116 * void* new_node_data(InstanceKlass* cls) { return NULL; }
117 * void free_node_data(void* data) { return; }
118 * bool visit() { return true; }
119 * };
120 */
121 template <class ALGO>
122 class HierarchyVisitor : StackObj {
123 private:
125 class Node : public ResourceObj {
126 public:
127 InstanceKlass* _class;
128 bool _super_was_visited;
129 int _interface_index;
130 void* _algorithm_data;
132 Node(InstanceKlass* cls, void* data, bool visit_super)
133 : _class(cls), _super_was_visited(!visit_super),
134 _interface_index(0), _algorithm_data(data) {}
136 int number_of_interfaces() { return _class->local_interfaces()->length(); }
137 int interface_index() { return _interface_index; }
138 void set_super_visited() { _super_was_visited = true; }
139 void increment_visited_interface() { ++_interface_index; }
140 void set_all_interfaces_visited() {
141 _interface_index = number_of_interfaces();
142 }
143 bool has_visited_super() { return _super_was_visited; }
144 bool has_visited_all_interfaces() {
145 return interface_index() >= number_of_interfaces();
146 }
147 InstanceKlass* interface_at(int index) {
148 return InstanceKlass::cast(_class->local_interfaces()->at(index));
149 }
150 InstanceKlass* next_super() { return _class->java_super(); }
151 InstanceKlass* next_interface() {
152 return interface_at(interface_index());
153 }
154 };
156 bool _cancelled;
157 GrowableArray<Node*> _path;
159 Node* current_top() const { return _path.top(); }
160 bool has_more_nodes() const { return !_path.is_empty(); }
161 void push(InstanceKlass* cls, void* data) {
162 assert(cls != NULL, "Requires a valid instance class");
163 Node* node = new Node(cls, data, has_super(cls));
164 _path.push(node);
165 }
166 void pop() { _path.pop(); }
168 void reset_iteration() {
169 _cancelled = false;
170 _path.clear();
171 }
172 bool is_cancelled() const { return _cancelled; }
174 // This code used to skip interface classes because their only
175 // superclass was j.l.Object which would be also covered by class
176 // superclass hierarchy walks. Now that the starting point can be
177 // an interface, we must ensure we catch j.l.Object as the super.
178 static bool has_super(InstanceKlass* cls) {
179 return cls->super() != NULL;
180 }
182 Node* node_at_depth(int i) const {
183 return (i >= _path.length()) ? NULL : _path.at(_path.length() - i - 1);
184 }
186 protected:
188 // Accessors available to the algorithm
189 int current_depth() const { return _path.length() - 1; }
191 InstanceKlass* class_at_depth(int i) {
192 Node* n = node_at_depth(i);
193 return n == NULL ? NULL : n->_class;
194 }
195 InstanceKlass* current_class() { return class_at_depth(0); }
197 void* data_at_depth(int i) {
198 Node* n = node_at_depth(i);
199 return n == NULL ? NULL : n->_algorithm_data;
200 }
201 void* current_data() { return data_at_depth(0); }
203 void cancel_iteration() { _cancelled = true; }
205 public:
207 void run(InstanceKlass* root) {
208 ALGO* algo = static_cast<ALGO*>(this);
210 reset_iteration();
212 void* algo_data = algo->new_node_data(root);
213 push(root, algo_data);
214 bool top_needs_visit = true;
216 do {
217 Node* top = current_top();
218 if (top_needs_visit) {
219 if (algo->visit() == false) {
220 // algorithm does not want to continue along this path. Arrange
221 // it so that this state is immediately popped off the stack
222 top->set_super_visited();
223 top->set_all_interfaces_visited();
224 }
225 top_needs_visit = false;
226 }
228 if (top->has_visited_super() && top->has_visited_all_interfaces()) {
229 algo->free_node_data(top->_algorithm_data);
230 pop();
231 } else {
232 InstanceKlass* next = NULL;
233 if (top->has_visited_super() == false) {
234 next = top->next_super();
235 top->set_super_visited();
236 } else {
237 next = top->next_interface();
238 top->increment_visited_interface();
239 }
240 assert(next != NULL, "Otherwise we shouldn't be here");
241 algo_data = algo->new_node_data(next);
242 push(next, algo_data);
243 top_needs_visit = true;
244 }
245 } while (!is_cancelled() && has_more_nodes());
246 }
247 };
249 #ifndef PRODUCT
250 class PrintHierarchy : public HierarchyVisitor<PrintHierarchy> {
251 public:
253 bool visit() {
254 InstanceKlass* cls = current_class();
255 streamIndentor si(tty, current_depth() * 2);
256 tty->indent().print_cr("%s", cls->name()->as_C_string());
257 return true;
258 }
260 void* new_node_data(InstanceKlass* cls) { return NULL; }
261 void free_node_data(void* data) { return; }
262 };
263 #endif // ndef PRODUCT
265 // Used to register InstanceKlass objects and all related metadata structures
266 // (Methods, ConstantPools) as "in-use" by the current thread so that they can't
267 // be deallocated by class redefinition while we're using them. The classes are
268 // de-registered when this goes out of scope.
269 //
270 // Once a class is registered, we need not bother with methodHandles or
271 // constantPoolHandles for it's associated metadata.
272 class KeepAliveRegistrar : public StackObj {
273 private:
274 Thread* _thread;
275 GrowableArray<ConstantPool*> _keep_alive;
277 public:
278 KeepAliveRegistrar(Thread* thread) : _thread(thread), _keep_alive(20) {
279 assert(thread == Thread::current(), "Must be current thread");
280 }
282 ~KeepAliveRegistrar() {
283 for (int i = _keep_alive.length() - 1; i >= 0; --i) {
284 ConstantPool* cp = _keep_alive.at(i);
285 int idx = _thread->metadata_handles()->find_from_end(cp);
286 assert(idx > 0, "Must be in the list");
287 _thread->metadata_handles()->remove_at(idx);
288 }
289 }
291 // Register a class as 'in-use' by the thread. It's fine to register a class
292 // multiple times (though perhaps inefficient)
293 void register_class(InstanceKlass* ik) {
294 ConstantPool* cp = ik->constants();
295 _keep_alive.push(cp);
296 _thread->metadata_handles()->push(cp);
297 }
298 };
300 class KeepAliveVisitor : public HierarchyVisitor<KeepAliveVisitor> {
301 private:
302 KeepAliveRegistrar* _registrar;
304 public:
305 KeepAliveVisitor(KeepAliveRegistrar* registrar) : _registrar(registrar) {}
307 void* new_node_data(InstanceKlass* cls) { return NULL; }
308 void free_node_data(void* data) { return; }
310 bool visit() {
311 _registrar->register_class(current_class());
312 return true;
313 }
314 };
317 // A method family contains a set of all methods that implement a single
318 // erased method. As members of the set are collected while walking over the
319 // hierarchy, they are tagged with a qualification state. The qualification
320 // state for an erased method is set to disqualified if there exists a path
321 // from the root of hierarchy to the method that contains an interleaving
322 // erased method defined in an interface.
324 class MethodFamily : public ResourceObj {
325 private:
327 GrowableArray<Pair<Method*,QualifiedState> > _members;
328 ResourceHashtable<Method*, int> _member_index;
330 Method* _selected_target; // Filled in later, if a unique target exists
331 Symbol* _exception_message; // If no unique target is found
332 Symbol* _exception_name; // If no unique target is found
334 bool contains_method(Method* method) {
335 int* lookup = _member_index.get(method);
336 return lookup != NULL;
337 }
339 void add_method(Method* method, QualifiedState state) {
340 Pair<Method*,QualifiedState> entry(method, state);
341 _member_index.put(method, _members.length());
342 _members.append(entry);
343 }
345 void disqualify_method(Method* method) {
346 int* index = _member_index.get(method);
347 guarantee(index != NULL && *index >= 0 && *index < _members.length(), "bad index");
348 _members.at(*index).second = DISQUALIFIED;
349 }
351 Symbol* generate_no_defaults_message(TRAPS) const;
352 Symbol* generate_method_message(Symbol *klass_name, Method* method, TRAPS) const;
353 Symbol* generate_conflicts_message(GrowableArray<Method*>* methods, TRAPS) const;
355 public:
357 MethodFamily()
358 : _selected_target(NULL), _exception_message(NULL), _exception_name(NULL) {}
360 void set_target_if_empty(Method* m) {
361 if (_selected_target == NULL && !m->is_overpass()) {
362 _selected_target = m;
363 }
364 }
366 void record_qualified_method(Method* m) {
367 // If the method already exists in the set as qualified, this operation is
368 // redundant. If it already exists as disqualified, then we leave it as
369 // disqualfied. Thus we only add to the set if it's not already in the
370 // set.
371 if (!contains_method(m)) {
372 add_method(m, QUALIFIED);
373 }
374 }
376 void record_disqualified_method(Method* m) {
377 // If not in the set, add it as disqualified. If it's already in the set,
378 // then set the state to disqualified no matter what the previous state was.
379 if (!contains_method(m)) {
380 add_method(m, DISQUALIFIED);
381 } else {
382 disqualify_method(m);
383 }
384 }
386 bool has_target() const { return _selected_target != NULL; }
387 bool throws_exception() { return _exception_message != NULL; }
389 Method* get_selected_target() { return _selected_target; }
390 Symbol* get_exception_message() { return _exception_message; }
391 Symbol* get_exception_name() { return _exception_name; }
393 // Either sets the target or the exception error message
394 void determine_target(InstanceKlass* root, TRAPS) {
395 if (has_target() || throws_exception()) {
396 return;
397 }
399 // Qualified methods are maximally-specific methods
400 // These include public, instance concrete (=default) and abstract methods
401 GrowableArray<Method*> qualified_methods;
402 int num_defaults = 0;
403 int default_index = -1;
404 int qualified_index = -1;
405 for (int i = 0; i < _members.length(); ++i) {
406 Pair<Method*,QualifiedState> entry = _members.at(i);
407 if (entry.second == QUALIFIED) {
408 qualified_methods.append(entry.first);
409 qualified_index++;
410 if (entry.first->is_default_method()) {
411 num_defaults++;
412 default_index = qualified_index;
414 }
415 }
416 }
418 if (num_defaults == 0) {
419 if (qualified_methods.length() == 0) {
420 _exception_message = generate_no_defaults_message(CHECK);
421 } else {
422 assert(root != NULL, "Null root class");
423 _exception_message = generate_method_message(root->name(), qualified_methods.at(0), CHECK);
424 }
425 _exception_name = vmSymbols::java_lang_AbstractMethodError();
426 // If only one qualified method is default, select that
427 } else if (num_defaults == 1) {
428 _selected_target = qualified_methods.at(default_index);
429 } else if (num_defaults > 1) {
430 _exception_message = generate_conflicts_message(&qualified_methods,CHECK);
431 _exception_name = vmSymbols::java_lang_IncompatibleClassChangeError();
432 if (TraceDefaultMethods) {
433 _exception_message->print_value_on(tty);
434 tty->print_cr("");
435 }
436 }
437 }
439 bool contains_signature(Symbol* query) {
440 for (int i = 0; i < _members.length(); ++i) {
441 if (query == _members.at(i).first->signature()) {
442 return true;
443 }
444 }
445 return false;
446 }
448 #ifndef PRODUCT
449 void print_sig_on(outputStream* str, Symbol* signature, int indent) const {
450 streamIndentor si(str, indent * 2);
452 str->indent().print_cr("Logical Method %s:", signature->as_C_string());
454 streamIndentor si2(str);
455 for (int i = 0; i < _members.length(); ++i) {
456 str->indent();
457 print_method(str, _members.at(i).first);
458 if (_members.at(i).second == DISQUALIFIED) {
459 str->print(" (disqualified)");
460 }
461 str->print_cr("");
462 }
464 if (_selected_target != NULL) {
465 print_selected(str, 1);
466 }
467 }
469 void print_selected(outputStream* str, int indent) const {
470 assert(has_target(), "Should be called otherwise");
471 streamIndentor si(str, indent * 2);
472 str->indent().print("Selected method: ");
473 print_method(str, _selected_target);
474 Klass* method_holder = _selected_target->method_holder();
475 if (!method_holder->is_interface()) {
476 tty->print(" : in superclass");
477 }
478 str->print_cr("");
479 }
481 void print_exception(outputStream* str, int indent) {
482 assert(throws_exception(), "Should be called otherwise");
483 assert(_exception_name != NULL, "exception_name should be set");
484 streamIndentor si(str, indent * 2);
485 str->indent().print_cr("%s: %s", _exception_name->as_C_string(), _exception_message->as_C_string());
486 }
487 #endif // ndef PRODUCT
488 };
490 Symbol* MethodFamily::generate_no_defaults_message(TRAPS) const {
491 return SymbolTable::new_symbol("No qualifying defaults found", CHECK_NULL);
492 }
494 Symbol* MethodFamily::generate_method_message(Symbol *klass_name, Method* method, TRAPS) const {
495 stringStream ss;
496 ss.print("Method ");
497 Symbol* name = method->name();
498 Symbol* signature = method->signature();
499 ss.write((const char*)klass_name->bytes(), klass_name->utf8_length());
500 ss.print(".");
501 ss.write((const char*)name->bytes(), name->utf8_length());
502 ss.write((const char*)signature->bytes(), signature->utf8_length());
503 ss.print(" is abstract");
504 return SymbolTable::new_symbol(ss.base(), (int)ss.size(), CHECK_NULL);
505 }
507 Symbol* MethodFamily::generate_conflicts_message(GrowableArray<Method*>* methods, TRAPS) const {
508 stringStream ss;
509 ss.print("Conflicting default methods:");
510 for (int i = 0; i < methods->length(); ++i) {
511 Method* method = methods->at(i);
512 Symbol* klass = method->klass_name();
513 Symbol* name = method->name();
514 ss.print(" ");
515 ss.write((const char*)klass->bytes(), klass->utf8_length());
516 ss.print(".");
517 ss.write((const char*)name->bytes(), name->utf8_length());
518 }
519 return SymbolTable::new_symbol(ss.base(), (int)ss.size(), CHECK_NULL);
520 }
523 class StateRestorer;
525 // StatefulMethodFamily is a wrapper around a MethodFamily that maintains the
526 // qualification state during hierarchy visitation, and applies that state
527 // when adding members to the MethodFamily
528 class StatefulMethodFamily : public ResourceObj {
529 friend class StateRestorer;
530 private:
531 QualifiedState _qualification_state;
533 void set_qualification_state(QualifiedState state) {
534 _qualification_state = state;
535 }
537 protected:
538 MethodFamily* _method_family;
540 public:
541 StatefulMethodFamily() {
542 _method_family = new MethodFamily();
543 _qualification_state = QUALIFIED;
544 }
546 StatefulMethodFamily(MethodFamily* mf) {
547 _method_family = mf;
548 _qualification_state = QUALIFIED;
549 }
551 void set_target_if_empty(Method* m) { _method_family->set_target_if_empty(m); }
553 MethodFamily* get_method_family() { return _method_family; }
555 StateRestorer* record_method_and_dq_further(Method* mo);
556 };
558 class StateRestorer : public PseudoScopeMark {
559 private:
560 StatefulMethodFamily* _method;
561 QualifiedState _state_to_restore;
562 public:
563 StateRestorer(StatefulMethodFamily* dm, QualifiedState state)
564 : _method(dm), _state_to_restore(state) {}
565 ~StateRestorer() { destroy(); }
566 void restore_state() { _method->set_qualification_state(_state_to_restore); }
567 virtual void destroy() { restore_state(); }
568 };
570 StateRestorer* StatefulMethodFamily::record_method_and_dq_further(Method* mo) {
571 StateRestorer* mark = new StateRestorer(this, _qualification_state);
572 if (_qualification_state == QUALIFIED) {
573 _method_family->record_qualified_method(mo);
574 } else {
575 _method_family->record_disqualified_method(mo);
576 }
577 // Everything found "above"??? this method in the hierarchy walk is set to
578 // disqualified
579 set_qualification_state(DISQUALIFIED);
580 return mark;
581 }
583 // Represents a location corresponding to a vtable slot for methods that
584 // neither the class nor any of it's ancestors provide an implementaion.
585 // Default methods may be present to fill this slot.
586 class EmptyVtableSlot : public ResourceObj {
587 private:
588 Symbol* _name;
589 Symbol* _signature;
590 int _size_of_parameters;
591 MethodFamily* _binding;
593 public:
594 EmptyVtableSlot(Method* method)
595 : _name(method->name()), _signature(method->signature()),
596 _size_of_parameters(method->size_of_parameters()), _binding(NULL) {}
598 Symbol* name() const { return _name; }
599 Symbol* signature() const { return _signature; }
600 int size_of_parameters() const { return _size_of_parameters; }
602 void bind_family(MethodFamily* lm) { _binding = lm; }
603 bool is_bound() { return _binding != NULL; }
604 MethodFamily* get_binding() { return _binding; }
606 #ifndef PRODUCT
607 void print_on(outputStream* str) const {
608 print_slot(str, name(), signature());
609 }
610 #endif // ndef PRODUCT
611 };
613 static bool already_in_vtable_slots(GrowableArray<EmptyVtableSlot*>* slots, Method* m) {
614 bool found = false;
615 for (int j = 0; j < slots->length(); ++j) {
616 if (slots->at(j)->name() == m->name() &&
617 slots->at(j)->signature() == m->signature() ) {
618 found = true;
619 break;
620 }
621 }
622 return found;
623 }
625 static GrowableArray<EmptyVtableSlot*>* find_empty_vtable_slots(
626 InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) {
628 assert(klass != NULL, "Must be valid class");
630 GrowableArray<EmptyVtableSlot*>* slots = new GrowableArray<EmptyVtableSlot*>();
632 // All miranda methods are obvious candidates
633 for (int i = 0; i < mirandas->length(); ++i) {
634 Method* m = mirandas->at(i);
635 if (!already_in_vtable_slots(slots, m)) {
636 slots->append(new EmptyVtableSlot(m));
637 }
638 }
640 // Also any overpasses in our superclasses, that we haven't implemented.
641 // (can't use the vtable because it is not guaranteed to be initialized yet)
642 InstanceKlass* super = klass->java_super();
643 while (super != NULL) {
644 for (int i = 0; i < super->methods()->length(); ++i) {
645 Method* m = super->methods()->at(i);
646 if (m->is_overpass() || m->is_static()) {
647 // m is a method that would have been a miranda if not for the
648 // default method processing that occurred on behalf of our superclass,
649 // so it's a method we want to re-examine in this new context. That is,
650 // unless we have a real implementation of it in the current class.
651 Method* impl = klass->lookup_method(m->name(), m->signature());
652 if (impl == NULL || impl->is_overpass() || impl->is_static()) {
653 if (!already_in_vtable_slots(slots, m)) {
654 slots->append(new EmptyVtableSlot(m));
655 }
656 }
657 }
658 }
660 // also any default methods in our superclasses
661 if (super->default_methods() != NULL) {
662 for (int i = 0; i < super->default_methods()->length(); ++i) {
663 Method* m = super->default_methods()->at(i);
664 // m is a method that would have been a miranda if not for the
665 // default method processing that occurred on behalf of our superclass,
666 // so it's a method we want to re-examine in this new context. That is,
667 // unless we have a real implementation of it in the current class.
668 Method* impl = klass->lookup_method(m->name(), m->signature());
669 if (impl == NULL || impl->is_overpass() || impl->is_static()) {
670 if (!already_in_vtable_slots(slots, m)) {
671 slots->append(new EmptyVtableSlot(m));
672 }
673 }
674 }
675 }
676 super = super->java_super();
677 }
679 #ifndef PRODUCT
680 if (TraceDefaultMethods) {
681 tty->print_cr("Slots that need filling:");
682 streamIndentor si(tty);
683 for (int i = 0; i < slots->length(); ++i) {
684 tty->indent();
685 slots->at(i)->print_on(tty);
686 tty->print_cr("");
687 }
688 }
689 #endif // ndef PRODUCT
690 return slots;
691 }
693 // Iterates over the superinterface type hierarchy looking for all methods
694 // with a specific erased signature.
695 class FindMethodsByErasedSig : public HierarchyVisitor<FindMethodsByErasedSig> {
696 private:
697 // Context data
698 Symbol* _method_name;
699 Symbol* _method_signature;
700 StatefulMethodFamily* _family;
702 public:
703 FindMethodsByErasedSig(Symbol* name, Symbol* signature) :
704 _method_name(name), _method_signature(signature),
705 _family(NULL) {}
707 void get_discovered_family(MethodFamily** family) {
708 if (_family != NULL) {
709 *family = _family->get_method_family();
710 } else {
711 *family = NULL;
712 }
713 }
715 void* new_node_data(InstanceKlass* cls) { return new PseudoScope(); }
716 void free_node_data(void* node_data) {
717 PseudoScope::cast(node_data)->destroy();
718 }
720 // Find all methods on this hierarchy that match this
721 // method's erased (name, signature)
722 bool visit() {
723 PseudoScope* scope = PseudoScope::cast(current_data());
724 InstanceKlass* iklass = current_class();
726 Method* m = iklass->find_method(_method_name, _method_signature);
727 // private interface methods are not candidates for default methods
728 // invokespecial to private interface methods doesn't use default method logic
729 // The overpasses are your supertypes' errors, we do not include them
730 // future: take access controls into account for superclass methods
731 if (m != NULL && !m->is_static() && !m->is_overpass() &&
732 (!iklass->is_interface() || m->is_public())) {
733 if (_family == NULL) {
734 _family = new StatefulMethodFamily();
735 }
737 if (iklass->is_interface()) {
738 StateRestorer* restorer = _family->record_method_and_dq_further(m);
739 scope->add_mark(restorer);
740 } else {
741 // This is the rule that methods in classes "win" (bad word) over
742 // methods in interfaces. This works because of single inheritance
743 _family->set_target_if_empty(m);
744 }
745 }
746 return true;
747 }
749 };
753 static void create_defaults_and_exceptions(
754 GrowableArray<EmptyVtableSlot*>* slots, InstanceKlass* klass, TRAPS);
756 static void generate_erased_defaults(
757 InstanceKlass* klass, GrowableArray<EmptyVtableSlot*>* empty_slots,
758 EmptyVtableSlot* slot, TRAPS) {
760 // sets up a set of methods with the same exact erased signature
761 FindMethodsByErasedSig visitor(slot->name(), slot->signature());
762 visitor.run(klass);
764 MethodFamily* family;
765 visitor.get_discovered_family(&family);
766 if (family != NULL) {
767 family->determine_target(klass, CHECK);
768 slot->bind_family(family);
769 }
770 }
772 static void merge_in_new_methods(InstanceKlass* klass,
773 GrowableArray<Method*>* new_methods, TRAPS);
774 static void create_default_methods( InstanceKlass* klass,
775 GrowableArray<Method*>* new_methods, TRAPS);
777 // This is the guts of the default methods implementation. This is called just
778 // after the classfile has been parsed if some ancestor has default methods.
779 //
780 // First if finds any name/signature slots that need any implementation (either
781 // because they are miranda or a superclass's implementation is an overpass
782 // itself). For each slot, iterate over the hierarchy, to see if they contain a
783 // signature that matches the slot we are looking at.
784 //
785 // For each slot filled, we generate an overpass method that either calls the
786 // unique default method candidate using invokespecial, or throws an exception
787 // (in the case of no default method candidates, or more than one valid
788 // candidate). These methods are then added to the class's method list.
789 // The JVM does not create bridges nor handle generic signatures here.
790 void DefaultMethods::generate_default_methods(
791 InstanceKlass* klass, GrowableArray<Method*>* mirandas, TRAPS) {
793 // This resource mark is the bound for all memory allocation that takes
794 // place during default method processing. After this goes out of scope,
795 // all (Resource) objects' memory will be reclaimed. Be careful if adding an
796 // embedded resource mark under here as that memory can't be used outside
797 // whatever scope it's in.
798 ResourceMark rm(THREAD);
800 // Keep entire hierarchy alive for the duration of the computation
801 KeepAliveRegistrar keepAlive(THREAD);
802 KeepAliveVisitor loadKeepAlive(&keepAlive);
803 loadKeepAlive.run(klass);
805 #ifndef PRODUCT
806 if (TraceDefaultMethods) {
807 ResourceMark rm; // be careful with these!
808 tty->print_cr("%s %s requires default method processing",
809 klass->is_interface() ? "Interface" : "Class",
810 klass->name()->as_klass_external_name());
811 PrintHierarchy printer;
812 printer.run(klass);
813 }
814 #endif // ndef PRODUCT
816 GrowableArray<EmptyVtableSlot*>* empty_slots =
817 find_empty_vtable_slots(klass, mirandas, CHECK);
819 for (int i = 0; i < empty_slots->length(); ++i) {
820 EmptyVtableSlot* slot = empty_slots->at(i);
821 #ifndef PRODUCT
822 if (TraceDefaultMethods) {
823 streamIndentor si(tty, 2);
824 tty->indent().print("Looking for default methods for slot ");
825 slot->print_on(tty);
826 tty->print_cr("");
827 }
828 #endif // ndef PRODUCT
830 generate_erased_defaults(klass, empty_slots, slot, CHECK);
831 }
832 #ifndef PRODUCT
833 if (TraceDefaultMethods) {
834 tty->print_cr("Creating defaults and overpasses...");
835 }
836 #endif // ndef PRODUCT
838 create_defaults_and_exceptions(empty_slots, klass, CHECK);
840 #ifndef PRODUCT
841 if (TraceDefaultMethods) {
842 tty->print_cr("Default method processing complete");
843 }
844 #endif // ndef PRODUCT
845 }
847 static int assemble_method_error(
848 BytecodeConstantPool* cp, BytecodeBuffer* buffer, Symbol* errorName, Symbol* message, TRAPS) {
850 Symbol* init = vmSymbols::object_initializer_name();
851 Symbol* sig = vmSymbols::string_void_signature();
853 BytecodeAssembler assem(buffer, cp);
855 assem._new(errorName);
856 assem.dup();
857 assem.load_string(message);
858 assem.invokespecial(errorName, init, sig);
859 assem.athrow();
861 return 3; // max stack size: [ exception, exception, string ]
862 }
864 static Method* new_method(
865 BytecodeConstantPool* cp, BytecodeBuffer* bytecodes, Symbol* name,
866 Symbol* sig, AccessFlags flags, int max_stack, int params,
867 ConstMethod::MethodType mt, TRAPS) {
869 address code_start = 0;
870 int code_length = 0;
871 InlineTableSizes sizes;
873 if (bytecodes != NULL && bytecodes->length() > 0) {
874 code_start = static_cast<address>(bytecodes->adr_at(0));
875 code_length = bytecodes->length();
876 }
878 Method* m = Method::allocate(cp->pool_holder()->class_loader_data(),
879 code_length, flags, &sizes,
880 mt, CHECK_NULL);
882 m->set_constants(NULL); // This will get filled in later
883 m->set_name_index(cp->utf8(name));
884 m->set_signature_index(cp->utf8(sig));
885 #ifdef CC_INTERP
886 ResultTypeFinder rtf(sig);
887 m->set_result_index(rtf.type());
888 #endif
889 m->set_size_of_parameters(params);
890 m->set_max_stack(max_stack);
891 m->set_max_locals(params);
892 m->constMethod()->set_stackmap_data(NULL);
893 m->set_code(code_start);
895 return m;
896 }
898 static void switchover_constant_pool(BytecodeConstantPool* bpool,
899 InstanceKlass* klass, GrowableArray<Method*>* new_methods, TRAPS) {
901 if (new_methods->length() > 0) {
902 ConstantPool* cp = bpool->create_constant_pool(CHECK);
903 if (cp != klass->constants()) {
904 klass->class_loader_data()->add_to_deallocate_list(klass->constants());
905 klass->set_constants(cp);
906 cp->set_pool_holder(klass);
908 for (int i = 0; i < new_methods->length(); ++i) {
909 new_methods->at(i)->set_constants(cp);
910 }
911 for (int i = 0; i < klass->methods()->length(); ++i) {
912 Method* mo = klass->methods()->at(i);
913 mo->set_constants(cp);
914 }
915 }
916 }
917 }
919 // Create default_methods list for the current class.
920 // With the VM only processing erased signatures, the VM only
921 // creates an overpass in a conflict case or a case with no candidates.
922 // This allows virtual methods to override the overpass, but ensures
923 // that a local method search will find the exception rather than an abstract
924 // or default method that is not a valid candidate.
925 static void create_defaults_and_exceptions(
926 GrowableArray<EmptyVtableSlot*>* slots,
927 InstanceKlass* klass, TRAPS) {
929 GrowableArray<Method*> overpasses;
930 GrowableArray<Method*> defaults;
931 BytecodeConstantPool bpool(klass->constants());
933 for (int i = 0; i < slots->length(); ++i) {
934 EmptyVtableSlot* slot = slots->at(i);
936 if (slot->is_bound()) {
937 MethodFamily* method = slot->get_binding();
938 BytecodeBuffer buffer;
940 #ifndef PRODUCT
941 if (TraceDefaultMethods) {
942 tty->print("for slot: ");
943 slot->print_on(tty);
944 tty->print_cr("");
945 if (method->has_target()) {
946 method->print_selected(tty, 1);
947 } else if (method->throws_exception()) {
948 method->print_exception(tty, 1);
949 }
950 }
951 #endif // ndef PRODUCT
953 if (method->has_target()) {
954 Method* selected = method->get_selected_target();
955 if (selected->method_holder()->is_interface()) {
956 defaults.push(selected);
957 }
958 } else if (method->throws_exception()) {
959 int max_stack = assemble_method_error(&bpool, &buffer,
960 method->get_exception_name(), method->get_exception_message(), CHECK);
961 AccessFlags flags = accessFlags_from(
962 JVM_ACC_PUBLIC | JVM_ACC_SYNTHETIC | JVM_ACC_BRIDGE);
963 Method* m = new_method(&bpool, &buffer, slot->name(), slot->signature(),
964 flags, max_stack, slot->size_of_parameters(),
965 ConstMethod::OVERPASS, CHECK);
966 // We push to the methods list:
967 // overpass methods which are exception throwing methods
968 if (m != NULL) {
969 overpasses.push(m);
970 }
971 }
972 }
973 }
975 #ifndef PRODUCT
976 if (TraceDefaultMethods) {
977 tty->print_cr("Created %d overpass methods", overpasses.length());
978 tty->print_cr("Created %d default methods", defaults.length());
979 }
980 #endif // ndef PRODUCT
982 if (overpasses.length() > 0) {
983 switchover_constant_pool(&bpool, klass, &overpasses, CHECK);
984 merge_in_new_methods(klass, &overpasses, CHECK);
985 }
986 if (defaults.length() > 0) {
987 create_default_methods(klass, &defaults, CHECK);
988 }
989 }
991 static void create_default_methods( InstanceKlass* klass,
992 GrowableArray<Method*>* new_methods, TRAPS) {
994 int new_size = new_methods->length();
995 Array<Method*>* total_default_methods = MetadataFactory::new_array<Method*>(
996 klass->class_loader_data(), new_size, NULL, CHECK);
997 for (int index = 0; index < new_size; index++ ) {
998 total_default_methods->at_put(index, new_methods->at(index));
999 }
1000 Method::sort_methods(total_default_methods, false, false);
1002 klass->set_default_methods(total_default_methods);
1003 }
1005 static void sort_methods(GrowableArray<Method*>* methods) {
1006 // Note that this must sort using the same key as is used for sorting
1007 // methods in InstanceKlass.
1008 bool sorted = true;
1009 for (int i = methods->length() - 1; i > 0; --i) {
1010 for (int j = 0; j < i; ++j) {
1011 Method* m1 = methods->at(j);
1012 Method* m2 = methods->at(j + 1);
1013 if ((uintptr_t)m1->name() > (uintptr_t)m2->name()) {
1014 methods->at_put(j, m2);
1015 methods->at_put(j + 1, m1);
1016 sorted = false;
1017 }
1018 }
1019 if (sorted) break;
1020 sorted = true;
1021 }
1022 #ifdef ASSERT
1023 uintptr_t prev = 0;
1024 for (int i = 0; i < methods->length(); ++i) {
1025 Method* mh = methods->at(i);
1026 uintptr_t nv = (uintptr_t)mh->name();
1027 assert(nv >= prev, "Incorrect overpass method ordering");
1028 prev = nv;
1029 }
1030 #endif
1031 }
1033 static void merge_in_new_methods(InstanceKlass* klass,
1034 GrowableArray<Method*>* new_methods, TRAPS) {
1036 enum { ANNOTATIONS, PARAMETERS, DEFAULTS, NUM_ARRAYS };
1038 Array<Method*>* original_methods = klass->methods();
1039 Array<int>* original_ordering = klass->method_ordering();
1040 Array<int>* merged_ordering = Universe::the_empty_int_array();
1042 int new_size = klass->methods()->length() + new_methods->length();
1044 Array<Method*>* merged_methods = MetadataFactory::new_array<Method*>(
1045 klass->class_loader_data(), new_size, NULL, CHECK);
1047 // original_ordering might be empty if this class has no methods of its own
1048 if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
1049 merged_ordering = MetadataFactory::new_array<int>(
1050 klass->class_loader_data(), new_size, CHECK);
1051 }
1052 int method_order_index = klass->methods()->length();
1054 sort_methods(new_methods);
1056 // Perform grand merge of existing methods and new methods
1057 int orig_idx = 0;
1058 int new_idx = 0;
1060 for (int i = 0; i < new_size; ++i) {
1061 Method* orig_method = NULL;
1062 Method* new_method = NULL;
1063 if (orig_idx < original_methods->length()) {
1064 orig_method = original_methods->at(orig_idx);
1065 }
1066 if (new_idx < new_methods->length()) {
1067 new_method = new_methods->at(new_idx);
1068 }
1070 if (orig_method != NULL &&
1071 (new_method == NULL || orig_method->name() < new_method->name())) {
1072 merged_methods->at_put(i, orig_method);
1073 original_methods->at_put(orig_idx, NULL);
1074 if (merged_ordering->length() > 0) {
1075 assert(original_ordering != NULL && original_ordering->length() > 0,
1076 "should have original order information for this method");
1077 merged_ordering->at_put(i, original_ordering->at(orig_idx));
1078 }
1079 ++orig_idx;
1080 } else {
1081 merged_methods->at_put(i, new_method);
1082 if (merged_ordering->length() > 0) {
1083 merged_ordering->at_put(i, method_order_index++);
1084 }
1085 ++new_idx;
1086 }
1087 // update idnum for new location
1088 merged_methods->at(i)->set_method_idnum(i);
1089 }
1091 // Verify correct order
1092 #ifdef ASSERT
1093 uintptr_t prev = 0;
1094 for (int i = 0; i < merged_methods->length(); ++i) {
1095 Method* mo = merged_methods->at(i);
1096 uintptr_t nv = (uintptr_t)mo->name();
1097 assert(nv >= prev, "Incorrect method ordering");
1098 prev = nv;
1099 }
1100 #endif
1102 // Replace klass methods with new merged lists
1103 klass->set_methods(merged_methods);
1104 klass->set_initial_method_idnum(new_size);
1105 klass->set_method_ordering(merged_ordering);
1107 // Free metadata
1108 ClassLoaderData* cld = klass->class_loader_data();
1109 if (original_methods->length() > 0) {
1110 MetadataFactory::free_array(cld, original_methods);
1111 }
1112 if (original_ordering != NULL && original_ordering->length() > 0) {
1113 MetadataFactory::free_array(cld, original_ordering);
1114 }
1115 }