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