1 /*
   2  * Copyright (c) 1997, 2014, 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/metadataOnStackMark.hpp"
  27 #include "classfile/systemDictionary.hpp"
  28 #include "code/debugInfoRec.hpp"
  29 #include "gc_interface/collectedHeap.inline.hpp"
  30 #include "interpreter/bytecodeStream.hpp"
  31 #include "interpreter/bytecodeTracer.hpp"
  32 #include "interpreter/bytecodes.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "interpreter/oopMapCache.hpp"
  35 #include "memory/gcLocker.hpp"
  36 #include "memory/generation.hpp"
  37 #include "memory/heapInspection.hpp"
  38 #include "memory/metadataFactory.hpp"
  39 #include "memory/oopFactory.hpp"
  40 #include "oops/constMethod.hpp"
  41 #include "oops/methodData.hpp"
  42 #include "oops/method.hpp"
  43 #include "oops/oop.inline.hpp"
  44 #include "oops/symbol.hpp"
  45 #include "prims/jvmtiExport.hpp"
  46 #include "prims/methodHandles.hpp"
  47 #include "prims/nativeLookup.hpp"
  48 #include "runtime/arguments.hpp"
  49 #include "runtime/compilationPolicy.hpp"
  50 #include "runtime/frame.inline.hpp"
  51 #include "runtime/handles.inline.hpp"
  52 #include "runtime/orderAccess.inline.hpp"
  53 #include "runtime/relocator.hpp"
  54 #include "runtime/sharedRuntime.hpp"
  55 #include "runtime/signature.hpp"
  56 #include "utilities/quickSort.hpp"
  57 #include "utilities/xmlstream.hpp"
  58 
  59 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  60 
  61 // Implementation of Method
  62 
  63 Method* Method::allocate(ClassLoaderData* loader_data,
  64                          int byte_code_size,
  65                          AccessFlags access_flags,
  66                          InlineTableSizes* sizes,
  67                          ConstMethod::MethodType method_type,
  68                          TRAPS) {
  69   assert(!access_flags.is_native() || byte_code_size == 0,
  70          "native methods should not contain byte codes");
  71   ConstMethod* cm = ConstMethod::allocate(loader_data,
  72                                           byte_code_size,
  73                                           sizes,
  74                                           method_type,
  75                                           CHECK_NULL);
  76 
  77   int size = Method::size(access_flags.is_native());
  78 
  79   return new (loader_data, size, false, MetaspaceObj::MethodType, THREAD) Method(cm, access_flags, size);
  80 }
  81 
  82 Method::Method(ConstMethod* xconst, AccessFlags access_flags, int size) {
  83   No_Safepoint_Verifier no_safepoint;
  84   set_constMethod(xconst);
  85   set_access_flags(access_flags);
  86   set_method_size(size);
  87 #ifdef CC_INTERP
  88   set_result_index(T_VOID);
  89 #endif
  90   set_intrinsic_id(vmIntrinsics::_none);
  91   set_jfr_towrite(false);
  92   set_force_inline(false);
  93   set_hidden(false);
  94   set_dont_inline(false);
  95   set_method_data(NULL);
  96   clear_method_counters();
  97   set_vtable_index(Method::garbage_vtable_index);
  98 
  99   // Fix and bury in Method*
 100   set_interpreter_entry(NULL); // sets i2i entry and from_int
 101   set_adapter_entry(NULL);
 102   clear_code(); // from_c/from_i get set to c2i/i2i
 103 
 104   if (access_flags.is_native()) {
 105     clear_native_function();
 106     set_signature_handler(NULL);
 107   }
 108 
 109   NOT_PRODUCT(set_compiled_invocation_count(0);)
 110 }
 111 
 112 // Release Method*.  The nmethod will be gone when we get here because
 113 // we've walked the code cache.
 114 void Method::deallocate_contents(ClassLoaderData* loader_data) {
 115   MetadataFactory::free_metadata(loader_data, constMethod());
 116   set_constMethod(NULL);
 117   MetadataFactory::free_metadata(loader_data, method_data());
 118   set_method_data(NULL);
 119   MetadataFactory::free_metadata(loader_data, method_counters());
 120   clear_method_counters();
 121   // The nmethod will be gone when we get here.
 122   if (code() != NULL) _code = NULL;
 123 }
 124 
 125 address Method::get_i2c_entry() {
 126   assert(_adapter != NULL, "must have");
 127   return _adapter->get_i2c_entry();
 128 }
 129 
 130 address Method::get_c2i_entry() {
 131   assert(_adapter != NULL, "must have");
 132   return _adapter->get_c2i_entry();
 133 }
 134 
 135 address Method::get_c2i_unverified_entry() {
 136   assert(_adapter != NULL, "must have");
 137   return _adapter->get_c2i_unverified_entry();
 138 }
 139 
 140 char* Method::name_and_sig_as_C_string() const {
 141   return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature());
 142 }
 143 
 144 char* Method::name_and_sig_as_C_string(char* buf, int size) const {
 145   return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature(), buf, size);
 146 }
 147 
 148 char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature) {
 149   const char* klass_name = klass->external_name();
 150   int klass_name_len  = (int)strlen(klass_name);
 151   int method_name_len = method_name->utf8_length();
 152   int len             = klass_name_len + 1 + method_name_len + signature->utf8_length();
 153   char* dest          = NEW_RESOURCE_ARRAY(char, len + 1);
 154   strcpy(dest, klass_name);
 155   dest[klass_name_len] = '.';
 156   strcpy(&dest[klass_name_len + 1], method_name->as_C_string());
 157   strcpy(&dest[klass_name_len + 1 + method_name_len], signature->as_C_string());
 158   dest[len] = 0;
 159   return dest;
 160 }
 161 
 162 char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size) {
 163   Symbol* klass_name = klass->name();
 164   klass_name->as_klass_external_name(buf, size);
 165   int len = (int)strlen(buf);
 166 
 167   if (len < size - 1) {
 168     buf[len++] = '.';
 169 
 170     method_name->as_C_string(&(buf[len]), size - len);
 171     len = (int)strlen(buf);
 172 
 173     signature->as_C_string(&(buf[len]), size - len);
 174   }
 175 
 176   return buf;
 177 }
 178 
 179 int Method::fast_exception_handler_bci_for(methodHandle mh, KlassHandle ex_klass, int throw_bci, TRAPS) {
 180   // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
 181   // access exception table
 182   ExceptionTable table(mh());
 183   int length = table.length();
 184   // iterate through all entries sequentially
 185   constantPoolHandle pool(THREAD, mh->constants());
 186   for (int i = 0; i < length; i ++) {
 187     //reacquire the table in case a GC happened
 188     ExceptionTable table(mh());
 189     int beg_bci = table.start_pc(i);
 190     int end_bci = table.end_pc(i);
 191     assert(beg_bci <= end_bci, "inconsistent exception table");
 192     if (beg_bci <= throw_bci && throw_bci < end_bci) {
 193       // exception handler bci range covers throw_bci => investigate further
 194       int handler_bci = table.handler_pc(i);
 195       int klass_index = table.catch_type_index(i);
 196       if (klass_index == 0) {
 197         return handler_bci;
 198       } else if (ex_klass.is_null()) {
 199         return handler_bci;
 200       } else {
 201         // we know the exception class => get the constraint class
 202         // this may require loading of the constraint class; if verification
 203         // fails or some other exception occurs, return handler_bci
 204         Klass* k = pool->klass_at(klass_index, CHECK_(handler_bci));
 205         KlassHandle klass = KlassHandle(THREAD, k);
 206         assert(klass.not_null(), "klass not loaded");
 207         if (ex_klass->is_subtype_of(klass())) {
 208           return handler_bci;
 209         }
 210       }
 211     }
 212   }
 213 
 214   return -1;
 215 }
 216 
 217 void Method::mask_for(int bci, InterpreterOopMap* mask) {
 218 
 219   Thread* myThread    = Thread::current();
 220   methodHandle h_this(myThread, this);
 221 #ifdef ASSERT
 222   bool has_capability = myThread->is_VM_thread() ||
 223                         myThread->is_ConcurrentGC_thread() ||
 224                         myThread->is_GC_task_thread();
 225 
 226   if (!has_capability) {
 227     if (!VerifyStack && !VerifyLastFrame) {
 228       // verify stack calls this outside VM thread
 229       warning("oopmap should only be accessed by the "
 230               "VM, GC task or CMS threads (or during debugging)");
 231       InterpreterOopMap local_mask;
 232       method_holder()->mask_for(h_this, bci, &local_mask);
 233       local_mask.print();
 234     }
 235   }
 236 #endif
 237   method_holder()->mask_for(h_this, bci, mask);
 238   return;
 239 }
 240 
 241 
 242 int Method::bci_from(address bcp) const {
 243   if (is_native() && bcp == 0) {
 244     return 0;
 245   }
 246 #ifdef ASSERT
 247   { ResourceMark rm;
 248   assert(is_native() && bcp == code_base() || contains(bcp) || is_error_reported(),
 249          err_msg("bcp doesn't belong to this method: bcp: " INTPTR_FORMAT ", method: %s", bcp, name_and_sig_as_C_string()));
 250   }
 251 #endif
 252   return bcp - code_base();
 253 }
 254 
 255 
 256 int Method::validate_bci(int bci) const {
 257   return (bci == 0 || bci < code_size()) ? bci : -1;
 258 }
 259 
 260 // Return bci if it appears to be a valid bcp
 261 // Return -1 otherwise.
 262 // Used by profiling code, when invalid data is a possibility.
 263 // The caller is responsible for validating the Method* itself.
 264 int Method::validate_bci_from_bcp(address bcp) const {
 265   // keep bci as -1 if not a valid bci
 266   int bci = -1;
 267   if (bcp == 0 || bcp == code_base()) {
 268     // code_size() may return 0 and we allow 0 here
 269     // the method may be native
 270     bci = 0;
 271   } else if (contains(bcp)) {
 272     bci = bcp - code_base();
 273   }
 274   // Assert that if we have dodged any asserts, bci is negative.
 275   assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0");
 276   return bci;
 277 }
 278 
 279 address Method::bcp_from(int bci) const {
 280   assert((is_native() && bci == 0)  || (!is_native() && 0 <= bci && bci < code_size()), err_msg("illegal bci: %d", bci));
 281   address bcp = code_base() + bci;
 282   assert(is_native() && bcp == code_base() || contains(bcp), "bcp doesn't belong to this method");
 283   return bcp;
 284 }
 285 
 286 address Method::bcp_from(address bcp) const {
 287   if (is_native() && bcp == NULL) {
 288     return code_base();
 289   } else {
 290     return bcp;
 291   }
 292 }
 293 
 294 int Method::size(bool is_native) {
 295   // If native, then include pointers for native_function and signature_handler
 296   int extra_bytes = (is_native) ? 2*sizeof(address*) : 0;
 297   int extra_words = align_size_up(extra_bytes, BytesPerWord) / BytesPerWord;
 298   return align_object_size(header_size() + extra_words);
 299 }
 300 
 301 
 302 Symbol* Method::klass_name() const {
 303   Klass* k = method_holder();
 304   assert(k->is_klass(), "must be klass");
 305   InstanceKlass* ik = (InstanceKlass*) k;
 306   return ik->name();
 307 }
 308 
 309 
 310 // Attempt to return method oop to original state.  Clear any pointers
 311 // (to objects outside the shared spaces).  We won't be able to predict
 312 // where they should point in a new JVM.  Further initialize some
 313 // entries now in order allow them to be write protected later.
 314 
 315 void Method::remove_unshareable_info() {
 316   unlink_method();
 317 }
 318 
 319 
 320 bool Method::was_executed_more_than(int n) {
 321   // Invocation counter is reset when the Method* is compiled.
 322   // If the method has compiled code we therefore assume it has
 323   // be excuted more than n times.
 324   if (is_accessor() || is_empty_method() || (code() != NULL)) {
 325     // interpreter doesn't bump invocation counter of trivial methods
 326     // compiler does not bump invocation counter of compiled methods
 327     return true;
 328   }
 329   else if ((method_counters() != NULL &&
 330             method_counters()->invocation_counter()->carry()) ||
 331            (method_data() != NULL &&
 332             method_data()->invocation_counter()->carry())) {
 333     // The carry bit is set when the counter overflows and causes
 334     // a compilation to occur.  We don't know how many times
 335     // the counter has been reset, so we simply assume it has
 336     // been executed more than n times.
 337     return true;
 338   } else {
 339     return invocation_count() > n;
 340   }
 341 }
 342 
 343 void Method::print_invocation_count() {
 344   if (is_static()) tty->print("static ");
 345   if (is_final()) tty->print("final ");
 346   if (is_synchronized()) tty->print("synchronized ");
 347   if (is_native()) tty->print("native ");
 348   tty->print("%s::", method_holder()->external_name());
 349   name()->print_symbol_on(tty);
 350   signature()->print_symbol_on(tty);
 351 
 352   if (WizardMode) {
 353     // dump the size of the byte codes
 354     tty->print(" {%d}", code_size());
 355   }
 356   tty->cr();
 357 
 358   tty->print_cr ("  interpreter_invocation_count: %8d ", interpreter_invocation_count());
 359   tty->print_cr ("  invocation_counter:           %8d ", invocation_count());
 360   tty->print_cr ("  backedge_counter:             %8d ", backedge_count());
 361 #ifndef PRODUCT
 362   if (CountCompiledCalls) {
 363     tty->print_cr ("  compiled_invocation_count: %8d ", compiled_invocation_count());
 364   }
 365 #endif
 366 }
 367 
 368 // Build a MethodData* object to hold information about this method
 369 // collected in the interpreter.
 370 void Method::build_interpreter_method_data(methodHandle method, TRAPS) {
 371   // Do not profile method if current thread holds the pending list lock,
 372   // which avoids deadlock for acquiring the MethodData_lock.
 373   if (InstanceRefKlass::owns_pending_list_lock((JavaThread*)THREAD)) {
 374     return;
 375   }
 376 
 377   // Grab a lock here to prevent multiple
 378   // MethodData*s from being created.
 379   MutexLocker ml(MethodData_lock, THREAD);
 380   if (method->method_data() == NULL) {
 381     ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
 382     MethodData* method_data = MethodData::allocate(loader_data, method, CHECK);
 383     method->set_method_data(method_data);
 384     if (PrintMethodData && (Verbose || WizardMode)) {
 385       ResourceMark rm(THREAD);
 386       tty->print("build_interpreter_method_data for ");
 387       method->print_name(tty);
 388       tty->cr();
 389       // At the end of the run, the MDO, full of data, will be dumped.
 390     }
 391   }
 392 }
 393 
 394 MethodCounters* Method::build_method_counters(Method* m, TRAPS) {
 395   methodHandle mh(m);
 396   ClassLoaderData* loader_data = mh->method_holder()->class_loader_data();
 397   MethodCounters* counters = MethodCounters::allocate(loader_data, CHECK_NULL);
 398   if (!mh->init_method_counters(counters)) {
 399     MetadataFactory::free_metadata(loader_data, counters);
 400   }
 401   return mh->method_counters();
 402 }
 403 
 404 void Method::cleanup_inline_caches() {
 405   // The current system doesn't use inline caches in the interpreter
 406   // => nothing to do (keep this method around for future use)
 407 }
 408 
 409 
 410 int Method::extra_stack_words() {
 411   // not an inline function, to avoid a header dependency on Interpreter
 412   return extra_stack_entries() * Interpreter::stackElementSize;
 413 }
 414 
 415 
 416 void Method::compute_size_of_parameters(Thread *thread) {
 417   ArgumentSizeComputer asc(signature());
 418   set_size_of_parameters(asc.size() + (is_static() ? 0 : 1));
 419 }
 420 
 421 #ifdef CC_INTERP
 422 void Method::set_result_index(BasicType type)          {
 423   _result_index = Interpreter::BasicType_as_index(type);
 424 }
 425 #endif
 426 
 427 BasicType Method::result_type() const {
 428   ResultTypeFinder rtf(signature());
 429   return rtf.type();
 430 }
 431 
 432 
 433 bool Method::is_empty_method() const {
 434   return  code_size() == 1
 435       && *code_base() == Bytecodes::_return;
 436 }
 437 
 438 
 439 bool Method::is_vanilla_constructor() const {
 440   // Returns true if this method is a vanilla constructor, i.e. an "<init>" "()V" method
 441   // which only calls the superclass vanilla constructor and possibly does stores of
 442   // zero constants to local fields:
 443   //
 444   //   aload_0
 445   //   invokespecial
 446   //   indexbyte1
 447   //   indexbyte2
 448   //
 449   // followed by an (optional) sequence of:
 450   //
 451   //   aload_0
 452   //   aconst_null / iconst_0 / fconst_0 / dconst_0
 453   //   putfield
 454   //   indexbyte1
 455   //   indexbyte2
 456   //
 457   // followed by:
 458   //
 459   //   return
 460 
 461   assert(name() == vmSymbols::object_initializer_name(),    "Should only be called for default constructors");
 462   assert(signature() == vmSymbols::void_method_signature(), "Should only be called for default constructors");
 463   int size = code_size();
 464   // Check if size match
 465   if (size == 0 || size % 5 != 0) return false;
 466   address cb = code_base();
 467   int last = size - 1;
 468   if (cb[0] != Bytecodes::_aload_0 || cb[1] != Bytecodes::_invokespecial || cb[last] != Bytecodes::_return) {
 469     // Does not call superclass default constructor
 470     return false;
 471   }
 472   // Check optional sequence
 473   for (int i = 4; i < last; i += 5) {
 474     if (cb[i] != Bytecodes::_aload_0) return false;
 475     if (!Bytecodes::is_zero_const(Bytecodes::cast(cb[i+1]))) return false;
 476     if (cb[i+2] != Bytecodes::_putfield) return false;
 477   }
 478   return true;
 479 }
 480 
 481 
 482 bool Method::compute_has_loops_flag() {
 483   BytecodeStream bcs(this);
 484   Bytecodes::Code bc;
 485 
 486   while ((bc = bcs.next()) >= 0) {
 487     switch( bc ) {
 488       case Bytecodes::_ifeq:
 489       case Bytecodes::_ifnull:
 490       case Bytecodes::_iflt:
 491       case Bytecodes::_ifle:
 492       case Bytecodes::_ifne:
 493       case Bytecodes::_ifnonnull:
 494       case Bytecodes::_ifgt:
 495       case Bytecodes::_ifge:
 496       case Bytecodes::_if_icmpeq:
 497       case Bytecodes::_if_icmpne:
 498       case Bytecodes::_if_icmplt:
 499       case Bytecodes::_if_icmpgt:
 500       case Bytecodes::_if_icmple:
 501       case Bytecodes::_if_icmpge:
 502       case Bytecodes::_if_acmpeq:
 503       case Bytecodes::_if_acmpne:
 504       case Bytecodes::_goto:
 505       case Bytecodes::_jsr:
 506         if( bcs.dest() < bcs.next_bci() ) _access_flags.set_has_loops();
 507         break;
 508 
 509       case Bytecodes::_goto_w:
 510       case Bytecodes::_jsr_w:
 511         if( bcs.dest_w() < bcs.next_bci() ) _access_flags.set_has_loops();
 512         break;
 513     }
 514   }
 515   _access_flags.set_loops_flag_init();
 516   return _access_flags.has_loops();
 517 }
 518 
 519 bool Method::is_final_method(AccessFlags class_access_flags) const {
 520   // or "does_not_require_vtable_entry"
 521   // default method or overpass can occur, is not final (reuses vtable entry)
 522   // private methods get vtable entries for backward class compatibility.
 523   if (is_overpass() || is_default_method())  return false;
 524   return is_final() || class_access_flags.is_final();
 525 }
 526 
 527 bool Method::is_final_method() const {
 528   return is_final_method(method_holder()->access_flags());
 529 }
 530 
 531 bool Method::is_default_method() const {
 532   if (method_holder() != NULL &&
 533       method_holder()->is_interface() &&
 534       !is_abstract()) {
 535     return true;
 536   } else {
 537     return false;
 538   }
 539 }
 540 
 541 bool Method::can_be_statically_bound(AccessFlags class_access_flags) const {
 542   if (is_final_method(class_access_flags))  return true;
 543 #ifdef ASSERT
 544   ResourceMark rm;
 545   bool is_nonv = (vtable_index() == nonvirtual_vtable_index);
 546   if (class_access_flags.is_interface()) {
 547       assert(is_nonv == is_static(), err_msg("is_nonv=%s", name_and_sig_as_C_string()));
 548   }
 549 #endif
 550   assert(valid_vtable_index() || valid_itable_index(), "method must be linked before we ask this question");
 551   return vtable_index() == nonvirtual_vtable_index;
 552 }
 553 
 554 bool Method::can_be_statically_bound() const {
 555   return can_be_statically_bound(method_holder()->access_flags());
 556 }
 557 
 558 bool Method::is_accessor() const {
 559   if (code_size() != 5) return false;
 560   if (size_of_parameters() != 1) return false;
 561   if (java_code_at(0) != Bytecodes::_aload_0 ) return false;
 562   if (java_code_at(1) != Bytecodes::_getfield) return false;
 563   if (java_code_at(4) != Bytecodes::_areturn &&
 564       java_code_at(4) != Bytecodes::_ireturn ) return false;
 565   return true;
 566 }
 567 
 568 bool Method::is_constant_getter() const {
 569   int last_index = code_size() - 1;
 570   // Check if the first 1-3 bytecodes are a constant push
 571   // and the last bytecode is a return.
 572   return (2 <= code_size() && code_size() <= 4 &&
 573           Bytecodes::is_const(java_code_at(0)) &&
 574           Bytecodes::length_for(java_code_at(0)) == last_index &&
 575           Bytecodes::is_return(java_code_at(last_index)));
 576 }
 577 
 578 bool Method::is_initializer() const {
 579   return name() == vmSymbols::object_initializer_name() || is_static_initializer();
 580 }
 581 
 582 bool Method::has_valid_initializer_flags() const {
 583   return (is_static() ||
 584           method_holder()->major_version() < 51);
 585 }
 586 
 587 bool Method::is_static_initializer() const {
 588   // For classfiles version 51 or greater, ensure that the clinit method is
 589   // static.  Non-static methods with the name "<clinit>" are not static
 590   // initializers. (older classfiles exempted for backward compatibility)
 591   return name() == vmSymbols::class_initializer_name() &&
 592          has_valid_initializer_flags();
 593 }
 594 
 595 
 596 objArrayHandle Method::resolved_checked_exceptions_impl(Method* method, TRAPS) {
 597   int length = method->checked_exceptions_length();
 598   if (length == 0) {  // common case
 599     return objArrayHandle(THREAD, Universe::the_empty_class_klass_array());
 600   } else {
 601     methodHandle h_this(THREAD, method);
 602     objArrayOop m_oop = oopFactory::new_objArray(SystemDictionary::Class_klass(), length, CHECK_(objArrayHandle()));
 603     objArrayHandle mirrors (THREAD, m_oop);
 604     for (int i = 0; i < length; i++) {
 605       CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe
 606       Klass* k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle()));
 607       assert(k->is_subclass_of(SystemDictionary::Throwable_klass()), "invalid exception class");
 608       mirrors->obj_at_put(i, k->java_mirror());
 609     }
 610     return mirrors;
 611   }
 612 };
 613 
 614 
 615 int Method::line_number_from_bci(int bci) const {
 616   if (bci == SynchronizationEntryBCI) bci = 0;
 617   assert(bci == 0 || 0 <= bci && bci < code_size(), "illegal bci");
 618   int best_bci  =  0;
 619   int best_line = -1;
 620 
 621   if (has_linenumber_table()) {
 622     // The line numbers are a short array of 2-tuples [start_pc, line_number].
 623     // Not necessarily sorted and not necessarily one-to-one.
 624     CompressedLineNumberReadStream stream(compressed_linenumber_table());
 625     while (stream.read_pair()) {
 626       if (stream.bci() == bci) {
 627         // perfect match
 628         return stream.line();
 629       } else {
 630         // update best_bci/line
 631         if (stream.bci() < bci && stream.bci() >= best_bci) {
 632           best_bci  = stream.bci();
 633           best_line = stream.line();
 634         }
 635       }
 636     }
 637   }
 638   return best_line;
 639 }
 640 
 641 
 642 bool Method::is_klass_loaded_by_klass_index(int klass_index) const {
 643   if( constants()->tag_at(klass_index).is_unresolved_klass() ) {
 644     Thread *thread = Thread::current();
 645     Symbol* klass_name = constants()->klass_name_at(klass_index);
 646     Handle loader(thread, method_holder()->class_loader());
 647     Handle prot  (thread, method_holder()->protection_domain());
 648     return SystemDictionary::find(klass_name, loader, prot, thread) != NULL;
 649   } else {
 650     return true;
 651   }
 652 }
 653 
 654 
 655 bool Method::is_klass_loaded(int refinfo_index, bool must_be_resolved) const {
 656   int klass_index = constants()->klass_ref_index_at(refinfo_index);
 657   if (must_be_resolved) {
 658     // Make sure klass is resolved in constantpool.
 659     if (constants()->tag_at(klass_index).is_unresolved_klass()) return false;
 660   }
 661   return is_klass_loaded_by_klass_index(klass_index);
 662 }
 663 
 664 
 665 void Method::set_native_function(address function, bool post_event_flag) {
 666   assert(function != NULL, "use clear_native_function to unregister natives");
 667   assert(!is_method_handle_intrinsic() || function == SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), "");
 668   address* native_function = native_function_addr();
 669 
 670   // We can see racers trying to place the same native function into place. Once
 671   // is plenty.
 672   address current = *native_function;
 673   if (current == function) return;
 674   if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
 675       function != NULL) {
 676     // native_method_throw_unsatisfied_link_error_entry() should only
 677     // be passed when post_event_flag is false.
 678     assert(function !=
 679       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 680       "post_event_flag mis-match");
 681 
 682     // post the bind event, and possible change the bind function
 683     JvmtiExport::post_native_method_bind(this, &function);
 684   }
 685   *native_function = function;
 686   // This function can be called more than once. We must make sure that we always
 687   // use the latest registered method -> check if a stub already has been generated.
 688   // If so, we have to make it not_entrant.
 689   nmethod* nm = code(); // Put it into local variable to guard against concurrent updates
 690   if (nm != NULL) {
 691     nm->make_not_entrant();
 692   }
 693 }
 694 
 695 
 696 bool Method::has_native_function() const {
 697   if (is_method_handle_intrinsic())
 698     return false;  // special-cased in SharedRuntime::generate_native_wrapper
 699   address func = native_function();
 700   return (func != NULL && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
 701 }
 702 
 703 
 704 void Method::clear_native_function() {
 705   // Note: is_method_handle_intrinsic() is allowed here.
 706   set_native_function(
 707     SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 708     !native_bind_event_is_interesting);
 709   clear_code();
 710 }
 711 
 712 address Method::critical_native_function() {
 713   methodHandle mh(this);
 714   return NativeLookup::lookup_critical_entry(mh);
 715 }
 716 
 717 
 718 void Method::set_signature_handler(address handler) {
 719   address* signature_handler =  signature_handler_addr();
 720   *signature_handler = handler;
 721 }
 722 
 723 
 724 void Method::print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason) {
 725   if (PrintCompilation && report) {
 726     ttyLocker ttyl;
 727     tty->print("made not %scompilable on ", is_osr ? "OSR " : "");
 728     if (comp_level == CompLevel_all) {
 729       tty->print("all levels ");
 730     } else {
 731       tty->print("levels ");
 732       for (int i = (int)CompLevel_none; i <= comp_level; i++) {
 733         tty->print("%d ", i);
 734       }
 735     }
 736     this->print_short_name(tty);
 737     int size = this->code_size();
 738     if (size > 0) {
 739       tty->print(" (%d bytes)", size);
 740     }
 741     if (reason != NULL) {
 742       tty->print("   %s", reason);
 743     }
 744     tty->cr();
 745   }
 746   if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
 747     ttyLocker ttyl;
 748     xtty->begin_elem("make_not_compilable thread='" UINTX_FORMAT "' osr='%d' level='%d'",
 749                      os::current_thread_id(), is_osr, comp_level);
 750     if (reason != NULL) {
 751       xtty->print(" reason=\'%s\'", reason);
 752     }
 753     xtty->method(this);
 754     xtty->stamp();
 755     xtty->end_elem();
 756   }
 757 }
 758 
 759 bool Method::is_always_compilable() const {
 760   // Generated adapters must be compiled
 761   if (is_method_handle_intrinsic() && is_synthetic()) {
 762     assert(!is_not_c1_compilable(), "sanity check");
 763     assert(!is_not_c2_compilable(), "sanity check");
 764     return true;
 765   }
 766 
 767   return false;
 768 }
 769 
 770 bool Method::is_not_compilable(int comp_level) const {
 771   if (number_of_breakpoints() > 0)
 772     return true;
 773   if (is_always_compilable())
 774     return false;
 775   if (comp_level == CompLevel_any)
 776     return is_not_c1_compilable() || is_not_c2_compilable();
 777   if (is_c1_compile(comp_level))
 778     return is_not_c1_compilable();
 779   if (is_c2_compile(comp_level))
 780     return is_not_c2_compilable();
 781   return false;
 782 }
 783 
 784 // call this when compiler finds that this method is not compilable
 785 void Method::set_not_compilable(int comp_level, bool report, const char* reason) {
 786   if (is_always_compilable()) {
 787     // Don't mark a method which should be always compilable
 788     return;
 789   }
 790   print_made_not_compilable(comp_level, /*is_osr*/ false, report, reason);
 791   if (comp_level == CompLevel_all) {
 792     set_not_c1_compilable();
 793     set_not_c2_compilable();
 794   } else {
 795     if (is_c1_compile(comp_level))
 796       set_not_c1_compilable();
 797     if (is_c2_compile(comp_level))
 798       set_not_c2_compilable();
 799   }
 800   CompilationPolicy::policy()->disable_compilation(this);
 801   assert(!CompilationPolicy::can_be_compiled(this, comp_level), "sanity check");
 802 }
 803 
 804 bool Method::is_not_osr_compilable(int comp_level) const {
 805   if (is_not_compilable(comp_level))
 806     return true;
 807   if (comp_level == CompLevel_any)
 808     return is_not_c1_osr_compilable() || is_not_c2_osr_compilable();
 809   if (is_c1_compile(comp_level))
 810     return is_not_c1_osr_compilable();
 811   if (is_c2_compile(comp_level))
 812     return is_not_c2_osr_compilable();
 813   return false;
 814 }
 815 
 816 void Method::set_not_osr_compilable(int comp_level, bool report, const char* reason) {
 817   print_made_not_compilable(comp_level, /*is_osr*/ true, report, reason);
 818   if (comp_level == CompLevel_all) {
 819     set_not_c1_osr_compilable();
 820     set_not_c2_osr_compilable();
 821   } else {
 822     if (is_c1_compile(comp_level))
 823       set_not_c1_osr_compilable();
 824     if (is_c2_compile(comp_level))
 825       set_not_c2_osr_compilable();
 826   }
 827   CompilationPolicy::policy()->disable_compilation(this);
 828   assert(!CompilationPolicy::can_be_osr_compiled(this, comp_level), "sanity check");
 829 }
 830 
 831 // Revert to using the interpreter and clear out the nmethod
 832 void Method::clear_code() {
 833 
 834   // this may be NULL if c2i adapters have not been made yet
 835   // Only should happen at allocate time.
 836   if (_adapter == NULL) {
 837     _from_compiled_entry    = NULL;
 838   } else {
 839     _from_compiled_entry    = _adapter->get_c2i_entry();
 840   }
 841   OrderAccess::storestore();
 842   _from_interpreted_entry = _i2i_entry;
 843   OrderAccess::storestore();
 844   _code = NULL;
 845 }
 846 
 847 // Called by class data sharing to remove any entry points (which are not shared)
 848 void Method::unlink_method() {
 849   _code = NULL;
 850   _i2i_entry = NULL;
 851   _from_interpreted_entry = NULL;
 852   if (is_native()) {
 853     *native_function_addr() = NULL;
 854     set_signature_handler(NULL);
 855   }
 856   NOT_PRODUCT(set_compiled_invocation_count(0);)
 857   _adapter = NULL;
 858   _from_compiled_entry = NULL;
 859 
 860   // In case of DumpSharedSpaces, _method_data should always be NULL.
 861   //
 862   // During runtime (!DumpSharedSpaces), when we are cleaning a
 863   // shared class that failed to load, this->link_method() may
 864   // have already been called (before an exception happened), so
 865   // this->_method_data may not be NULL.
 866   assert(!DumpSharedSpaces || _method_data == NULL, "unexpected method data?");
 867 
 868   set_method_data(NULL);
 869   clear_method_counters();
 870 }
 871 
 872 // Called when the method_holder is getting linked. Setup entrypoints so the method
 873 // is ready to be called from interpreter, compiler, and vtables.
 874 void Method::link_method(methodHandle h_method, TRAPS) {
 875   // If the code cache is full, we may reenter this function for the
 876   // leftover methods that weren't linked.
 877   if (_i2i_entry != NULL) return;
 878 
 879   assert(_adapter == NULL, "init'd to NULL" );
 880   assert( _code == NULL, "nothing compiled yet" );
 881 
 882   // Setup interpreter entrypoint
 883   assert(this == h_method(), "wrong h_method()" );
 884   address entry = Interpreter::entry_for_method(h_method);
 885   assert(entry != NULL, "interpreter entry must be non-null");
 886   // Sets both _i2i_entry and _from_interpreted_entry
 887   set_interpreter_entry(entry);
 888 
 889   // Don't overwrite already registered native entries.
 890   if (is_native() && !has_native_function()) {
 891     set_native_function(
 892       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 893       !native_bind_event_is_interesting);
 894   }
 895 
 896   // Setup compiler entrypoint.  This is made eagerly, so we do not need
 897   // special handling of vtables.  An alternative is to make adapters more
 898   // lazily by calling make_adapter() from from_compiled_entry() for the
 899   // normal calls.  For vtable calls life gets more complicated.  When a
 900   // call-site goes mega-morphic we need adapters in all methods which can be
 901   // called from the vtable.  We need adapters on such methods that get loaded
 902   // later.  Ditto for mega-morphic itable calls.  If this proves to be a
 903   // problem we'll make these lazily later.
 904   (void) make_adapters(h_method, CHECK);
 905 
 906   // ONLY USE the h_method now as make_adapter may have blocked
 907 
 908 }
 909 
 910 address Method::make_adapters(methodHandle mh, TRAPS) {
 911   // Adapters for compiled code are made eagerly here.  They are fairly
 912   // small (generally < 100 bytes) and quick to make (and cached and shared)
 913   // so making them eagerly shouldn't be too expensive.
 914   AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
 915   if (adapter == NULL ) {
 916     THROW_MSG_NULL(vmSymbols::java_lang_VirtualMachineError(), "out of space in CodeCache for adapters");
 917   }
 918 
 919   mh->set_adapter_entry(adapter);
 920   mh->_from_compiled_entry = adapter->get_c2i_entry();
 921   return adapter->get_c2i_entry();
 922 }
 923 
 924 void Method::restore_unshareable_info(TRAPS) {
 925   // Since restore_unshareable_info can be called more than once for a method, don't
 926   // redo any work.   If this field is restored, there is nothing to do.
 927   if (_from_compiled_entry == NULL) {
 928     // restore method's vtable by calling a virtual function
 929     restore_vtable();
 930 
 931     methodHandle mh(THREAD, this);
 932     link_method(mh, CHECK);
 933   }
 934 }
 935 
 936 
 937 // The verified_code_entry() must be called when a invoke is resolved
 938 // on this method.
 939 
 940 // It returns the compiled code entry point, after asserting not null.
 941 // This function is called after potential safepoints so that nmethod
 942 // or adapter that it points to is still live and valid.
 943 // This function must not hit a safepoint!
 944 address Method::verified_code_entry() {
 945   debug_only(No_Safepoint_Verifier nsv;)
 946   assert(_from_compiled_entry != NULL, "must be set");
 947   return _from_compiled_entry;
 948 }
 949 
 950 // Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
 951 // (could be racing a deopt).
 952 // Not inline to avoid circular ref.
 953 bool Method::check_code() const {
 954   // cached in a register or local.  There's a race on the value of the field.
 955   nmethod *code = (nmethod *)OrderAccess::load_ptr_acquire(&_code);
 956   return code == NULL || (code->method() == NULL) || (code->method() == (Method*)this && !code->is_osr_method());
 957 }
 958 
 959 // Install compiled code.  Instantly it can execute.
 960 void Method::set_code(methodHandle mh, nmethod *code) {
 961   assert( code, "use clear_code to remove code" );
 962   assert( mh->check_code(), "" );
 963 
 964   guarantee(mh->adapter() != NULL, "Adapter blob must already exist!");
 965 
 966   // These writes must happen in this order, because the interpreter will
 967   // directly jump to from_interpreted_entry which jumps to an i2c adapter
 968   // which jumps to _from_compiled_entry.
 969   mh->_code = code;             // Assign before allowing compiled code to exec
 970 
 971   int comp_level = code->comp_level();
 972   // In theory there could be a race here. In practice it is unlikely
 973   // and not worth worrying about.
 974   if (comp_level > mh->highest_comp_level()) {
 975     mh->set_highest_comp_level(comp_level);
 976   }
 977 
 978   OrderAccess::storestore();
 979 #ifdef SHARK
 980   mh->_from_interpreted_entry = code->insts_begin();
 981 #else //!SHARK
 982   mh->_from_compiled_entry = code->verified_entry_point();
 983   OrderAccess::storestore();
 984   // Instantly compiled code can execute.
 985   if (!mh->is_method_handle_intrinsic())
 986     mh->_from_interpreted_entry = mh->get_i2c_entry();
 987 #endif //!SHARK
 988 }
 989 
 990 
 991 bool Method::is_overridden_in(Klass* k) const {
 992   InstanceKlass* ik = InstanceKlass::cast(k);
 993 
 994   if (ik->is_interface()) return false;
 995 
 996   // If method is an interface, we skip it - except if it
 997   // is a miranda method
 998   if (method_holder()->is_interface()) {
 999     // Check that method is not a miranda method
1000     if (ik->lookup_method(name(), signature()) == NULL) {
1001       // No implementation exist - so miranda method
1002       return false;
1003     }
1004     return true;
1005   }
1006 
1007   assert(ik->is_subclass_of(method_holder()), "should be subklass");
1008   assert(ik->vtable() != NULL, "vtable should exist");
1009   if (!has_vtable_index()) {
1010     return false;
1011   } else {
1012     Method* vt_m = ik->method_at_vtable(vtable_index());
1013     return vt_m != this;
1014   }
1015 }
1016 
1017 
1018 // give advice about whether this Method* should be cached or not
1019 bool Method::should_not_be_cached() const {
1020   if (is_old()) {
1021     // This method has been redefined. It is either EMCP or obsolete
1022     // and we don't want to cache it because that would pin the method
1023     // down and prevent it from being collectible if and when it
1024     // finishes executing.
1025     return true;
1026   }
1027 
1028   // caching this method should be just fine
1029   return false;
1030 }
1031 
1032 
1033 /**
1034  *  Returns true if this is one of the specially treated methods for
1035  *  security related stack walks (like Reflection.getCallerClass).
1036  */
1037 bool Method::is_ignored_by_security_stack_walk() const {
1038   if (intrinsic_id() == vmIntrinsics::_invoke) {
1039     // This is Method.invoke() -- ignore it
1040     return true;
1041   }
1042   if (method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass())) {
1043     // This is an auxilary frame -- ignore it
1044     return true;
1045   }
1046   if (is_method_handle_intrinsic() || is_compiled_lambda_form()) {
1047     // This is an internal adapter frame for method handles -- ignore it
1048     return true;
1049   }
1050   return false;
1051 }
1052 
1053 
1054 // Constant pool structure for invoke methods:
1055 enum {
1056   _imcp_invoke_name = 1,        // utf8: 'invokeExact', etc.
1057   _imcp_invoke_signature,       // utf8: (variable Symbol*)
1058   _imcp_limit
1059 };
1060 
1061 // Test if this method is an MH adapter frame generated by Java code.
1062 // Cf. java/lang/invoke/InvokerBytecodeGenerator
1063 bool Method::is_compiled_lambda_form() const {
1064   return intrinsic_id() == vmIntrinsics::_compiledLambdaForm;
1065 }
1066 
1067 // Test if this method is an internal MH primitive method.
1068 bool Method::is_method_handle_intrinsic() const {
1069   vmIntrinsics::ID iid = intrinsic_id();
1070   return (MethodHandles::is_signature_polymorphic(iid) &&
1071           MethodHandles::is_signature_polymorphic_intrinsic(iid));
1072 }
1073 
1074 bool Method::has_member_arg() const {
1075   vmIntrinsics::ID iid = intrinsic_id();
1076   return (MethodHandles::is_signature_polymorphic(iid) &&
1077           MethodHandles::has_member_arg(iid));
1078 }
1079 
1080 // Make an instance of a signature-polymorphic internal MH primitive.
1081 methodHandle Method::make_method_handle_intrinsic(vmIntrinsics::ID iid,
1082                                                          Symbol* signature,
1083                                                          TRAPS) {
1084   ResourceMark rm;
1085   methodHandle empty;
1086 
1087   KlassHandle holder = SystemDictionary::MethodHandle_klass();
1088   Symbol* name = MethodHandles::signature_polymorphic_intrinsic_name(iid);
1089   assert(iid == MethodHandles::signature_polymorphic_name_id(name), "");
1090   if (TraceMethodHandles) {
1091     tty->print_cr("make_method_handle_intrinsic MH.%s%s", name->as_C_string(), signature->as_C_string());
1092   }
1093 
1094   // invariant:   cp->symbol_at_put is preceded by a refcount increment (more usually a lookup)
1095   name->increment_refcount();
1096   signature->increment_refcount();
1097 
1098   int cp_length = _imcp_limit;
1099   ClassLoaderData* loader_data = holder->class_loader_data();
1100   constantPoolHandle cp;
1101   {
1102     ConstantPool* cp_oop = ConstantPool::allocate(loader_data, cp_length, CHECK_(empty));
1103     cp = constantPoolHandle(THREAD, cp_oop);
1104   }
1105   cp->set_pool_holder(InstanceKlass::cast(holder()));
1106   cp->symbol_at_put(_imcp_invoke_name,       name);
1107   cp->symbol_at_put(_imcp_invoke_signature,  signature);
1108   cp->set_has_preresolution();
1109 
1110   // decide on access bits:  public or not?
1111   int flags_bits = (JVM_ACC_NATIVE | JVM_ACC_SYNTHETIC | JVM_ACC_FINAL);
1112   bool must_be_static = MethodHandles::is_signature_polymorphic_static(iid);
1113   if (must_be_static)  flags_bits |= JVM_ACC_STATIC;
1114   assert((flags_bits & JVM_ACC_PUBLIC) == 0, "do not expose these methods");
1115 
1116   methodHandle m;
1117   {
1118     InlineTableSizes sizes;
1119     Method* m_oop = Method::allocate(loader_data, 0,
1120                                      accessFlags_from(flags_bits), &sizes,
1121                                      ConstMethod::NORMAL, CHECK_(empty));
1122     m = methodHandle(THREAD, m_oop);
1123   }
1124   m->set_constants(cp());
1125   m->set_name_index(_imcp_invoke_name);
1126   m->set_signature_index(_imcp_invoke_signature);
1127   assert(MethodHandles::is_signature_polymorphic_name(m->name()), "");
1128   assert(m->signature() == signature, "");
1129 #ifdef CC_INTERP
1130   ResultTypeFinder rtf(signature);
1131   m->set_result_index(rtf.type());
1132 #endif
1133   m->compute_size_of_parameters(THREAD);
1134   m->init_intrinsic_id();
1135   assert(m->is_method_handle_intrinsic(), "");
1136 #ifdef ASSERT
1137   if (!MethodHandles::is_signature_polymorphic(m->intrinsic_id()))  m->print();
1138   assert(MethodHandles::is_signature_polymorphic(m->intrinsic_id()), "must be an invoker");
1139   assert(m->intrinsic_id() == iid, "correctly predicted iid");
1140 #endif //ASSERT
1141 
1142   // Finally, set up its entry points.
1143   assert(m->can_be_statically_bound(), "");
1144   m->set_vtable_index(Method::nonvirtual_vtable_index);
1145   m->link_method(m, CHECK_(empty));
1146 
1147   if (TraceMethodHandles && (Verbose || WizardMode))
1148     m->print_on(tty);
1149 
1150   return m;
1151 }
1152 
1153 Klass* Method::check_non_bcp_klass(Klass* klass) {
1154   if (klass != NULL && klass->class_loader() != NULL) {
1155     if (klass->oop_is_objArray())
1156       klass = ObjArrayKlass::cast(klass)->bottom_klass();
1157     return klass;
1158   }
1159   return NULL;
1160 }
1161 
1162 
1163 methodHandle Method::clone_with_new_data(methodHandle m, u_char* new_code, int new_code_length,
1164                                                 u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
1165   // Code below does not work for native methods - they should never get rewritten anyway
1166   assert(!m->is_native(), "cannot rewrite native methods");
1167   // Allocate new Method*
1168   AccessFlags flags = m->access_flags();
1169 
1170   ConstMethod* cm = m->constMethod();
1171   int checked_exceptions_len = cm->checked_exceptions_length();
1172   int localvariable_len = cm->localvariable_table_length();
1173   int exception_table_len = cm->exception_table_length();
1174   int method_parameters_len = cm->method_parameters_length();
1175   int method_annotations_len = cm->method_annotations_length();
1176   int parameter_annotations_len = cm->parameter_annotations_length();
1177   int type_annotations_len = cm->type_annotations_length();
1178   int default_annotations_len = cm->default_annotations_length();
1179 
1180   InlineTableSizes sizes(
1181       localvariable_len,
1182       new_compressed_linenumber_size,
1183       exception_table_len,
1184       checked_exceptions_len,
1185       method_parameters_len,
1186       cm->generic_signature_index(),
1187       method_annotations_len,
1188       parameter_annotations_len,
1189       type_annotations_len,
1190       default_annotations_len,
1191       0);
1192 
1193   ClassLoaderData* loader_data = m->method_holder()->class_loader_data();
1194   Method* newm_oop = Method::allocate(loader_data,
1195                                       new_code_length,
1196                                       flags,
1197                                       &sizes,
1198                                       m->method_type(),
1199                                       CHECK_(methodHandle()));
1200   methodHandle newm (THREAD, newm_oop);
1201   int new_method_size = newm->method_size();
1202 
1203   // Create a shallow copy of Method part, but be careful to preserve the new ConstMethod*
1204   ConstMethod* newcm = newm->constMethod();
1205   int new_const_method_size = newm->constMethod()->size();
1206 
1207   memcpy(newm(), m(), sizeof(Method));
1208 
1209   // Create shallow copy of ConstMethod.
1210   memcpy(newcm, m->constMethod(), sizeof(ConstMethod));
1211 
1212   // Reset correct method/const method, method size, and parameter info
1213   newm->set_constMethod(newcm);
1214   newm->constMethod()->set_code_size(new_code_length);
1215   newm->constMethod()->set_constMethod_size(new_const_method_size);
1216   newm->set_method_size(new_method_size);
1217   assert(newm->code_size() == new_code_length, "check");
1218   assert(newm->method_parameters_length() == method_parameters_len, "check");
1219   assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
1220   assert(newm->exception_table_length() == exception_table_len, "check");
1221   assert(newm->localvariable_table_length() == localvariable_len, "check");
1222   // Copy new byte codes
1223   memcpy(newm->code_base(), new_code, new_code_length);
1224   // Copy line number table
1225   if (new_compressed_linenumber_size > 0) {
1226     memcpy(newm->compressed_linenumber_table(),
1227            new_compressed_linenumber_table,
1228            new_compressed_linenumber_size);
1229   }
1230   // Copy method_parameters
1231   if (method_parameters_len > 0) {
1232     memcpy(newm->method_parameters_start(),
1233            m->method_parameters_start(),
1234            method_parameters_len * sizeof(MethodParametersElement));
1235   }
1236   // Copy checked_exceptions
1237   if (checked_exceptions_len > 0) {
1238     memcpy(newm->checked_exceptions_start(),
1239            m->checked_exceptions_start(),
1240            checked_exceptions_len * sizeof(CheckedExceptionElement));
1241   }
1242   // Copy exception table
1243   if (exception_table_len > 0) {
1244     memcpy(newm->exception_table_start(),
1245            m->exception_table_start(),
1246            exception_table_len * sizeof(ExceptionTableElement));
1247   }
1248   // Copy local variable number table
1249   if (localvariable_len > 0) {
1250     memcpy(newm->localvariable_table_start(),
1251            m->localvariable_table_start(),
1252            localvariable_len * sizeof(LocalVariableTableElement));
1253   }
1254   // Copy stackmap table
1255   if (m->has_stackmap_table()) {
1256     int code_attribute_length = m->stackmap_data()->length();
1257     Array<u1>* stackmap_data =
1258       MetadataFactory::new_array<u1>(loader_data, code_attribute_length, 0, CHECK_NULL);
1259     memcpy((void*)stackmap_data->adr_at(0),
1260            (void*)m->stackmap_data()->adr_at(0), code_attribute_length);
1261     newm->set_stackmap_data(stackmap_data);
1262   }
1263 
1264   // copy annotations over to new method
1265   newcm->copy_annotations_from(cm);
1266   return newm;
1267 }
1268 
1269 vmSymbols::SID Method::klass_id_for_intrinsics(Klass* holder) {
1270   // if loader is not the default loader (i.e., != NULL), we can't know the intrinsics
1271   // because we are not loading from core libraries
1272   // exception: the AES intrinsics come from lib/ext/sunjce_provider.jar
1273   // which does not use the class default class loader so we check for its loader here
1274   InstanceKlass* ik = InstanceKlass::cast(holder);
1275   if ((ik->class_loader() != NULL) && !SystemDictionary::is_ext_class_loader(ik->class_loader())) {
1276     return vmSymbols::NO_SID;   // regardless of name, no intrinsics here
1277   }
1278 
1279   // see if the klass name is well-known:
1280   Symbol* klass_name = ik->name();
1281   return vmSymbols::find_sid(klass_name);
1282 }
1283 
1284 void Method::init_intrinsic_id() {
1285   assert(_intrinsic_id == vmIntrinsics::_none, "do this just once");
1286   const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte));
1287   assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size");
1288   assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), "");
1289 
1290   // the klass name is well-known:
1291   vmSymbols::SID klass_id = klass_id_for_intrinsics(method_holder());
1292   assert(klass_id != vmSymbols::NO_SID, "caller responsibility");
1293 
1294   // ditto for method and signature:
1295   vmSymbols::SID  name_id = vmSymbols::find_sid(name());
1296   if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1297       && name_id == vmSymbols::NO_SID)
1298     return;
1299   vmSymbols::SID   sig_id = vmSymbols::find_sid(signature());
1300   if (klass_id != vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1301       && sig_id == vmSymbols::NO_SID)  return;
1302   jshort flags = access_flags().as_short();
1303 
1304   vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1305   if (id != vmIntrinsics::_none) {
1306     set_intrinsic_id(id);
1307     if (id == vmIntrinsics::_Class_cast) {
1308       // Even if the intrinsic is rejected, we want to inline this simple method.
1309       set_force_inline(true);
1310     }
1311     return;
1312   }
1313 
1314   // A few slightly irregular cases:
1315   switch (klass_id) {
1316   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_StrictMath):
1317     // Second chance: check in regular Math.
1318     switch (name_id) {
1319     case vmSymbols::VM_SYMBOL_ENUM_NAME(min_name):
1320     case vmSymbols::VM_SYMBOL_ENUM_NAME(max_name):
1321     case vmSymbols::VM_SYMBOL_ENUM_NAME(sqrt_name):
1322       // pretend it is the corresponding method in the non-strict class:
1323       klass_id = vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_Math);
1324       id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1325       break;
1326     }
1327     break;
1328 
1329   // Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*.
1330   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle):
1331     if (!is_native())  break;
1332     id = MethodHandles::signature_polymorphic_name_id(method_holder(), name());
1333     if (is_static() != MethodHandles::is_signature_polymorphic_static(id))
1334       id = vmIntrinsics::_none;
1335     break;
1336   }
1337 
1338   if (id != vmIntrinsics::_none) {
1339     // Set up its iid.  It is an alias method.
1340     set_intrinsic_id(id);
1341     return;
1342   }
1343 }
1344 
1345 // These two methods are static since a GC may move the Method
1346 bool Method::load_signature_classes(methodHandle m, TRAPS) {
1347   if (THREAD->is_Compiler_thread()) {
1348     // There is nothing useful this routine can do from within the Compile thread.
1349     // Hopefully, the signature contains only well-known classes.
1350     // We could scan for this and return true/false, but the caller won't care.
1351     return false;
1352   }
1353   bool sig_is_loaded = true;
1354   Handle class_loader(THREAD, m->method_holder()->class_loader());
1355   Handle protection_domain(THREAD, m->method_holder()->protection_domain());
1356   ResourceMark rm(THREAD);
1357   Symbol*  signature = m->signature();
1358   for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
1359     if (ss.is_object()) {
1360       Symbol* sym = ss.as_symbol(CHECK_(false));
1361       Symbol*  name  = sym;
1362       Klass* klass = SystemDictionary::resolve_or_null(name, class_loader,
1363                                              protection_domain, THREAD);
1364       // We are loading classes eagerly. If a ClassNotFoundException or
1365       // a LinkageError was generated, be sure to ignore it.
1366       if (HAS_PENDING_EXCEPTION) {
1367         if (PENDING_EXCEPTION->is_a(SystemDictionary::ClassNotFoundException_klass()) ||
1368             PENDING_EXCEPTION->is_a(SystemDictionary::LinkageError_klass())) {
1369           CLEAR_PENDING_EXCEPTION;
1370         } else {
1371           return false;
1372         }
1373       }
1374       if( klass == NULL) { sig_is_loaded = false; }
1375     }
1376   }
1377   return sig_is_loaded;
1378 }
1379 
1380 bool Method::has_unloaded_classes_in_signature(methodHandle m, TRAPS) {
1381   Handle class_loader(THREAD, m->method_holder()->class_loader());
1382   Handle protection_domain(THREAD, m->method_holder()->protection_domain());
1383   ResourceMark rm(THREAD);
1384   Symbol*  signature = m->signature();
1385   for(SignatureStream ss(signature); !ss.is_done(); ss.next()) {
1386     if (ss.type() == T_OBJECT) {
1387       Symbol* name = ss.as_symbol_or_null();
1388       if (name == NULL) return true;
1389       Klass* klass = SystemDictionary::find(name, class_loader, protection_domain, THREAD);
1390       if (klass == NULL) return true;
1391     }
1392   }
1393   return false;
1394 }
1395 
1396 // Exposed so field engineers can debug VM
1397 void Method::print_short_name(outputStream* st) {
1398   ResourceMark rm;
1399 #ifdef PRODUCT
1400   st->print(" %s::", method_holder()->external_name());
1401 #else
1402   st->print(" %s::", method_holder()->internal_name());
1403 #endif
1404   name()->print_symbol_on(st);
1405   if (WizardMode) signature()->print_symbol_on(st);
1406   else if (MethodHandles::is_signature_polymorphic(intrinsic_id()))
1407     MethodHandles::print_as_basic_type_signature_on(st, signature(), true);
1408 }
1409 
1410 // Comparer for sorting an object array containing
1411 // Method*s.
1412 static int method_comparator(Method* a, Method* b) {
1413   return a->name()->fast_compare(b->name());
1414 }
1415 
1416 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1417 // default_methods also uses this without the ordering for fast find_method
1418 void Method::sort_methods(Array<Method*>* methods, bool idempotent, bool set_idnums) {
1419   int length = methods->length();
1420   if (length > 1) {
1421     {
1422       No_Safepoint_Verifier nsv;
1423       QuickSort::sort<Method*>(methods->data(), length, method_comparator, idempotent);
1424     }
1425     // Reset method ordering
1426     if (set_idnums) {
1427       for (int i = 0; i < length; i++) {
1428         Method* m = methods->at(i);
1429         m->set_method_idnum(i);
1430       }
1431     }
1432   }
1433 }
1434 
1435 //-----------------------------------------------------------------------------------
1436 // Non-product code unless JVM/TI needs it
1437 
1438 #if !defined(PRODUCT) || INCLUDE_JVMTI
1439 class SignatureTypePrinter : public SignatureTypeNames {
1440  private:
1441   outputStream* _st;
1442   bool _use_separator;
1443 
1444   void type_name(const char* name) {
1445     if (_use_separator) _st->print(", ");
1446     _st->print("%s", name);
1447     _use_separator = true;
1448   }
1449 
1450  public:
1451   SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) {
1452     _st = st;
1453     _use_separator = false;
1454   }
1455 
1456   void print_parameters()              { _use_separator = false; iterate_parameters(); }
1457   void print_returntype()              { _use_separator = false; iterate_returntype(); }
1458 };
1459 
1460 
1461 void Method::print_name(outputStream* st) {
1462   Thread *thread = Thread::current();
1463   ResourceMark rm(thread);
1464   SignatureTypePrinter sig(signature(), st);
1465   st->print("%s ", is_static() ? "static" : "virtual");
1466   sig.print_returntype();
1467   st->print(" %s.", method_holder()->internal_name());
1468   name()->print_symbol_on(st);
1469   st->print("(");
1470   sig.print_parameters();
1471   st->print(")");
1472 }
1473 #endif // !PRODUCT || INCLUDE_JVMTI
1474 
1475 
1476 void Method::print_codes_on(outputStream* st) const {
1477   print_codes_on(0, code_size(), st);
1478 }
1479 
1480 void Method::print_codes_on(int from, int to, outputStream* st) const {
1481   Thread *thread = Thread::current();
1482   ResourceMark rm(thread);
1483   methodHandle mh (thread, (Method*)this);
1484   BytecodeStream s(mh);
1485   s.set_interval(from, to);
1486   BytecodeTracer::set_closure(BytecodeTracer::std_closure());
1487   while (s.next() >= 0) BytecodeTracer::trace(mh, s.bcp(), st);
1488 }
1489 
1490 
1491 // Simple compression of line number tables. We use a regular compressed stream, except that we compress deltas
1492 // between (bci,line) pairs since they are smaller. If (bci delta, line delta) fits in (5-bit unsigned, 3-bit unsigned)
1493 // we save it as one byte, otherwise we write a 0xFF escape character and use regular compression. 0x0 is used
1494 // as end-of-stream terminator.
1495 
1496 void CompressedLineNumberWriteStream::write_pair_regular(int bci_delta, int line_delta) {
1497   // bci and line number does not compress into single byte.
1498   // Write out escape character and use regular compression for bci and line number.
1499   write_byte((jubyte)0xFF);
1500   write_signed_int(bci_delta);
1501   write_signed_int(line_delta);
1502 }
1503 
1504 // See comment in method.hpp which explains why this exists.
1505 #if defined(_M_AMD64) && _MSC_VER >= 1400
1506 #pragma optimize("", off)
1507 void CompressedLineNumberWriteStream::write_pair(int bci, int line) {
1508   write_pair_inline(bci, line);
1509 }
1510 #pragma optimize("", on)
1511 #endif
1512 
1513 CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
1514   _bci = 0;
1515   _line = 0;
1516 };
1517 
1518 
1519 bool CompressedLineNumberReadStream::read_pair() {
1520   jubyte next = read_byte();
1521   // Check for terminator
1522   if (next == 0) return false;
1523   if (next == 0xFF) {
1524     // Escape character, regular compression used
1525     _bci  += read_signed_int();
1526     _line += read_signed_int();
1527   } else {
1528     // Single byte compression used
1529     _bci  += next >> 3;
1530     _line += next & 0x7;
1531   }
1532   return true;
1533 }
1534 
1535 
1536 Bytecodes::Code Method::orig_bytecode_at(int bci) const {
1537   BreakpointInfo* bp = method_holder()->breakpoints();
1538   for (; bp != NULL; bp = bp->next()) {
1539     if (bp->match(this, bci)) {
1540       return bp->orig_bytecode();
1541     }
1542   }
1543   {
1544     ResourceMark rm;
1545     fatal(err_msg("no original bytecode found in %s at bci %d", name_and_sig_as_C_string(), bci));
1546   }
1547   return Bytecodes::_shouldnotreachhere;
1548 }
1549 
1550 void Method::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
1551   assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
1552   BreakpointInfo* bp = method_holder()->breakpoints();
1553   for (; bp != NULL; bp = bp->next()) {
1554     if (bp->match(this, bci)) {
1555       bp->set_orig_bytecode(code);
1556       // and continue, in case there is more than one
1557     }
1558   }
1559 }
1560 
1561 void Method::set_breakpoint(int bci) {
1562   InstanceKlass* ik = method_holder();
1563   BreakpointInfo *bp = new BreakpointInfo(this, bci);
1564   bp->set_next(ik->breakpoints());
1565   ik->set_breakpoints(bp);
1566   // do this last:
1567   bp->set(this);
1568 }
1569 
1570 static void clear_matches(Method* m, int bci) {
1571   InstanceKlass* ik = m->method_holder();
1572   BreakpointInfo* prev_bp = NULL;
1573   BreakpointInfo* next_bp;
1574   for (BreakpointInfo* bp = ik->breakpoints(); bp != NULL; bp = next_bp) {
1575     next_bp = bp->next();
1576     // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
1577     if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
1578       // do this first:
1579       bp->clear(m);
1580       // unhook it
1581       if (prev_bp != NULL)
1582         prev_bp->set_next(next_bp);
1583       else
1584         ik->set_breakpoints(next_bp);
1585       delete bp;
1586       // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
1587       // at same location. So we have multiple matching (method_index and bci)
1588       // BreakpointInfo nodes in BreakpointInfo list. We should just delete one
1589       // breakpoint for clear_breakpoint request and keep all other method versions
1590       // BreakpointInfo for future clear_breakpoint request.
1591       // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
1592       // which is being called when class is unloaded. We delete all the Breakpoint
1593       // information for all versions of method. We may not correctly restore the original
1594       // bytecode in all method versions, but that is ok. Because the class is being unloaded
1595       // so these methods won't be used anymore.
1596       if (bci >= 0) {
1597         break;
1598       }
1599     } else {
1600       // This one is a keeper.
1601       prev_bp = bp;
1602     }
1603   }
1604 }
1605 
1606 void Method::clear_breakpoint(int bci) {
1607   assert(bci >= 0, "");
1608   clear_matches(this, bci);
1609 }
1610 
1611 void Method::clear_all_breakpoints() {
1612   clear_matches(this, -1);
1613 }
1614 
1615 
1616 int Method::invocation_count() {
1617   MethodCounters *mcs = method_counters();
1618   if (TieredCompilation) {
1619     MethodData* const mdo = method_data();
1620     if (((mcs != NULL) ? mcs->invocation_counter()->carry() : false) ||
1621         ((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
1622       return InvocationCounter::count_limit;
1623     } else {
1624       return ((mcs != NULL) ? mcs->invocation_counter()->count() : 0) +
1625              ((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
1626     }
1627   } else {
1628     return (mcs == NULL) ? 0 : mcs->invocation_counter()->count();
1629   }
1630 }
1631 
1632 int Method::backedge_count() {
1633   MethodCounters *mcs = method_counters();
1634   if (TieredCompilation) {
1635     MethodData* const mdo = method_data();
1636     if (((mcs != NULL) ? mcs->backedge_counter()->carry() : false) ||
1637         ((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
1638       return InvocationCounter::count_limit;
1639     } else {
1640       return ((mcs != NULL) ? mcs->backedge_counter()->count() : 0) +
1641              ((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
1642     }
1643   } else {
1644     return (mcs == NULL) ? 0 : mcs->backedge_counter()->count();
1645   }
1646 }
1647 
1648 int Method::highest_comp_level() const {
1649   const MethodCounters* mcs = method_counters();
1650   if (mcs != NULL) {
1651     return mcs->highest_comp_level();
1652   } else {
1653     return CompLevel_none;
1654   }
1655 }
1656 
1657 int Method::highest_osr_comp_level() const {
1658   const MethodCounters* mcs = method_counters();
1659   if (mcs != NULL) {
1660     return mcs->highest_osr_comp_level();
1661   } else {
1662     return CompLevel_none;
1663   }
1664 }
1665 
1666 void Method::set_highest_comp_level(int level) {
1667   MethodCounters* mcs = method_counters();
1668   if (mcs != NULL) {
1669     mcs->set_highest_comp_level(level);
1670   }
1671 }
1672 
1673 void Method::set_highest_osr_comp_level(int level) {
1674   MethodCounters* mcs = method_counters();
1675   if (mcs != NULL) {
1676     mcs->set_highest_osr_comp_level(level);
1677   }
1678 }
1679 
1680 BreakpointInfo::BreakpointInfo(Method* m, int bci) {
1681   _bci = bci;
1682   _name_index = m->name_index();
1683   _signature_index = m->signature_index();
1684   _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
1685   if (_orig_bytecode == Bytecodes::_breakpoint)
1686     _orig_bytecode = m->orig_bytecode_at(_bci);
1687   _next = NULL;
1688 }
1689 
1690 void BreakpointInfo::set(Method* method) {
1691 #ifdef ASSERT
1692   {
1693     Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
1694     if (code == Bytecodes::_breakpoint)
1695       code = method->orig_bytecode_at(_bci);
1696     assert(orig_bytecode() == code, "original bytecode must be the same");
1697   }
1698 #endif
1699   Thread *thread = Thread::current();
1700   *method->bcp_from(_bci) = Bytecodes::_breakpoint;
1701   method->incr_number_of_breakpoints(thread);
1702   SystemDictionary::notice_modification();
1703   {
1704     // Deoptimize all dependents on this method
1705     HandleMark hm(thread);
1706     methodHandle mh(thread, method);
1707     Universe::flush_dependents_on_method(mh);
1708   }
1709 }
1710 
1711 void BreakpointInfo::clear(Method* method) {
1712   *method->bcp_from(_bci) = orig_bytecode();
1713   assert(method->number_of_breakpoints() > 0, "must not go negative");
1714   method->decr_number_of_breakpoints(Thread::current());
1715 }
1716 
1717 // jmethodID handling
1718 
1719 // This is a block allocating object, sort of like JNIHandleBlock, only a
1720 // lot simpler.  There aren't many of these, they aren't long, they are rarely
1721 // deleted and so we can do some suboptimal things.
1722 // It's allocated on the CHeap because once we allocate a jmethodID, we can
1723 // never get rid of it.
1724 // It would be nice to be able to parameterize the number of methods for
1725 // the null_class_loader but then we'd have to turn this and ClassLoaderData
1726 // into templates.
1727 
1728 // I feel like this brain dead class should exist somewhere in the STL
1729 
1730 class JNIMethodBlock : public CHeapObj<mtClass> {
1731   enum { number_of_methods = 8 };
1732 
1733   Method*         _methods[number_of_methods];
1734   int             _top;
1735   JNIMethodBlock* _next;
1736  public:
1737   static Method* const _free_method;
1738 
1739   JNIMethodBlock() : _next(NULL), _top(0) {
1740     for (int i = 0; i< number_of_methods; i++) _methods[i] = _free_method;
1741   }
1742 
1743   Method** add_method(Method* m) {
1744     if (_top < number_of_methods) {
1745       // top points to the next free entry.
1746       int i = _top;
1747       _methods[i] = m;
1748       _top++;
1749       return &_methods[i];
1750     } else if (_top == number_of_methods) {
1751       // if the next free entry ran off the block see if there's a free entry
1752       for (int i = 0; i< number_of_methods; i++) {
1753         if (_methods[i] == _free_method) {
1754           _methods[i] = m;
1755           return &_methods[i];
1756         }
1757       }
1758       // Only check each block once for frees.  They're very unlikely.
1759       // Increment top past the end of the block.
1760       _top++;
1761     }
1762     // need to allocate a next block.
1763     if (_next == NULL) {
1764       _next = new JNIMethodBlock();
1765     }
1766     return _next->add_method(m);
1767   }
1768 
1769   bool contains(Method** m) {
1770     for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
1771       for (int i = 0; i< number_of_methods; i++) {
1772         if (&(b->_methods[i]) == m) {
1773           return true;
1774         }
1775       }
1776     }
1777     return false;  // not found
1778   }
1779 
1780   // Doesn't really destroy it, just marks it as free so it can be reused.
1781   void destroy_method(Method** m) {
1782 #ifdef ASSERT
1783     assert(contains(m), "should be a methodID");
1784 #endif // ASSERT
1785     *m = _free_method;
1786   }
1787 
1788   // During class unloading the methods are cleared, which is different
1789   // than freed.
1790   void clear_all_methods() {
1791     for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
1792       for (int i = 0; i< number_of_methods; i++) {
1793         _methods[i] = NULL;
1794       }
1795     }
1796   }
1797 #ifndef PRODUCT
1798   int count_methods() {
1799     // count all allocated methods
1800     int count = 0;
1801     for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
1802       for (int i = 0; i< number_of_methods; i++) {
1803         if (_methods[i] != _free_method) count++;
1804       }
1805     }
1806     return count;
1807   }
1808 #endif // PRODUCT
1809 };
1810 
1811 // Something that can't be mistaken for an address or a markOop
1812 Method* const JNIMethodBlock::_free_method = (Method*)55;
1813 
1814 // Add a method id to the jmethod_ids
1815 jmethodID Method::make_jmethod_id(ClassLoaderData* loader_data, Method* m) {
1816   ClassLoaderData* cld = loader_data;
1817 
1818   if (!SafepointSynchronize::is_at_safepoint()) {
1819     // Have to add jmethod_ids() to class loader data thread-safely.
1820     // Also have to add the method to the list safely, which the cld lock
1821     // protects as well.
1822     MutexLockerEx ml(cld->metaspace_lock(),  Mutex::_no_safepoint_check_flag);
1823     if (cld->jmethod_ids() == NULL) {
1824       cld->set_jmethod_ids(new JNIMethodBlock());
1825     }
1826     // jmethodID is a pointer to Method*
1827     return (jmethodID)cld->jmethod_ids()->add_method(m);
1828   } else {
1829     // At safepoint, we are single threaded and can set this.
1830     if (cld->jmethod_ids() == NULL) {
1831       cld->set_jmethod_ids(new JNIMethodBlock());
1832     }
1833     // jmethodID is a pointer to Method*
1834     return (jmethodID)cld->jmethod_ids()->add_method(m);
1835   }
1836 }
1837 
1838 // Mark a jmethodID as free.  This is called when there is a data race in
1839 // InstanceKlass while creating the jmethodID cache.
1840 void Method::destroy_jmethod_id(ClassLoaderData* loader_data, jmethodID m) {
1841   ClassLoaderData* cld = loader_data;
1842   Method** ptr = (Method**)m;
1843   assert(cld->jmethod_ids() != NULL, "should have method handles");
1844   cld->jmethod_ids()->destroy_method(ptr);
1845 }
1846 
1847 void Method::change_method_associated_with_jmethod_id(jmethodID jmid, Method* new_method) {
1848   // Can't assert the method_holder is the same because the new method has the
1849   // scratch method holder.
1850   assert(resolve_jmethod_id(jmid)->method_holder()->class_loader()
1851            == new_method->method_holder()->class_loader(),
1852          "changing to a different class loader");
1853   // Just change the method in place, jmethodID pointer doesn't change.
1854   *((Method**)jmid) = new_method;
1855 }
1856 
1857 bool Method::is_method_id(jmethodID mid) {
1858   Method* m = resolve_jmethod_id(mid);
1859   assert(m != NULL, "should be called with non-null method");
1860   InstanceKlass* ik = m->method_holder();
1861   ClassLoaderData* cld = ik->class_loader_data();
1862   if (cld->jmethod_ids() == NULL) return false;
1863   return (cld->jmethod_ids()->contains((Method**)mid));
1864 }
1865 
1866 Method* Method::checked_resolve_jmethod_id(jmethodID mid) {
1867   if (mid == NULL) return NULL;
1868   Method* o = resolve_jmethod_id(mid);
1869   if (o == NULL || o == JNIMethodBlock::_free_method || !((Metadata*)o)->is_method()) {
1870     return NULL;
1871   }
1872   return o;
1873 };
1874 
1875 void Method::set_on_stack(const bool value) {
1876   // Set both the method itself and its constant pool.  The constant pool
1877   // on stack means some method referring to it is also on the stack.
1878   constants()->set_on_stack(value);
1879 
1880   bool succeeded = _access_flags.set_on_stack(value);
1881   if (value && succeeded) {
1882     MetadataOnStackMark::record(this, Thread::current());
1883   }
1884 }
1885 
1886 // Called when the class loader is unloaded to make all methods weak.
1887 void Method::clear_jmethod_ids(ClassLoaderData* loader_data) {
1888   loader_data->jmethod_ids()->clear_all_methods();
1889 }
1890 
1891 bool Method::has_method_vptr(const void* ptr) {
1892   Method m;
1893   // This assumes that the vtbl pointer is the first word of a C++ object.
1894   // This assumption is also in universe.cpp patch_klass_vtble
1895   void* vtbl2 = dereference_vptr((const void*)&m);
1896   void* this_vtbl = dereference_vptr(ptr);
1897   return vtbl2 == this_vtbl;
1898 }
1899 
1900 // Check that this pointer is valid by checking that the vtbl pointer matches
1901 bool Method::is_valid_method() const {
1902   if (this == NULL) {
1903     return false;
1904   } else if (!is_metaspace_object()) {
1905     return false;
1906   } else {
1907     return has_method_vptr((const void*)this);
1908   }
1909 }
1910 
1911 #ifndef PRODUCT
1912 void Method::print_jmethod_ids(ClassLoaderData* loader_data, outputStream* out) {
1913   out->print_cr("jni_method_id count = %d", loader_data->jmethod_ids()->count_methods());
1914 }
1915 #endif // PRODUCT
1916 
1917 
1918 // Printing
1919 
1920 #ifndef PRODUCT
1921 
1922 void Method::print_on(outputStream* st) const {
1923   ResourceMark rm;
1924   assert(is_method(), "must be method");
1925   st->print_cr("%s", internal_name());
1926   // get the effect of PrintOopAddress, always, for methods:
1927   st->print_cr(" - this oop:          "INTPTR_FORMAT, (intptr_t)this);
1928   st->print   (" - method holder:     "); method_holder()->print_value_on(st); st->cr();
1929   st->print   (" - constants:         "INTPTR_FORMAT" ", (address)constants());
1930   constants()->print_value_on(st); st->cr();
1931   st->print   (" - access:            0x%x  ", access_flags().as_int()); access_flags().print_on(st); st->cr();
1932   st->print   (" - name:              ");    name()->print_value_on(st); st->cr();
1933   st->print   (" - signature:         ");    signature()->print_value_on(st); st->cr();
1934   st->print_cr(" - max stack:         %d",   max_stack());
1935   st->print_cr(" - max locals:        %d",   max_locals());
1936   st->print_cr(" - size of params:    %d",   size_of_parameters());
1937   st->print_cr(" - method size:       %d",   method_size());
1938   if (intrinsic_id() != vmIntrinsics::_none)
1939     st->print_cr(" - intrinsic id:      %d %s", intrinsic_id(), vmIntrinsics::name_at(intrinsic_id()));
1940   if (highest_comp_level() != CompLevel_none)
1941     st->print_cr(" - highest level:     %d", highest_comp_level());
1942   st->print_cr(" - vtable index:      %d",   _vtable_index);
1943   st->print_cr(" - i2i entry:         " INTPTR_FORMAT, interpreter_entry());
1944   st->print(   " - adapters:          ");
1945   AdapterHandlerEntry* a = ((Method*)this)->adapter();
1946   if (a == NULL)
1947     st->print_cr(INTPTR_FORMAT, a);
1948   else
1949     a->print_adapter_on(st);
1950   st->print_cr(" - compiled entry     " INTPTR_FORMAT, from_compiled_entry());
1951   st->print_cr(" - code size:         %d",   code_size());
1952   if (code_size() != 0) {
1953     st->print_cr(" - code start:        " INTPTR_FORMAT, code_base());
1954     st->print_cr(" - code end (excl):   " INTPTR_FORMAT, code_base() + code_size());
1955   }
1956   if (method_data() != NULL) {
1957     st->print_cr(" - method data:       " INTPTR_FORMAT, (address)method_data());
1958   }
1959   st->print_cr(" - checked ex length: %d",   checked_exceptions_length());
1960   if (checked_exceptions_length() > 0) {
1961     CheckedExceptionElement* table = checked_exceptions_start();
1962     st->print_cr(" - checked ex start:  " INTPTR_FORMAT, table);
1963     if (Verbose) {
1964       for (int i = 0; i < checked_exceptions_length(); i++) {
1965         st->print_cr("   - throws %s", constants()->printable_name_at(table[i].class_cp_index));
1966       }
1967     }
1968   }
1969   if (has_linenumber_table()) {
1970     u_char* table = compressed_linenumber_table();
1971     st->print_cr(" - linenumber start:  " INTPTR_FORMAT, table);
1972     if (Verbose) {
1973       CompressedLineNumberReadStream stream(table);
1974       while (stream.read_pair()) {
1975         st->print_cr("   - line %d: %d", stream.line(), stream.bci());
1976       }
1977     }
1978   }
1979   st->print_cr(" - localvar length:   %d",   localvariable_table_length());
1980   if (localvariable_table_length() > 0) {
1981     LocalVariableTableElement* table = localvariable_table_start();
1982     st->print_cr(" - localvar start:    " INTPTR_FORMAT, table);
1983     if (Verbose) {
1984       for (int i = 0; i < localvariable_table_length(); i++) {
1985         int bci = table[i].start_bci;
1986         int len = table[i].length;
1987         const char* name = constants()->printable_name_at(table[i].name_cp_index);
1988         const char* desc = constants()->printable_name_at(table[i].descriptor_cp_index);
1989         int slot = table[i].slot;
1990         st->print_cr("   - %s %s bci=%d len=%d slot=%d", desc, name, bci, len, slot);
1991       }
1992     }
1993   }
1994   if (code() != NULL) {
1995     st->print   (" - compiled code: ");
1996     code()->print_value_on(st);
1997   }
1998   if (is_native()) {
1999     st->print_cr(" - native function:   " INTPTR_FORMAT, native_function());
2000     st->print_cr(" - signature handler: " INTPTR_FORMAT, signature_handler());
2001   }
2002 }
2003 
2004 #endif //PRODUCT
2005 
2006 void Method::print_value_on(outputStream* st) const {
2007   assert(is_method(), "must be method");
2008   st->print("%s", internal_name());
2009   print_address_on(st);
2010   st->print(" ");
2011   name()->print_value_on(st);
2012   st->print(" ");
2013   signature()->print_value_on(st);
2014   st->print(" in ");
2015   method_holder()->print_value_on(st);
2016   if (WizardMode) st->print("#%d", _vtable_index);
2017   if (WizardMode) st->print("[%d,%d]", size_of_parameters(), max_locals());
2018   if (WizardMode && code() != NULL) st->print(" ((nmethod*)%p)", code());
2019 }
2020 
2021 #if INCLUDE_SERVICES
2022 // Size Statistics
2023 void Method::collect_statistics(KlassSizeStats *sz) const {
2024   int mysize = sz->count(this);
2025   sz->_method_bytes += mysize;
2026   sz->_method_all_bytes += mysize;
2027   sz->_rw_bytes += mysize;
2028 
2029   if (constMethod()) {
2030     constMethod()->collect_statistics(sz);
2031   }
2032   if (method_data()) {
2033     method_data()->collect_statistics(sz);
2034   }
2035 }
2036 #endif // INCLUDE_SERVICES
2037 
2038 // Verification
2039 
2040 void Method::verify_on(outputStream* st) {
2041   guarantee(is_method(), "object must be method");
2042   guarantee(constants()->is_constantPool(), "should be constant pool");
2043   guarantee(constMethod()->is_constMethod(), "should be ConstMethod*");
2044   MethodData* md = method_data();
2045   guarantee(md == NULL ||
2046       md->is_methodData(), "should be method data");
2047 }