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