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