1 /*
   2  * Copyright (c) 1997, 2024, 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 "cds/cdsConfig.hpp"
  27 #include "cds/cppVtables.hpp"
  28 #include "cds/metaspaceShared.hpp"
  29 #include "classfile/classLoaderDataGraph.hpp"
  30 #include "classfile/metadataOnStackMark.hpp"
  31 #include "classfile/symbolTable.hpp"
  32 #include "classfile/systemDictionary.hpp"
  33 #include "classfile/vmClasses.hpp"
  34 #include "code/codeCache.hpp"
  35 #include "code/debugInfoRec.hpp"
  36 #include "compiler/compilationPolicy.hpp"
  37 #include "gc/shared/collectedHeap.inline.hpp"
  38 #include "interpreter/bytecodeStream.hpp"
  39 #include "interpreter/bytecodeTracer.hpp"
  40 #include "interpreter/bytecodes.hpp"
  41 #include "interpreter/interpreter.hpp"
  42 #include "interpreter/oopMapCache.hpp"
  43 #include "logging/log.hpp"
  44 #include "logging/logStream.hpp"
  45 #include "logging/logTag.hpp"
  46 #include "memory/allocation.inline.hpp"
  47 #include "memory/metadataFactory.hpp"
  48 #include "memory/metaspaceClosure.hpp"
  49 #include "memory/oopFactory.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "memory/universe.hpp"
  52 #include "nmt/memTracker.hpp"
  53 #include "oops/constMethod.hpp"
  54 #include "oops/constantPool.hpp"
  55 #include "oops/klass.inline.hpp"
  56 #include "oops/method.inline.hpp"
  57 #include "oops/methodData.hpp"
  58 #include "oops/objArrayKlass.hpp"
  59 #include "oops/objArrayOop.inline.hpp"
  60 #include "oops/oop.inline.hpp"
  61 #include "oops/symbol.hpp"
  62 #include "prims/jvmtiExport.hpp"
  63 #include "prims/methodHandles.hpp"
  64 #include "runtime/atomic.hpp"
  65 #include "runtime/continuationEntry.hpp"
  66 #include "runtime/frame.inline.hpp"
  67 #include "runtime/handles.inline.hpp"
  68 #include "runtime/init.hpp"
  69 #include "runtime/java.hpp"
  70 #include "runtime/orderAccess.hpp"
  71 #include "runtime/relocator.hpp"
  72 #include "runtime/safepointVerifiers.hpp"
  73 #include "runtime/sharedRuntime.hpp"
  74 #include "runtime/signature.hpp"
  75 #include "runtime/threads.hpp"
  76 #include "runtime/vm_version.hpp"
  77 #include "utilities/align.hpp"
  78 #include "utilities/quickSort.hpp"
  79 #include "utilities/vmError.hpp"
  80 #include "utilities/xmlstream.hpp"
  81 
  82 // Implementation of Method
  83 
  84 Method* Method::allocate(ClassLoaderData* loader_data,
  85                          int byte_code_size,
  86                          AccessFlags access_flags,
  87                          InlineTableSizes* sizes,
  88                          ConstMethod::MethodType method_type,
  89                          Symbol* name,
  90                          TRAPS) {
  91   assert(!access_flags.is_native() || byte_code_size == 0,
  92          "native methods should not contain byte codes");
  93   ConstMethod* cm = ConstMethod::allocate(loader_data,
  94                                           byte_code_size,
  95                                           sizes,
  96                                           method_type,
  97                                           CHECK_NULL);
  98   int size = Method::size(access_flags.is_native());
  99   return new (loader_data, size, MetaspaceObj::MethodType, THREAD) Method(cm, access_flags, name);
 100 }
 101 
 102 Method::Method(ConstMethod* xconst, AccessFlags access_flags, Symbol* name) {
 103   NoSafepointVerifier no_safepoint;
 104   set_constMethod(xconst);
 105   set_access_flags(access_flags);
 106   set_intrinsic_id(vmIntrinsics::_none);
 107   clear_method_data();
 108   clear_method_counters();
 109   set_vtable_index(Method::garbage_vtable_index);
 110 
 111   // Fix and bury in Method*
 112   set_interpreter_entry(nullptr); // sets i2i entry and from_int
 113   set_adapter_entry(nullptr);
 114   Method::clear_code(); // from_c/from_i get set to c2i/i2i
 115 
 116   if (access_flags.is_native()) {
 117     clear_native_function();
 118     set_signature_handler(nullptr);
 119   }
 120 
 121   NOT_PRODUCT(set_compiled_invocation_count(0);)
 122   // Name is very useful for debugging.
 123   NOT_PRODUCT(_name = name;)
 124 }
 125 
 126 // Release Method*.  The nmethod will be gone when we get here because
 127 // we've walked the code cache.
 128 void Method::deallocate_contents(ClassLoaderData* loader_data) {
 129   MetadataFactory::free_metadata(loader_data, constMethod());
 130   set_constMethod(nullptr);
 131   MetadataFactory::free_metadata(loader_data, method_data());
 132   clear_method_data();
 133   MetadataFactory::free_metadata(loader_data, method_counters());
 134   clear_method_counters();
 135   // The nmethod will be gone when we get here.
 136   if (code() != nullptr) _code = nullptr;
 137 }
 138 
 139 void Method::release_C_heap_structures() {
 140   if (method_data()) {
 141     method_data()->release_C_heap_structures();
 142 
 143     // Destroy MethodData embedded lock
 144     method_data()->~MethodData();
 145   }
 146 }
 147 
 148 address Method::get_i2c_entry() {
 149   assert(adapter() != nullptr, "must have");
 150   return adapter()->get_i2c_entry();
 151 }
 152 
 153 address Method::get_c2i_entry() {
 154   assert(adapter() != nullptr, "must have");
 155   return adapter()->get_c2i_entry();
 156 }
 157 
 158 address Method::get_c2i_unverified_entry() {
 159   assert(adapter() != nullptr, "must have");
 160   return adapter()->get_c2i_unverified_entry();
 161 }
 162 
 163 address Method::get_c2i_no_clinit_check_entry() {
 164   assert(VM_Version::supports_fast_class_init_checks(), "");
 165   assert(adapter() != nullptr, "must have");
 166   return adapter()->get_c2i_no_clinit_check_entry();
 167 }
 168 
 169 char* Method::name_and_sig_as_C_string() const {
 170   return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature());
 171 }
 172 
 173 char* Method::name_and_sig_as_C_string(char* buf, int size) const {
 174   return name_and_sig_as_C_string(constants()->pool_holder(), name(), signature(), buf, size);
 175 }
 176 
 177 char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature) {
 178   const char* klass_name = klass->external_name();
 179   int klass_name_len  = (int)strlen(klass_name);
 180   int method_name_len = method_name->utf8_length();
 181   int len             = klass_name_len + 1 + method_name_len + signature->utf8_length();
 182   char* dest          = NEW_RESOURCE_ARRAY(char, len + 1);
 183   strcpy(dest, klass_name);
 184   dest[klass_name_len] = '.';
 185   strcpy(&dest[klass_name_len + 1], method_name->as_C_string());
 186   strcpy(&dest[klass_name_len + 1 + method_name_len], signature->as_C_string());
 187   dest[len] = 0;
 188   return dest;
 189 }
 190 
 191 char* Method::name_and_sig_as_C_string(Klass* klass, Symbol* method_name, Symbol* signature, char* buf, int size) {
 192   Symbol* klass_name = klass->name();
 193   klass_name->as_klass_external_name(buf, size);
 194   int len = (int)strlen(buf);
 195 
 196   if (len < size - 1) {
 197     buf[len++] = '.';
 198 
 199     method_name->as_C_string(&(buf[len]), size - len);
 200     len = (int)strlen(buf);
 201 
 202     signature->as_C_string(&(buf[len]), size - len);
 203   }
 204 
 205   return buf;
 206 }
 207 
 208 const char* Method::external_name() const {
 209   return external_name(constants()->pool_holder(), name(), signature());
 210 }
 211 
 212 void Method::print_external_name(outputStream *os) const {
 213   print_external_name(os, constants()->pool_holder(), name(), signature());
 214 }
 215 
 216 const char* Method::external_name(Klass* klass, Symbol* method_name, Symbol* signature) {
 217   stringStream ss;
 218   print_external_name(&ss, klass, method_name, signature);
 219   return ss.as_string();
 220 }
 221 
 222 void Method::print_external_name(outputStream *os, Klass* klass, Symbol* method_name, Symbol* signature) {
 223   signature->print_as_signature_external_return_type(os);
 224   os->print(" %s.%s(", klass->external_name(), method_name->as_C_string());
 225   signature->print_as_signature_external_parameters(os);
 226   os->print(")");
 227 }
 228 
 229 int Method::fast_exception_handler_bci_for(const methodHandle& mh, Klass* ex_klass, int throw_bci, TRAPS) {
 230   if (log_is_enabled(Debug, exceptions)) {
 231     ResourceMark rm(THREAD);
 232     log_debug(exceptions)("Looking for catch handler for exception of type \"%s\" in method \"%s\"",
 233                           ex_klass == nullptr ? "null" : ex_klass->external_name(), mh->name()->as_C_string());
 234   }
 235   // exception table holds quadruple entries of the form (beg_bci, end_bci, handler_bci, klass_index)
 236   // access exception table
 237   ExceptionTable table(mh());
 238   int length = table.length();
 239   // iterate through all entries sequentially
 240   constantPoolHandle pool(THREAD, mh->constants());
 241   for (int i = 0; i < length; i ++) {
 242     //reacquire the table in case a GC happened
 243     ExceptionTable table(mh());
 244     int beg_bci = table.start_pc(i);
 245     int end_bci = table.end_pc(i);
 246     assert(beg_bci <= end_bci, "inconsistent exception table");
 247     log_debug(exceptions)("  - checking exception table entry for BCI %d to %d",
 248                          beg_bci, end_bci);
 249 
 250     if (beg_bci <= throw_bci && throw_bci < end_bci) {
 251       // exception handler bci range covers throw_bci => investigate further
 252       log_debug(exceptions)("    - entry covers throw point BCI %d", throw_bci);
 253 
 254       int handler_bci = table.handler_pc(i);
 255       int klass_index = table.catch_type_index(i);
 256       if (klass_index == 0) {
 257         if (log_is_enabled(Info, exceptions)) {
 258           ResourceMark rm(THREAD);
 259           log_info(exceptions)("Found catch-all handler for exception of type \"%s\" in method \"%s\" at BCI: %d",
 260                                ex_klass == nullptr ? "null" : ex_klass->external_name(), mh->name()->as_C_string(), handler_bci);
 261         }
 262         return handler_bci;
 263       } else if (ex_klass == nullptr) {
 264         // Is this even possible?
 265         if (log_is_enabled(Info, exceptions)) {
 266           ResourceMark rm(THREAD);
 267           log_info(exceptions)("null exception class is implicitly caught by handler in method \"%s\" at BCI: %d",
 268                                mh()->name()->as_C_string(), handler_bci);
 269         }
 270         return handler_bci;
 271       } else {
 272         if (log_is_enabled(Debug, exceptions)) {
 273           ResourceMark rm(THREAD);
 274           log_debug(exceptions)("    - resolving catch type \"%s\"",
 275                                pool->klass_name_at(klass_index)->as_C_string());
 276         }
 277         // we know the exception class => get the constraint class
 278         // this may require loading of the constraint class; if verification
 279         // fails or some other exception occurs, return handler_bci
 280         Klass* k = pool->klass_at(klass_index, THREAD);
 281         if (HAS_PENDING_EXCEPTION) {
 282           if (log_is_enabled(Debug, exceptions)) {
 283             ResourceMark rm(THREAD);
 284             log_debug(exceptions)("    - exception \"%s\" occurred resolving catch type",
 285                                  PENDING_EXCEPTION->klass()->external_name());
 286           }
 287           return handler_bci;
 288         }
 289         assert(k != nullptr, "klass not loaded");
 290         if (ex_klass->is_subtype_of(k)) {
 291           if (log_is_enabled(Info, exceptions)) {
 292             ResourceMark rm(THREAD);
 293             log_info(exceptions)("Found matching handler for exception of type \"%s\" in method \"%s\" at BCI: %d",
 294                                  ex_klass == nullptr ? "null" : ex_klass->external_name(), mh->name()->as_C_string(), handler_bci);
 295           }
 296           return handler_bci;
 297         }
 298       }
 299     }
 300   }
 301 
 302   if (log_is_enabled(Debug, exceptions)) {
 303     ResourceMark rm(THREAD);
 304     log_debug(exceptions)("No catch handler found for exception of type \"%s\" in method \"%s\"",
 305                           ex_klass->external_name(), mh->name()->as_C_string());
 306   }
 307 
 308   return -1;
 309 }
 310 
 311 void Method::mask_for(int bci, InterpreterOopMap* mask) {
 312   methodHandle h_this(Thread::current(), this);
 313   mask_for(h_this, bci, mask);
 314 }
 315 
 316 void Method::mask_for(const methodHandle& this_mh, int bci, InterpreterOopMap* mask) {
 317   assert(this_mh() == this, "Sanity");
 318   method_holder()->mask_for(this_mh, bci, mask);
 319 }
 320 
 321 int Method::bci_from(address bcp) const {
 322   if (is_native() && bcp == 0) {
 323     return 0;
 324   }
 325   // Do not have a ResourceMark here because AsyncGetCallTrace stack walking code
 326   // may call this after interrupting a nested ResourceMark.
 327   assert((is_native() && bcp == code_base()) || contains(bcp) || VMError::is_error_reported(),
 328          "bcp doesn't belong to this method. bcp: " PTR_FORMAT, p2i(bcp));
 329 
 330   return int(bcp - code_base());
 331 }
 332 
 333 
 334 int Method::validate_bci(int bci) const {
 335   return (bci == 0 || bci < code_size()) ? bci : -1;
 336 }
 337 
 338 // Return bci if it appears to be a valid bcp
 339 // Return -1 otherwise.
 340 // Used by profiling code, when invalid data is a possibility.
 341 // The caller is responsible for validating the Method* itself.
 342 int Method::validate_bci_from_bcp(address bcp) const {
 343   // keep bci as -1 if not a valid bci
 344   int bci = -1;
 345   if (bcp == 0 || bcp == code_base()) {
 346     // code_size() may return 0 and we allow 0 here
 347     // the method may be native
 348     bci = 0;
 349   } else if (contains(bcp)) {
 350     bci = int(bcp - code_base());
 351   }
 352   // Assert that if we have dodged any asserts, bci is negative.
 353   assert(bci == -1 || bci == bci_from(bcp_from(bci)), "sane bci if >=0");
 354   return bci;
 355 }
 356 
 357 address Method::bcp_from(int bci) const {
 358   assert((is_native() && bci == 0) || (!is_native() && 0 <= bci && bci < code_size()),
 359          "illegal bci: %d for %s method", bci, is_native() ? "native" : "non-native");
 360   address bcp = code_base() + bci;
 361   assert((is_native() && bcp == code_base()) || contains(bcp), "bcp doesn't belong to this method");
 362   return bcp;
 363 }
 364 
 365 address Method::bcp_from(address bcp) const {
 366   if (is_native() && bcp == nullptr) {
 367     return code_base();
 368   } else {
 369     return bcp;
 370   }
 371 }
 372 
 373 int Method::size(bool is_native) {
 374   // If native, then include pointers for native_function and signature_handler
 375   int extra_bytes = (is_native) ? 2*sizeof(address*) : 0;
 376   int extra_words = align_up(extra_bytes, BytesPerWord) / BytesPerWord;
 377   return align_metadata_size(header_size() + extra_words);
 378 }
 379 
 380 Symbol* Method::klass_name() const {
 381   return method_holder()->name();
 382 }
 383 
 384 void Method::metaspace_pointers_do(MetaspaceClosure* it) {
 385   log_trace(cds)("Iter(Method): %p", this);
 386 
 387   if (!method_holder()->is_rewritten()) {
 388     it->push(&_constMethod, MetaspaceClosure::_writable);
 389   } else {
 390     it->push(&_constMethod);
 391   }
 392   it->push(&_method_data);
 393   it->push(&_method_counters);
 394   NOT_PRODUCT(it->push(&_name);)
 395 }
 396 
 397 #if INCLUDE_CDS
 398 // Attempt to return method to original state.  Clear any pointers
 399 // (to objects outside the shared spaces).  We won't be able to predict
 400 // where they should point in a new JVM.  Further initialize some
 401 // entries now in order allow them to be write protected later.
 402 
 403 void Method::remove_unshareable_info() {
 404   unlink_method();
 405   JFR_ONLY(REMOVE_METHOD_ID(this);)
 406 }
 407 
 408 void Method::restore_unshareable_info(TRAPS) {
 409   assert(is_method() && is_valid_method(this), "ensure C++ vtable is restored");
 410   assert(!queued_for_compilation(), "method's queued_for_compilation flag should not be set");
 411 }
 412 #endif
 413 
 414 void Method::set_vtable_index(int index) {
 415   if (is_shared() && !MetaspaceShared::remapped_readwrite() && method_holder()->verified_at_dump_time()) {
 416     // At runtime initialize_vtable is rerun as part of link_class_impl()
 417     // for a shared class loaded by the non-boot loader to obtain the loader
 418     // constraints based on the runtime classloaders' context.
 419     return; // don't write into the shared class
 420   } else {
 421     _vtable_index = index;
 422   }
 423 }
 424 
 425 void Method::set_itable_index(int index) {
 426   if (is_shared() && !MetaspaceShared::remapped_readwrite() && method_holder()->verified_at_dump_time()) {
 427     // At runtime initialize_itable is rerun as part of link_class_impl()
 428     // for a shared class loaded by the non-boot loader to obtain the loader
 429     // constraints based on the runtime classloaders' context. The dumptime
 430     // itable index should be the same as the runtime index.
 431     assert(_vtable_index == itable_index_max - index,
 432            "archived itable index is different from runtime index");
 433     return; // don’t write into the shared class
 434   } else {
 435     _vtable_index = itable_index_max - index;
 436   }
 437   assert(valid_itable_index(), "");
 438 }
 439 
 440 // The RegisterNatives call being attempted tried to register with a method that
 441 // is not native.  Ask JVM TI what prefixes have been specified.  Then check
 442 // to see if the native method is now wrapped with the prefixes.  See the
 443 // SetNativeMethodPrefix(es) functions in the JVM TI Spec for details.
 444 static Method* find_prefixed_native(Klass* k, Symbol* name, Symbol* signature, TRAPS) {
 445 #if INCLUDE_JVMTI
 446   ResourceMark rm(THREAD);
 447   Method* method;
 448   int name_len = name->utf8_length();
 449   char* name_str = name->as_utf8();
 450   int prefix_count;
 451   char** prefixes = JvmtiExport::get_all_native_method_prefixes(&prefix_count);
 452   for (int i = 0; i < prefix_count; i++) {
 453     char* prefix = prefixes[i];
 454     int prefix_len = (int)strlen(prefix);
 455 
 456     // try adding this prefix to the method name and see if it matches another method name
 457     int trial_len = name_len + prefix_len;
 458     char* trial_name_str = NEW_RESOURCE_ARRAY(char, trial_len + 1);
 459     strcpy(trial_name_str, prefix);
 460     strcat(trial_name_str, name_str);
 461     TempNewSymbol trial_name = SymbolTable::probe(trial_name_str, trial_len);
 462     if (trial_name == nullptr) {
 463       continue; // no such symbol, so this prefix wasn't used, try the next prefix
 464     }
 465     method = k->lookup_method(trial_name, signature);
 466     if (method == nullptr) {
 467       continue; // signature doesn't match, try the next prefix
 468     }
 469     if (method->is_native()) {
 470       method->set_is_prefixed_native();
 471       return method; // wahoo, we found a prefixed version of the method, return it
 472     }
 473     // found as non-native, so prefix is good, add it, probably just need more prefixes
 474     name_len = trial_len;
 475     name_str = trial_name_str;
 476   }
 477 #endif // INCLUDE_JVMTI
 478   return nullptr; // not found
 479 }
 480 
 481 bool Method::register_native(Klass* k, Symbol* name, Symbol* signature, address entry, TRAPS) {
 482   Method* method = k->lookup_method(name, signature);
 483   if (method == nullptr) {
 484     ResourceMark rm(THREAD);
 485     stringStream st;
 486     st.print("Method '");
 487     print_external_name(&st, k, name, signature);
 488     st.print("' name or signature does not match");
 489     THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), false);
 490   }
 491   if (!method->is_native()) {
 492     // trying to register to a non-native method, see if a JVM TI agent has added prefix(es)
 493     method = find_prefixed_native(k, name, signature, THREAD);
 494     if (method == nullptr) {
 495       ResourceMark rm(THREAD);
 496       stringStream st;
 497       st.print("Method '");
 498       print_external_name(&st, k, name, signature);
 499       st.print("' is not declared as native");
 500       THROW_MSG_(vmSymbols::java_lang_NoSuchMethodError(), st.as_string(), false);
 501     }
 502   }
 503 
 504   if (entry != nullptr) {
 505     method->set_native_function(entry, native_bind_event_is_interesting);
 506   } else {
 507     method->clear_native_function();
 508   }
 509   if (log_is_enabled(Debug, jni, resolve)) {
 510     ResourceMark rm(THREAD);
 511     log_debug(jni, resolve)("[Registering JNI native method %s.%s]",
 512                             method->method_holder()->external_name(),
 513                             method->name()->as_C_string());
 514   }
 515   return true;
 516 }
 517 
 518 bool Method::was_executed_more_than(int n) {
 519   // Invocation counter is reset when the Method* is compiled.
 520   // If the method has compiled code we therefore assume it has
 521   // be executed more than n times.
 522   if (is_accessor() || is_empty_method() || (code() != nullptr)) {
 523     // interpreter doesn't bump invocation counter of trivial methods
 524     // compiler does not bump invocation counter of compiled methods
 525     return true;
 526   }
 527   else if ((method_counters() != nullptr &&
 528             method_counters()->invocation_counter()->carry()) ||
 529            (method_data() != nullptr &&
 530             method_data()->invocation_counter()->carry())) {
 531     // The carry bit is set when the counter overflows and causes
 532     // a compilation to occur.  We don't know how many times
 533     // the counter has been reset, so we simply assume it has
 534     // been executed more than n times.
 535     return true;
 536   } else {
 537     return invocation_count() > n;
 538   }
 539 }
 540 
 541 void Method::print_invocation_count(outputStream* st) {
 542   //---<  compose+print method return type, klass, name, and signature  >---
 543   if (is_static())       { st->print("static "); }
 544   if (is_final())        { st->print("final "); }
 545   if (is_synchronized()) { st->print("synchronized "); }
 546   if (is_native())       { st->print("native "); }
 547   st->print("%s::", method_holder()->external_name());
 548   name()->print_symbol_on(st);
 549   signature()->print_symbol_on(st);
 550 
 551   if (WizardMode) {
 552     // dump the size of the byte codes
 553     st->print(" {%d}", code_size());
 554   }
 555   st->cr();
 556 
 557   // Counting based on signed int counters tends to overflow with
 558   // longer-running workloads on fast machines. The counters under
 559   // consideration here, however, are limited in range by counting
 560   // logic. See InvocationCounter:count_limit for example.
 561   // No "overflow precautions" need to be implemented here.
 562   st->print_cr ("  interpreter_invocation_count: " INT32_FORMAT_W(11), interpreter_invocation_count());
 563   st->print_cr ("  invocation_counter:           " INT32_FORMAT_W(11), invocation_count());
 564   st->print_cr ("  backedge_counter:             " INT32_FORMAT_W(11), backedge_count());
 565 
 566   if (method_data() != nullptr) {
 567     st->print_cr ("  decompile_count:              " UINT32_FORMAT_W(11), method_data()->decompile_count());
 568   }
 569 
 570 #ifndef PRODUCT
 571   if (CountCompiledCalls) {
 572     st->print_cr ("  compiled_invocation_count:    " INT64_FORMAT_W(11), compiled_invocation_count());
 573   }
 574 #endif
 575 }
 576 
 577 // Build a MethodData* object to hold profiling information collected on this
 578 // method when requested.
 579 void Method::build_profiling_method_data(const methodHandle& method, TRAPS) {
 580   // Do not profile the method if metaspace has hit an OOM previously
 581   // allocating profiling data. Callers clear pending exception so don't
 582   // add one here.
 583   if (ClassLoaderDataGraph::has_metaspace_oom()) {
 584     return;
 585   }
 586 
 587   ClassLoaderData* loader_data = method->method_holder()->class_loader_data();
 588   MethodData* method_data = MethodData::allocate(loader_data, method, THREAD);
 589   if (HAS_PENDING_EXCEPTION) {
 590     CompileBroker::log_metaspace_failure();
 591     ClassLoaderDataGraph::set_metaspace_oom(true);
 592     return;   // return the exception (which is cleared)
 593   }
 594 
 595   if (!Atomic::replace_if_null(&method->_method_data, method_data)) {
 596     MetadataFactory::free_metadata(loader_data, method_data);
 597     return;
 598   }
 599 
 600   if (PrintMethodData && (Verbose || WizardMode)) {
 601     ResourceMark rm(THREAD);
 602     tty->print("build_profiling_method_data for ");
 603     method->print_name(tty);
 604     tty->cr();
 605     // At the end of the run, the MDO, full of data, will be dumped.
 606   }
 607 }
 608 
 609 MethodCounters* Method::build_method_counters(Thread* current, Method* m) {
 610   // Do not profile the method if metaspace has hit an OOM previously
 611   if (ClassLoaderDataGraph::has_metaspace_oom()) {
 612     return nullptr;
 613   }
 614 
 615   methodHandle mh(current, m);
 616   MethodCounters* counters;
 617   if (current->is_Java_thread()) {
 618     JavaThread* THREAD = JavaThread::cast(current); // For exception macros.
 619     // Use the TRAPS version for a JavaThread so it will adjust the GC threshold
 620     // if needed.
 621     counters = MethodCounters::allocate_with_exception(mh, THREAD);
 622     if (HAS_PENDING_EXCEPTION) {
 623       CLEAR_PENDING_EXCEPTION;
 624     }
 625   } else {
 626     // Call metaspace allocation that doesn't throw exception if the
 627     // current thread isn't a JavaThread, ie. the VMThread.
 628     counters = MethodCounters::allocate_no_exception(mh);
 629   }
 630 
 631   if (counters == nullptr) {
 632     CompileBroker::log_metaspace_failure();
 633     ClassLoaderDataGraph::set_metaspace_oom(true);
 634     return nullptr;
 635   }
 636 
 637   if (!mh->init_method_counters(counters)) {
 638     MetadataFactory::free_metadata(mh->method_holder()->class_loader_data(), counters);
 639   }
 640 
 641   return mh->method_counters();
 642 }
 643 
 644 bool Method::init_method_counters(MethodCounters* counters) {
 645   // Try to install a pointer to MethodCounters, return true on success.
 646   return Atomic::replace_if_null(&_method_counters, counters);
 647 }
 648 
 649 void Method::set_exception_handler_entered(int handler_bci) {
 650   if (ProfileExceptionHandlers) {
 651     MethodData* mdo = method_data();
 652     if (mdo != nullptr) {
 653       BitData handler_data = mdo->exception_handler_bci_to_data(handler_bci);
 654       handler_data.set_exception_handler_entered();
 655     }
 656   }
 657 }
 658 
 659 int Method::extra_stack_words() {
 660   // not an inline function, to avoid a header dependency on Interpreter
 661   return extra_stack_entries() * Interpreter::stackElementSize;
 662 }
 663 
 664 bool Method::compute_has_loops_flag() {
 665   BytecodeStream bcs(methodHandle(Thread::current(), this));
 666   Bytecodes::Code bc;
 667 
 668   while ((bc = bcs.next()) >= 0) {
 669     switch (bc) {
 670       case Bytecodes::_ifeq:
 671       case Bytecodes::_ifnull:
 672       case Bytecodes::_iflt:
 673       case Bytecodes::_ifle:
 674       case Bytecodes::_ifne:
 675       case Bytecodes::_ifnonnull:
 676       case Bytecodes::_ifgt:
 677       case Bytecodes::_ifge:
 678       case Bytecodes::_if_icmpeq:
 679       case Bytecodes::_if_icmpne:
 680       case Bytecodes::_if_icmplt:
 681       case Bytecodes::_if_icmpgt:
 682       case Bytecodes::_if_icmple:
 683       case Bytecodes::_if_icmpge:
 684       case Bytecodes::_if_acmpeq:
 685       case Bytecodes::_if_acmpne:
 686       case Bytecodes::_goto:
 687       case Bytecodes::_jsr:
 688         if (bcs.dest() < bcs.next_bci()) {
 689           return set_has_loops();
 690         }
 691         break;
 692 
 693       case Bytecodes::_goto_w:
 694       case Bytecodes::_jsr_w:
 695         if (bcs.dest_w() < bcs.next_bci()) {
 696           return set_has_loops();
 697         }
 698         break;
 699 
 700       case Bytecodes::_lookupswitch: {
 701         Bytecode_lookupswitch lookupswitch(this, bcs.bcp());
 702         if (lookupswitch.default_offset() < 0) {
 703           return set_has_loops();
 704         } else {
 705           for (int i = 0; i < lookupswitch.number_of_pairs(); ++i) {
 706             LookupswitchPair pair = lookupswitch.pair_at(i);
 707             if (pair.offset() < 0) {
 708               return set_has_loops();
 709             }
 710           }
 711         }
 712         break;
 713       }
 714       case Bytecodes::_tableswitch: {
 715         Bytecode_tableswitch tableswitch(this, bcs.bcp());
 716         if (tableswitch.default_offset() < 0) {
 717           return set_has_loops();
 718         } else {
 719           for (int i = 0; i < tableswitch.length(); ++i) {
 720             if (tableswitch.dest_offset_at(i) < 0) {
 721               return set_has_loops();
 722             }
 723           }
 724         }
 725         break;
 726       }
 727       default:
 728         break;
 729     }
 730   }
 731 
 732   _flags.set_has_loops_flag_init(true);
 733   return false;
 734 }
 735 
 736 bool Method::is_final_method(AccessFlags class_access_flags) const {
 737   // or "does_not_require_vtable_entry"
 738   // default method or overpass can occur, is not final (reuses vtable entry)
 739   // private methods in classes get vtable entries for backward class compatibility.
 740   if (is_overpass() || is_default_method())  return false;
 741   return is_final() || class_access_flags.is_final();
 742 }
 743 
 744 bool Method::is_final_method() const {
 745   return is_final_method(method_holder()->access_flags());
 746 }
 747 
 748 bool Method::is_default_method() const {
 749   if (method_holder() != nullptr &&
 750       method_holder()->is_interface() &&
 751       !is_abstract() && !is_private()) {
 752     return true;
 753   } else {
 754     return false;
 755   }
 756 }
 757 
 758 bool Method::can_be_statically_bound(AccessFlags class_access_flags) const {
 759   if (is_final_method(class_access_flags))  return true;
 760 #ifdef ASSERT
 761   bool is_nonv = (vtable_index() == nonvirtual_vtable_index);
 762   if (class_access_flags.is_interface()) {
 763       ResourceMark rm;
 764       assert(is_nonv == is_static() || is_nonv == is_private(),
 765              "nonvirtual unexpected for non-static, non-private: %s",
 766              name_and_sig_as_C_string());
 767   }
 768 #endif
 769   assert(valid_vtable_index() || valid_itable_index(), "method must be linked before we ask this question");
 770   return vtable_index() == nonvirtual_vtable_index;
 771 }
 772 
 773 bool Method::can_be_statically_bound() const {
 774   return can_be_statically_bound(method_holder()->access_flags());
 775 }
 776 
 777 bool Method::can_be_statically_bound(InstanceKlass* context) const {
 778   return (method_holder() == context) && can_be_statically_bound();
 779 }
 780 
 781 /**
 782  *  Returns false if this is one of specially treated methods for
 783  *  which we have to provide stack trace in throw in compiled code.
 784  *  Returns true otherwise.
 785  */
 786 bool Method::can_omit_stack_trace() {
 787   if (klass_name() == vmSymbols::sun_invoke_util_ValueConversions()) {
 788     return false; // All methods in sun.invoke.util.ValueConversions
 789   }
 790   return true;
 791 }
 792 
 793 bool Method::is_accessor() const {
 794   return is_getter() || is_setter();
 795 }
 796 
 797 bool Method::is_getter() const {
 798   if (code_size() != 5) return false;
 799   if (size_of_parameters() != 1) return false;
 800   if (java_code_at(0) != Bytecodes::_aload_0)  return false;
 801   if (java_code_at(1) != Bytecodes::_getfield) return false;
 802   switch (java_code_at(4)) {
 803     case Bytecodes::_ireturn:
 804     case Bytecodes::_lreturn:
 805     case Bytecodes::_freturn:
 806     case Bytecodes::_dreturn:
 807     case Bytecodes::_areturn:
 808       break;
 809     default:
 810       return false;
 811   }
 812   return true;
 813 }
 814 
 815 bool Method::is_setter() const {
 816   if (code_size() != 6) return false;
 817   if (java_code_at(0) != Bytecodes::_aload_0) return false;
 818   switch (java_code_at(1)) {
 819     case Bytecodes::_iload_1:
 820     case Bytecodes::_aload_1:
 821     case Bytecodes::_fload_1:
 822       if (size_of_parameters() != 2) return false;
 823       break;
 824     case Bytecodes::_dload_1:
 825     case Bytecodes::_lload_1:
 826       if (size_of_parameters() != 3) return false;
 827       break;
 828     default:
 829       return false;
 830   }
 831   if (java_code_at(2) != Bytecodes::_putfield) return false;
 832   if (java_code_at(5) != Bytecodes::_return)   return false;
 833   return true;
 834 }
 835 
 836 bool Method::is_constant_getter() const {
 837   int last_index = code_size() - 1;
 838   // Check if the first 1-3 bytecodes are a constant push
 839   // and the last bytecode is a return.
 840   return (2 <= code_size() && code_size() <= 4 &&
 841           Bytecodes::is_const(java_code_at(0)) &&
 842           Bytecodes::length_for(java_code_at(0)) == last_index &&
 843           Bytecodes::is_return(java_code_at(last_index)));
 844 }
 845 
 846 bool Method::is_initializer() const {
 847   return is_object_initializer() || is_static_initializer();
 848 }
 849 
 850 bool Method::has_valid_initializer_flags() const {
 851   return (is_static() ||
 852           method_holder()->major_version() < 51);
 853 }
 854 
 855 bool Method::is_static_initializer() const {
 856   // For classfiles version 51 or greater, ensure that the clinit method is
 857   // static.  Non-static methods with the name "<clinit>" are not static
 858   // initializers. (older classfiles exempted for backward compatibility)
 859   return name() == vmSymbols::class_initializer_name() &&
 860          has_valid_initializer_flags();
 861 }
 862 
 863 bool Method::is_object_initializer() const {
 864    return name() == vmSymbols::object_initializer_name();
 865 }
 866 
 867 bool Method::needs_clinit_barrier() const {
 868   return is_static() && !method_holder()->is_initialized();
 869 }
 870 
 871 objArrayHandle Method::resolved_checked_exceptions_impl(Method* method, TRAPS) {
 872   int length = method->checked_exceptions_length();
 873   if (length == 0) {  // common case
 874     return objArrayHandle(THREAD, Universe::the_empty_class_array());
 875   } else {
 876     methodHandle h_this(THREAD, method);
 877     objArrayOop m_oop = oopFactory::new_objArray(vmClasses::Class_klass(), length, CHECK_(objArrayHandle()));
 878     objArrayHandle mirrors (THREAD, m_oop);
 879     for (int i = 0; i < length; i++) {
 880       CheckedExceptionElement* table = h_this->checked_exceptions_start(); // recompute on each iteration, not gc safe
 881       Klass* k = h_this->constants()->klass_at(table[i].class_cp_index, CHECK_(objArrayHandle()));
 882       if (log_is_enabled(Warning, exceptions) &&
 883           !k->is_subclass_of(vmClasses::Throwable_klass())) {
 884         ResourceMark rm(THREAD);
 885         log_warning(exceptions)(
 886           "Class %s in throws clause of method %s is not a subtype of class java.lang.Throwable",
 887           k->external_name(), method->external_name());
 888       }
 889       mirrors->obj_at_put(i, k->java_mirror());
 890     }
 891     return mirrors;
 892   }
 893 };
 894 
 895 
 896 int Method::line_number_from_bci(int bci) const {
 897   int best_bci  =  0;
 898   int best_line = -1;
 899   if (bci == SynchronizationEntryBCI) bci = 0;
 900   if (0 <= bci && bci < code_size() && has_linenumber_table()) {
 901     // The line numbers are a short array of 2-tuples [start_pc, line_number].
 902     // Not necessarily sorted and not necessarily one-to-one.
 903     CompressedLineNumberReadStream stream(compressed_linenumber_table());
 904     while (stream.read_pair()) {
 905       if (stream.bci() == bci) {
 906         // perfect match
 907         return stream.line();
 908       } else {
 909         // update best_bci/line
 910         if (stream.bci() < bci && stream.bci() >= best_bci) {
 911           best_bci  = stream.bci();
 912           best_line = stream.line();
 913         }
 914       }
 915     }
 916   }
 917   return best_line;
 918 }
 919 
 920 
 921 bool Method::is_klass_loaded_by_klass_index(int klass_index) const {
 922   if( constants()->tag_at(klass_index).is_unresolved_klass() ) {
 923     Thread *thread = Thread::current();
 924     Symbol* klass_name = constants()->klass_name_at(klass_index);
 925     Handle loader(thread, method_holder()->class_loader());
 926     Handle prot  (thread, method_holder()->protection_domain());
 927     return SystemDictionary::find_instance_klass(thread, klass_name, loader, prot) != nullptr;
 928   } else {
 929     return true;
 930   }
 931 }
 932 
 933 
 934 bool Method::is_klass_loaded(int refinfo_index, Bytecodes::Code bc, bool must_be_resolved) const {
 935   int klass_index = constants()->klass_ref_index_at(refinfo_index, bc);
 936   if (must_be_resolved) {
 937     // Make sure klass is resolved in constantpool.
 938     if (constants()->tag_at(klass_index).is_unresolved_klass()) return false;
 939   }
 940   return is_klass_loaded_by_klass_index(klass_index);
 941 }
 942 
 943 
 944 void Method::set_native_function(address function, bool post_event_flag) {
 945   assert(function != nullptr, "use clear_native_function to unregister natives");
 946   assert(!is_special_native_intrinsic() || function == SharedRuntime::native_method_throw_unsatisfied_link_error_entry(), "");
 947   address* native_function = native_function_addr();
 948 
 949   // We can see racers trying to place the same native function into place. Once
 950   // is plenty.
 951   address current = *native_function;
 952   if (current == function) return;
 953   if (post_event_flag && JvmtiExport::should_post_native_method_bind() &&
 954       function != nullptr) {
 955     // native_method_throw_unsatisfied_link_error_entry() should only
 956     // be passed when post_event_flag is false.
 957     assert(function !=
 958       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 959       "post_event_flag mismatch");
 960 
 961     // post the bind event, and possible change the bind function
 962     JvmtiExport::post_native_method_bind(this, &function);
 963   }
 964   *native_function = function;
 965   // This function can be called more than once. We must make sure that we always
 966   // use the latest registered method -> check if a stub already has been generated.
 967   // If so, we have to make it not_entrant.
 968   nmethod* nm = code(); // Put it into local variable to guard against concurrent updates
 969   if (nm != nullptr) {
 970     nm->make_not_entrant();
 971   }
 972 }
 973 
 974 
 975 bool Method::has_native_function() const {
 976   if (is_special_native_intrinsic())
 977     return false;  // special-cased in SharedRuntime::generate_native_wrapper
 978   address func = native_function();
 979   return (func != nullptr && func != SharedRuntime::native_method_throw_unsatisfied_link_error_entry());
 980 }
 981 
 982 
 983 void Method::clear_native_function() {
 984   // Note: is_method_handle_intrinsic() is allowed here.
 985   set_native_function(
 986     SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
 987     !native_bind_event_is_interesting);
 988   this->unlink_code();
 989 }
 990 
 991 
 992 void Method::set_signature_handler(address handler) {
 993   address* signature_handler =  signature_handler_addr();
 994   *signature_handler = handler;
 995 }
 996 
 997 
 998 void Method::print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason) {
 999   assert(reason != nullptr, "must provide a reason");
1000   if (PrintCompilation && report) {
1001     ttyLocker ttyl;
1002     tty->print("made not %scompilable on ", is_osr ? "OSR " : "");
1003     if (comp_level == CompLevel_all) {
1004       tty->print("all levels ");
1005     } else {
1006       tty->print("level %d ", comp_level);
1007     }
1008     this->print_short_name(tty);
1009     int size = this->code_size();
1010     if (size > 0) {
1011       tty->print(" (%d bytes)", size);
1012     }
1013     if (reason != nullptr) {
1014       tty->print("   %s", reason);
1015     }
1016     tty->cr();
1017   }
1018   if ((TraceDeoptimization || LogCompilation) && (xtty != nullptr)) {
1019     ttyLocker ttyl;
1020     xtty->begin_elem("make_not_compilable thread='" UINTX_FORMAT "' osr='%d' level='%d'",
1021                      os::current_thread_id(), is_osr, comp_level);
1022     if (reason != nullptr) {
1023       xtty->print(" reason=\'%s\'", reason);
1024     }
1025     xtty->method(this);
1026     xtty->stamp();
1027     xtty->end_elem();
1028   }
1029 }
1030 
1031 bool Method::is_always_compilable() const {
1032   // Generated adapters must be compiled
1033   if (is_special_native_intrinsic() && is_synthetic()) {
1034     assert(!is_not_c1_compilable(), "sanity check");
1035     assert(!is_not_c2_compilable(), "sanity check");
1036     return true;
1037   }
1038 
1039   return false;
1040 }
1041 
1042 bool Method::is_not_compilable(int comp_level) const {
1043   if (number_of_breakpoints() > 0)
1044     return true;
1045   if (is_always_compilable())
1046     return false;
1047   if (comp_level == CompLevel_any)
1048     return is_not_c1_compilable() && is_not_c2_compilable();
1049   if (is_c1_compile(comp_level))
1050     return is_not_c1_compilable();
1051   if (is_c2_compile(comp_level))
1052     return is_not_c2_compilable();
1053   return false;
1054 }
1055 
1056 // call this when compiler finds that this method is not compilable
1057 void Method::set_not_compilable(const char* reason, int comp_level, bool report) {
1058   if (is_always_compilable()) {
1059     // Don't mark a method which should be always compilable
1060     return;
1061   }
1062   print_made_not_compilable(comp_level, /*is_osr*/ false, report, reason);
1063   if (comp_level == CompLevel_all) {
1064     set_is_not_c1_compilable();
1065     set_is_not_c2_compilable();
1066   } else {
1067     if (is_c1_compile(comp_level))
1068       set_is_not_c1_compilable();
1069     if (is_c2_compile(comp_level))
1070       set_is_not_c2_compilable();
1071   }
1072   assert(!CompilationPolicy::can_be_compiled(methodHandle(Thread::current(), this), comp_level), "sanity check");
1073 }
1074 
1075 bool Method::is_not_osr_compilable(int comp_level) const {
1076   if (is_not_compilable(comp_level))
1077     return true;
1078   if (comp_level == CompLevel_any)
1079     return is_not_c1_osr_compilable() && is_not_c2_osr_compilable();
1080   if (is_c1_compile(comp_level))
1081     return is_not_c1_osr_compilable();
1082   if (is_c2_compile(comp_level))
1083     return is_not_c2_osr_compilable();
1084   return false;
1085 }
1086 
1087 void Method::set_not_osr_compilable(const char* reason, int comp_level, bool report) {
1088   print_made_not_compilable(comp_level, /*is_osr*/ true, report, reason);
1089   if (comp_level == CompLevel_all) {
1090     set_is_not_c1_osr_compilable();
1091     set_is_not_c2_osr_compilable();
1092   } else {
1093     if (is_c1_compile(comp_level))
1094       set_is_not_c1_osr_compilable();
1095     if (is_c2_compile(comp_level))
1096       set_is_not_c2_osr_compilable();
1097   }
1098   assert(!CompilationPolicy::can_be_osr_compiled(methodHandle(Thread::current(), this), comp_level), "sanity check");
1099 }
1100 
1101 // Revert to using the interpreter and clear out the nmethod
1102 void Method::clear_code() {
1103   // this may be null if c2i adapters have not been made yet
1104   // Only should happen at allocate time.
1105   if (adapter() == nullptr) {
1106     _from_compiled_entry    = nullptr;
1107   } else {
1108     _from_compiled_entry    = adapter()->get_c2i_entry();
1109   }
1110   OrderAccess::storestore();
1111   _from_interpreted_entry = _i2i_entry;
1112   OrderAccess::storestore();
1113   _code = nullptr;
1114 }
1115 
1116 void Method::unlink_code(nmethod *compare) {
1117   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
1118   // We need to check if either the _code or _from_compiled_code_entry_point
1119   // refer to this nmethod because there is a race in setting these two fields
1120   // in Method* as seen in bugid 4947125.
1121   if (code() == compare ||
1122       from_compiled_entry() == compare->verified_entry_point()) {
1123     clear_code();
1124   }
1125 }
1126 
1127 void Method::unlink_code() {
1128   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
1129   clear_code();
1130 }
1131 
1132 #if INCLUDE_CDS
1133 // Called by class data sharing to remove any entry points (which are not shared)
1134 void Method::unlink_method() {
1135   assert(CDSConfig::is_dumping_archive(), "sanity");
1136   _code = nullptr;
1137   _adapter = nullptr;
1138   _i2i_entry = nullptr;
1139   _from_compiled_entry = nullptr;
1140   _from_interpreted_entry = nullptr;
1141 
1142   if (is_native()) {
1143     *native_function_addr() = nullptr;
1144     set_signature_handler(nullptr);
1145   }
1146   NOT_PRODUCT(set_compiled_invocation_count(0);)
1147 
1148   clear_method_data();
1149   clear_method_counters();
1150   remove_unshareable_flags();
1151 }
1152 
1153 void Method::remove_unshareable_flags() {
1154   // clear all the flags that shouldn't be in the archived version
1155   assert(!is_old(), "must be");
1156   assert(!is_obsolete(), "must be");
1157   assert(!is_deleted(), "must be");
1158 
1159   set_is_prefixed_native(false);
1160   set_queued_for_compilation(false);
1161   set_is_not_c2_compilable(false);
1162   set_is_not_c1_compilable(false);
1163   set_is_not_c2_osr_compilable(false);
1164   set_on_stack_flag(false);
1165 }
1166 #endif
1167 
1168 // Called when the method_holder is getting linked. Setup entrypoints so the method
1169 // is ready to be called from interpreter, compiler, and vtables.
1170 void Method::link_method(const methodHandle& h_method, TRAPS) {
1171   // If the code cache is full, we may reenter this function for the
1172   // leftover methods that weren't linked.
1173   if (adapter() != nullptr) {
1174     return;
1175   }
1176   assert( _code == nullptr, "nothing compiled yet" );
1177 
1178   // Setup interpreter entrypoint
1179   assert(this == h_method(), "wrong h_method()" );
1180 
1181   assert(adapter() == nullptr, "init'd to null");
1182   address entry = Interpreter::entry_for_method(h_method);
1183   assert(entry != nullptr, "interpreter entry must be non-null");
1184   // Sets both _i2i_entry and _from_interpreted_entry
1185   set_interpreter_entry(entry);
1186 
1187   // Don't overwrite already registered native entries.
1188   if (is_native() && !has_native_function()) {
1189     set_native_function(
1190       SharedRuntime::native_method_throw_unsatisfied_link_error_entry(),
1191       !native_bind_event_is_interesting);
1192   }
1193 
1194   // Setup compiler entrypoint.  This is made eagerly, so we do not need
1195   // special handling of vtables.  An alternative is to make adapters more
1196   // lazily by calling make_adapter() from from_compiled_entry() for the
1197   // normal calls.  For vtable calls life gets more complicated.  When a
1198   // call-site goes mega-morphic we need adapters in all methods which can be
1199   // called from the vtable.  We need adapters on such methods that get loaded
1200   // later.  Ditto for mega-morphic itable calls.  If this proves to be a
1201   // problem we'll make these lazily later.
1202   (void) make_adapters(h_method, CHECK);
1203 
1204   // ONLY USE the h_method now as make_adapter may have blocked
1205 
1206   if (h_method->is_continuation_native_intrinsic()) {
1207     _from_interpreted_entry = nullptr;
1208     _from_compiled_entry = nullptr;
1209     _i2i_entry = nullptr;
1210     if (Continuations::enabled()) {
1211       assert(!Threads::is_vm_complete(), "should only be called during vm init");
1212       AdapterHandlerLibrary::create_native_wrapper(h_method);
1213       if (!h_method->has_compiled_code()) {
1214         THROW_MSG(vmSymbols::java_lang_OutOfMemoryError(), "Initial size of CodeCache is too small");
1215       }
1216       assert(_from_interpreted_entry == get_i2c_entry(), "invariant");
1217     }
1218   }
1219 }
1220 
1221 address Method::make_adapters(const methodHandle& mh, TRAPS) {
1222   // Adapters for compiled code are made eagerly here.  They are fairly
1223   // small (generally < 100 bytes) and quick to make (and cached and shared)
1224   // so making them eagerly shouldn't be too expensive.
1225   AdapterHandlerEntry* adapter = AdapterHandlerLibrary::get_adapter(mh);
1226   if (adapter == nullptr ) {
1227     if (!is_init_completed()) {
1228       // Don't throw exceptions during VM initialization because java.lang.* classes
1229       // might not have been initialized, causing problems when constructing the
1230       // Java exception object.
1231       vm_exit_during_initialization("Out of space in CodeCache for adapters");
1232     } else {
1233       THROW_MSG_NULL(vmSymbols::java_lang_OutOfMemoryError(), "Out of space in CodeCache for adapters");
1234     }
1235   }
1236 
1237   mh->set_adapter_entry(adapter);
1238   mh->_from_compiled_entry = adapter->get_c2i_entry();
1239   return adapter->get_c2i_entry();
1240 }
1241 
1242 // The verified_code_entry() must be called when a invoke is resolved
1243 // on this method.
1244 
1245 // It returns the compiled code entry point, after asserting not null.
1246 // This function is called after potential safepoints so that nmethod
1247 // or adapter that it points to is still live and valid.
1248 // This function must not hit a safepoint!
1249 address Method::verified_code_entry() {
1250   debug_only(NoSafepointVerifier nsv;)
1251   assert(_from_compiled_entry != nullptr, "must be set");
1252   return _from_compiled_entry;
1253 }
1254 
1255 // Check that if an nmethod ref exists, it has a backlink to this or no backlink at all
1256 // (could be racing a deopt).
1257 // Not inline to avoid circular ref.
1258 bool Method::check_code() const {
1259   // cached in a register or local.  There's a race on the value of the field.
1260   nmethod *code = Atomic::load_acquire(&_code);
1261   return code == nullptr || (code->method() == nullptr) || (code->method() == (Method*)this && !code->is_osr_method());
1262 }
1263 
1264 // Install compiled code.  Instantly it can execute.
1265 void Method::set_code(const methodHandle& mh, nmethod *code) {
1266   assert_lock_strong(NMethodState_lock);
1267   assert( code, "use clear_code to remove code" );
1268   assert( mh->check_code(), "" );
1269 
1270   guarantee(mh->adapter() != nullptr, "Adapter blob must already exist!");
1271 
1272   // These writes must happen in this order, because the interpreter will
1273   // directly jump to from_interpreted_entry which jumps to an i2c adapter
1274   // which jumps to _from_compiled_entry.
1275   mh->_code = code;             // Assign before allowing compiled code to exec
1276 
1277   int comp_level = code->comp_level();
1278   // In theory there could be a race here. In practice it is unlikely
1279   // and not worth worrying about.
1280   if (comp_level > mh->highest_comp_level()) {
1281     mh->set_highest_comp_level(comp_level);
1282   }
1283 
1284   OrderAccess::storestore();
1285   mh->_from_compiled_entry = code->verified_entry_point();
1286   OrderAccess::storestore();
1287 
1288   if (mh->is_continuation_native_intrinsic()) {
1289     assert(mh->_from_interpreted_entry == nullptr, "initialized incorrectly"); // see link_method
1290 
1291     if (mh->is_continuation_enter_intrinsic()) {
1292       // This is the entry used when we're in interpreter-only mode; see InterpreterMacroAssembler::jump_from_interpreted
1293       mh->_i2i_entry = ContinuationEntry::interpreted_entry();
1294     } else if (mh->is_continuation_yield_intrinsic()) {
1295       mh->_i2i_entry = mh->get_i2c_entry();
1296     } else {
1297       guarantee(false, "Unknown Continuation native intrinsic");
1298     }
1299     // This must come last, as it is what's tested in LinkResolver::resolve_static_call
1300     Atomic::release_store(&mh->_from_interpreted_entry , mh->get_i2c_entry());
1301   } else if (!mh->is_method_handle_intrinsic()) {
1302     // Instantly compiled code can execute.
1303     mh->_from_interpreted_entry = mh->get_i2c_entry();
1304   }
1305 }
1306 
1307 
1308 bool Method::is_overridden_in(Klass* k) const {
1309   InstanceKlass* ik = InstanceKlass::cast(k);
1310 
1311   if (ik->is_interface()) return false;
1312 
1313   // If method is an interface, we skip it - except if it
1314   // is a miranda method
1315   if (method_holder()->is_interface()) {
1316     // Check that method is not a miranda method
1317     if (ik->lookup_method(name(), signature()) == nullptr) {
1318       // No implementation exist - so miranda method
1319       return false;
1320     }
1321     return true;
1322   }
1323 
1324   assert(ik->is_subclass_of(method_holder()), "should be subklass");
1325   if (!has_vtable_index()) {
1326     return false;
1327   } else {
1328     Method* vt_m = ik->method_at_vtable(vtable_index());
1329     return vt_m != this;
1330   }
1331 }
1332 
1333 
1334 // give advice about whether this Method* should be cached or not
1335 bool Method::should_not_be_cached() const {
1336   if (is_old()) {
1337     // This method has been redefined. It is either EMCP or obsolete
1338     // and we don't want to cache it because that would pin the method
1339     // down and prevent it from being collectible if and when it
1340     // finishes executing.
1341     return true;
1342   }
1343 
1344   // caching this method should be just fine
1345   return false;
1346 }
1347 
1348 
1349 /**
1350  *  Returns true if this is one of the specially treated methods for
1351  *  security related stack walks (like Reflection.getCallerClass).
1352  */
1353 bool Method::is_ignored_by_security_stack_walk() const {
1354   if (intrinsic_id() == vmIntrinsics::_invoke) {
1355     // This is Method.invoke() -- ignore it
1356     return true;
1357   }
1358   if (method_holder()->is_subclass_of(vmClasses::reflect_MethodAccessorImpl_klass())) {
1359     // This is an auxiliary frame -- ignore it
1360     return true;
1361   }
1362   if (is_method_handle_intrinsic() || is_compiled_lambda_form()) {
1363     // This is an internal adapter frame for method handles -- ignore it
1364     return true;
1365   }
1366   return false;
1367 }
1368 
1369 
1370 // Constant pool structure for invoke methods:
1371 enum {
1372   _imcp_invoke_name = 1,        // utf8: 'invokeExact', etc.
1373   _imcp_invoke_signature,       // utf8: (variable Symbol*)
1374   _imcp_limit
1375 };
1376 
1377 // Test if this method is an MH adapter frame generated by Java code.
1378 // Cf. java/lang/invoke/InvokerBytecodeGenerator
1379 bool Method::is_compiled_lambda_form() const {
1380   return intrinsic_id() == vmIntrinsics::_compiledLambdaForm;
1381 }
1382 
1383 // Test if this method is an internal MH primitive method.
1384 bool Method::is_method_handle_intrinsic() const {
1385   vmIntrinsics::ID iid = intrinsic_id();
1386   return (MethodHandles::is_signature_polymorphic(iid) &&
1387           MethodHandles::is_signature_polymorphic_intrinsic(iid));
1388 }
1389 
1390 bool Method::has_member_arg() const {
1391   vmIntrinsics::ID iid = intrinsic_id();
1392   return (MethodHandles::is_signature_polymorphic(iid) &&
1393           MethodHandles::has_member_arg(iid));
1394 }
1395 
1396 // Make an instance of a signature-polymorphic internal MH primitive.
1397 methodHandle Method::make_method_handle_intrinsic(vmIntrinsics::ID iid,
1398                                                          Symbol* signature,
1399                                                          TRAPS) {
1400   ResourceMark rm(THREAD);
1401   methodHandle empty;
1402 
1403   InstanceKlass* holder = vmClasses::MethodHandle_klass();
1404   Symbol* name = MethodHandles::signature_polymorphic_intrinsic_name(iid);
1405   assert(iid == MethodHandles::signature_polymorphic_name_id(name), "");
1406 
1407   log_info(methodhandles)("make_method_handle_intrinsic MH.%s%s", name->as_C_string(), signature->as_C_string());
1408 
1409   // invariant:   cp->symbol_at_put is preceded by a refcount increment (more usually a lookup)
1410   name->increment_refcount();
1411   signature->increment_refcount();
1412 
1413   int cp_length = _imcp_limit;
1414   ClassLoaderData* loader_data = holder->class_loader_data();
1415   constantPoolHandle cp;
1416   {
1417     ConstantPool* cp_oop = ConstantPool::allocate(loader_data, cp_length, CHECK_(empty));
1418     cp = constantPoolHandle(THREAD, cp_oop);
1419   }
1420   cp->copy_fields(holder->constants());
1421   cp->set_pool_holder(holder);
1422   cp->symbol_at_put(_imcp_invoke_name,       name);
1423   cp->symbol_at_put(_imcp_invoke_signature,  signature);
1424   cp->set_has_preresolution();
1425 
1426   // decide on access bits:  public or not?
1427   int flags_bits = (JVM_ACC_NATIVE | JVM_ACC_SYNTHETIC | JVM_ACC_FINAL);
1428   bool must_be_static = MethodHandles::is_signature_polymorphic_static(iid);
1429   if (must_be_static)  flags_bits |= JVM_ACC_STATIC;
1430   assert((flags_bits & JVM_ACC_PUBLIC) == 0, "do not expose these methods");
1431 
1432   methodHandle m;
1433   {
1434     InlineTableSizes sizes;
1435     Method* m_oop = Method::allocate(loader_data, 0,
1436                                      accessFlags_from(flags_bits), &sizes,
1437                                      ConstMethod::NORMAL,
1438                                      name,
1439                                      CHECK_(empty));
1440     m = methodHandle(THREAD, m_oop);
1441   }
1442   m->set_constants(cp());
1443   m->set_name_index(_imcp_invoke_name);
1444   m->set_signature_index(_imcp_invoke_signature);
1445   assert(MethodHandles::is_signature_polymorphic_name(m->name()), "");
1446   assert(m->signature() == signature, "");
1447   m->constMethod()->compute_from_signature(signature, must_be_static);
1448   m->init_intrinsic_id(klass_id_for_intrinsics(m->method_holder()));
1449   assert(m->is_method_handle_intrinsic(), "");
1450 #ifdef ASSERT
1451   if (!MethodHandles::is_signature_polymorphic(m->intrinsic_id()))  m->print();
1452   assert(MethodHandles::is_signature_polymorphic(m->intrinsic_id()), "must be an invoker");
1453   assert(m->intrinsic_id() == iid, "correctly predicted iid");
1454 #endif //ASSERT
1455 
1456   // Finally, set up its entry points.
1457   assert(m->can_be_statically_bound(), "");
1458   m->set_vtable_index(Method::nonvirtual_vtable_index);
1459   m->link_method(m, CHECK_(empty));
1460 
1461   if (iid == vmIntrinsics::_linkToNative) {
1462     m->set_interpreter_entry(m->adapter()->get_i2c_entry());
1463   }
1464   if (log_is_enabled(Debug, methodhandles)) {
1465     LogTarget(Debug, methodhandles) lt;
1466     LogStream ls(lt);
1467     m->print_on(&ls);
1468   }
1469 
1470   return m;
1471 }
1472 
1473 Klass* Method::check_non_bcp_klass(Klass* klass) {
1474   if (klass != nullptr && klass->class_loader() != nullptr) {
1475     if (klass->is_objArray_klass())
1476       klass = ObjArrayKlass::cast(klass)->bottom_klass();
1477     return klass;
1478   }
1479   return nullptr;
1480 }
1481 
1482 
1483 methodHandle Method::clone_with_new_data(const methodHandle& m, u_char* new_code, int new_code_length,
1484                                                 u_char* new_compressed_linenumber_table, int new_compressed_linenumber_size, TRAPS) {
1485   // Code below does not work for native methods - they should never get rewritten anyway
1486   assert(!m->is_native(), "cannot rewrite native methods");
1487   // Allocate new Method*
1488   AccessFlags flags = m->access_flags();
1489 
1490   ConstMethod* cm = m->constMethod();
1491   int checked_exceptions_len = cm->checked_exceptions_length();
1492   int localvariable_len = cm->localvariable_table_length();
1493   int exception_table_len = cm->exception_table_length();
1494   int method_parameters_len = cm->method_parameters_length();
1495   int method_annotations_len = cm->method_annotations_length();
1496   int parameter_annotations_len = cm->parameter_annotations_length();
1497   int type_annotations_len = cm->type_annotations_length();
1498   int default_annotations_len = cm->default_annotations_length();
1499 
1500   InlineTableSizes sizes(
1501       localvariable_len,
1502       new_compressed_linenumber_size,
1503       exception_table_len,
1504       checked_exceptions_len,
1505       method_parameters_len,
1506       cm->generic_signature_index(),
1507       method_annotations_len,
1508       parameter_annotations_len,
1509       type_annotations_len,
1510       default_annotations_len,
1511       0);
1512 
1513   ClassLoaderData* loader_data = m->method_holder()->class_loader_data();
1514   Method* newm_oop = Method::allocate(loader_data,
1515                                       new_code_length,
1516                                       flags,
1517                                       &sizes,
1518                                       m->method_type(),
1519                                       m->name(),
1520                                       CHECK_(methodHandle()));
1521   methodHandle newm (THREAD, newm_oop);
1522 
1523   // Create a shallow copy of Method part, but be careful to preserve the new ConstMethod*
1524   ConstMethod* newcm = newm->constMethod();
1525   int new_const_method_size = newm->constMethod()->size();
1526 
1527   // This works because the source and target are both Methods. Some compilers
1528   // (e.g., clang) complain that the target vtable pointer will be stomped,
1529   // so cast away newm()'s and m()'s Methodness.
1530   memcpy((void*)newm(), (void*)m(), sizeof(Method));
1531 
1532   // Create shallow copy of ConstMethod.
1533   memcpy(newcm, m->constMethod(), sizeof(ConstMethod));
1534 
1535   // Reset correct method/const method, method size, and parameter info
1536   newm->set_constMethod(newcm);
1537   newm->constMethod()->set_code_size(new_code_length);
1538   newm->constMethod()->set_constMethod_size(new_const_method_size);
1539   assert(newm->code_size() == new_code_length, "check");
1540   assert(newm->method_parameters_length() == method_parameters_len, "check");
1541   assert(newm->checked_exceptions_length() == checked_exceptions_len, "check");
1542   assert(newm->exception_table_length() == exception_table_len, "check");
1543   assert(newm->localvariable_table_length() == localvariable_len, "check");
1544   // Copy new byte codes
1545   memcpy(newm->code_base(), new_code, new_code_length);
1546   // Copy line number table
1547   if (new_compressed_linenumber_size > 0) {
1548     memcpy(newm->compressed_linenumber_table(),
1549            new_compressed_linenumber_table,
1550            new_compressed_linenumber_size);
1551   }
1552   // Copy method_parameters
1553   if (method_parameters_len > 0) {
1554     memcpy(newm->method_parameters_start(),
1555            m->method_parameters_start(),
1556            method_parameters_len * sizeof(MethodParametersElement));
1557   }
1558   // Copy checked_exceptions
1559   if (checked_exceptions_len > 0) {
1560     memcpy(newm->checked_exceptions_start(),
1561            m->checked_exceptions_start(),
1562            checked_exceptions_len * sizeof(CheckedExceptionElement));
1563   }
1564   // Copy exception table
1565   if (exception_table_len > 0) {
1566     memcpy(newm->exception_table_start(),
1567            m->exception_table_start(),
1568            exception_table_len * sizeof(ExceptionTableElement));
1569   }
1570   // Copy local variable number table
1571   if (localvariable_len > 0) {
1572     memcpy(newm->localvariable_table_start(),
1573            m->localvariable_table_start(),
1574            localvariable_len * sizeof(LocalVariableTableElement));
1575   }
1576   // Copy stackmap table
1577   if (m->has_stackmap_table()) {
1578     int code_attribute_length = m->stackmap_data()->length();
1579     Array<u1>* stackmap_data =
1580       MetadataFactory::new_array<u1>(loader_data, code_attribute_length, 0, CHECK_(methodHandle()));
1581     memcpy((void*)stackmap_data->adr_at(0),
1582            (void*)m->stackmap_data()->adr_at(0), code_attribute_length);
1583     newm->set_stackmap_data(stackmap_data);
1584   }
1585 
1586   // copy annotations over to new method
1587   newcm->copy_annotations_from(loader_data, cm, CHECK_(methodHandle()));
1588   return newm;
1589 }
1590 
1591 vmSymbolID Method::klass_id_for_intrinsics(const Klass* holder) {
1592   // if loader is not the default loader (i.e., non-null), we can't know the intrinsics
1593   // because we are not loading from core libraries
1594   // exception: the AES intrinsics come from lib/ext/sunjce_provider.jar
1595   // which does not use the class default class loader so we check for its loader here
1596   const InstanceKlass* ik = InstanceKlass::cast(holder);
1597   if ((ik->class_loader() != nullptr) && !SystemDictionary::is_platform_class_loader(ik->class_loader())) {
1598     return vmSymbolID::NO_SID;   // regardless of name, no intrinsics here
1599   }
1600 
1601   // see if the klass name is well-known:
1602   Symbol* klass_name = ik->name();
1603   vmSymbolID id = vmSymbols::find_sid(klass_name);
1604   if (id != vmSymbolID::NO_SID && vmIntrinsics::class_has_intrinsics(id)) {
1605     return id;
1606   } else {
1607     return vmSymbolID::NO_SID;
1608   }
1609 }
1610 
1611 void Method::init_intrinsic_id(vmSymbolID klass_id) {
1612   assert(_intrinsic_id == static_cast<int>(vmIntrinsics::_none), "do this just once");
1613   const uintptr_t max_id_uint = right_n_bits((int)(sizeof(_intrinsic_id) * BitsPerByte));
1614   assert((uintptr_t)vmIntrinsics::ID_LIMIT <= max_id_uint, "else fix size");
1615   assert(intrinsic_id_size_in_bytes() == sizeof(_intrinsic_id), "");
1616 
1617   // the klass name is well-known:
1618   assert(klass_id == klass_id_for_intrinsics(method_holder()), "must be");
1619   assert(klass_id != vmSymbolID::NO_SID, "caller responsibility");
1620 
1621   // ditto for method and signature:
1622   vmSymbolID name_id = vmSymbols::find_sid(name());
1623   if (klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1624       && klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle)
1625       && name_id == vmSymbolID::NO_SID) {
1626     return;
1627   }
1628   vmSymbolID sig_id = vmSymbols::find_sid(signature());
1629   if (klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle)
1630       && klass_id != VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle)
1631       && sig_id == vmSymbolID::NO_SID) {
1632     return;
1633   }
1634   jshort flags = access_flags().as_short();
1635 
1636   vmIntrinsics::ID id = vmIntrinsics::find_id(klass_id, name_id, sig_id, flags);
1637   if (id != vmIntrinsics::_none) {
1638     set_intrinsic_id(id);
1639     if (id == vmIntrinsics::_Class_cast) {
1640       // Even if the intrinsic is rejected, we want to inline this simple method.
1641       set_force_inline();
1642     }
1643     return;
1644   }
1645 
1646   // A few slightly irregular cases:
1647   switch (klass_id) {
1648   // Signature-polymorphic methods: MethodHandle.invoke*, InvokeDynamic.*., VarHandle
1649   case VM_SYMBOL_ENUM_NAME(java_lang_invoke_MethodHandle):
1650   case VM_SYMBOL_ENUM_NAME(java_lang_invoke_VarHandle):
1651     if (!is_native())  break;
1652     id = MethodHandles::signature_polymorphic_name_id(method_holder(), name());
1653     if (is_static() != MethodHandles::is_signature_polymorphic_static(id))
1654       id = vmIntrinsics::_none;
1655     break;
1656 
1657   default:
1658     break;
1659   }
1660 
1661   if (id != vmIntrinsics::_none) {
1662     // Set up its iid.  It is an alias method.
1663     set_intrinsic_id(id);
1664     return;
1665   }
1666 }
1667 
1668 bool Method::load_signature_classes(const methodHandle& m, TRAPS) {
1669   if (!THREAD->can_call_java()) {
1670     // There is nothing useful this routine can do from within the Compile thread.
1671     // Hopefully, the signature contains only well-known classes.
1672     // We could scan for this and return true/false, but the caller won't care.
1673     return false;
1674   }
1675   bool sig_is_loaded = true;
1676   ResourceMark rm(THREAD);
1677   for (ResolvingSignatureStream ss(m()); !ss.is_done(); ss.next()) {
1678     if (ss.is_reference()) {
1679       // load everything, including arrays "[Lfoo;"
1680       Klass* klass = ss.as_klass(SignatureStream::ReturnNull, THREAD);
1681       // We are loading classes eagerly. If a ClassNotFoundException or
1682       // a LinkageError was generated, be sure to ignore it.
1683       if (HAS_PENDING_EXCEPTION) {
1684         if (PENDING_EXCEPTION->is_a(vmClasses::ClassNotFoundException_klass()) ||
1685             PENDING_EXCEPTION->is_a(vmClasses::LinkageError_klass())) {
1686           CLEAR_PENDING_EXCEPTION;
1687         } else {
1688           return false;
1689         }
1690       }
1691       if( klass == nullptr) { sig_is_loaded = false; }
1692     }
1693   }
1694   return sig_is_loaded;
1695 }
1696 
1697 // Exposed so field engineers can debug VM
1698 void Method::print_short_name(outputStream* st) const {
1699   ResourceMark rm;
1700 #ifdef PRODUCT
1701   st->print(" %s::", method_holder()->external_name());
1702 #else
1703   st->print(" %s::", method_holder()->internal_name());
1704 #endif
1705   name()->print_symbol_on(st);
1706   if (WizardMode) signature()->print_symbol_on(st);
1707   else if (MethodHandles::is_signature_polymorphic(intrinsic_id()))
1708     MethodHandles::print_as_basic_type_signature_on(st, signature());
1709 }
1710 
1711 // Comparer for sorting an object array containing
1712 // Method*s.
1713 static int method_comparator(Method* a, Method* b) {
1714   return a->name()->fast_compare(b->name());
1715 }
1716 
1717 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
1718 // default_methods also uses this without the ordering for fast find_method
1719 void Method::sort_methods(Array<Method*>* methods, bool set_idnums, method_comparator_func func) {
1720   int length = methods->length();
1721   if (length > 1) {
1722     if (func == nullptr) {
1723       func = method_comparator;
1724     }
1725     {
1726       NoSafepointVerifier nsv;
1727       QuickSort::sort(methods->data(), length, func, /*idempotent=*/false);
1728     }
1729     // Reset method ordering
1730     if (set_idnums) {
1731       for (u2 i = 0; i < length; i++) {
1732         Method* m = methods->at(i);
1733         m->set_method_idnum(i);
1734         m->set_orig_method_idnum(i);
1735       }
1736     }
1737   }
1738 }
1739 
1740 //-----------------------------------------------------------------------------------
1741 // Non-product code unless JVM/TI needs it
1742 
1743 #if !defined(PRODUCT) || INCLUDE_JVMTI
1744 class SignatureTypePrinter : public SignatureTypeNames {
1745  private:
1746   outputStream* _st;
1747   bool _use_separator;
1748 
1749   void type_name(const char* name) {
1750     if (_use_separator) _st->print(", ");
1751     _st->print("%s", name);
1752     _use_separator = true;
1753   }
1754 
1755  public:
1756   SignatureTypePrinter(Symbol* signature, outputStream* st) : SignatureTypeNames(signature) {
1757     _st = st;
1758     _use_separator = false;
1759   }
1760 
1761   void print_parameters()              { _use_separator = false; do_parameters_on(this); }
1762   void print_returntype()              { _use_separator = false; do_type(return_type()); }
1763 };
1764 
1765 
1766 void Method::print_name(outputStream* st) const {
1767   Thread *thread = Thread::current();
1768   ResourceMark rm(thread);
1769   st->print("%s ", is_static() ? "static" : "virtual");
1770   if (WizardMode) {
1771     st->print("%s.", method_holder()->internal_name());
1772     name()->print_symbol_on(st);
1773     signature()->print_symbol_on(st);
1774   } else {
1775     SignatureTypePrinter sig(signature(), st);
1776     sig.print_returntype();
1777     st->print(" %s.", method_holder()->internal_name());
1778     name()->print_symbol_on(st);
1779     st->print("(");
1780     sig.print_parameters();
1781     st->print(")");
1782   }
1783 }
1784 #endif // !PRODUCT || INCLUDE_JVMTI
1785 
1786 
1787 void Method::print_codes_on(outputStream* st, int flags) const {
1788   print_codes_on(0, code_size(), st, flags);
1789 }
1790 
1791 void Method::print_codes_on(int from, int to, outputStream* st, int flags) const {
1792   Thread *thread = Thread::current();
1793   ResourceMark rm(thread);
1794   methodHandle mh (thread, (Method*)this);
1795   BytecodeTracer::print_method_codes(mh, from, to, st, flags);
1796 }
1797 
1798 CompressedLineNumberReadStream::CompressedLineNumberReadStream(u_char* buffer) : CompressedReadStream(buffer) {
1799   _bci = 0;
1800   _line = 0;
1801 };
1802 
1803 bool CompressedLineNumberReadStream::read_pair() {
1804   jubyte next = read_byte();
1805   // Check for terminator
1806   if (next == 0) return false;
1807   if (next == 0xFF) {
1808     // Escape character, regular compression used
1809     _bci  += read_signed_int();
1810     _line += read_signed_int();
1811   } else {
1812     // Single byte compression used
1813     _bci  += next >> 3;
1814     _line += next & 0x7;
1815   }
1816   return true;
1817 }
1818 
1819 #if INCLUDE_JVMTI
1820 
1821 Bytecodes::Code Method::orig_bytecode_at(int bci) const {
1822   BreakpointInfo* bp = method_holder()->breakpoints();
1823   for (; bp != nullptr; bp = bp->next()) {
1824     if (bp->match(this, bci)) {
1825       return bp->orig_bytecode();
1826     }
1827   }
1828   {
1829     ResourceMark rm;
1830     fatal("no original bytecode found in %s at bci %d", name_and_sig_as_C_string(), bci);
1831   }
1832   return Bytecodes::_shouldnotreachhere;
1833 }
1834 
1835 void Method::set_orig_bytecode_at(int bci, Bytecodes::Code code) {
1836   assert(code != Bytecodes::_breakpoint, "cannot patch breakpoints this way");
1837   BreakpointInfo* bp = method_holder()->breakpoints();
1838   for (; bp != nullptr; bp = bp->next()) {
1839     if (bp->match(this, bci)) {
1840       bp->set_orig_bytecode(code);
1841       // and continue, in case there is more than one
1842     }
1843   }
1844 }
1845 
1846 void Method::set_breakpoint(int bci) {
1847   InstanceKlass* ik = method_holder();
1848   BreakpointInfo *bp = new BreakpointInfo(this, bci);
1849   bp->set_next(ik->breakpoints());
1850   ik->set_breakpoints(bp);
1851   // do this last:
1852   bp->set(this);
1853 }
1854 
1855 static void clear_matches(Method* m, int bci) {
1856   InstanceKlass* ik = m->method_holder();
1857   BreakpointInfo* prev_bp = nullptr;
1858   BreakpointInfo* next_bp;
1859   for (BreakpointInfo* bp = ik->breakpoints(); bp != nullptr; bp = next_bp) {
1860     next_bp = bp->next();
1861     // bci value of -1 is used to delete all breakpoints in method m (ex: clear_all_breakpoint).
1862     if (bci >= 0 ? bp->match(m, bci) : bp->match(m)) {
1863       // do this first:
1864       bp->clear(m);
1865       // unhook it
1866       if (prev_bp != nullptr)
1867         prev_bp->set_next(next_bp);
1868       else
1869         ik->set_breakpoints(next_bp);
1870       delete bp;
1871       // When class is redefined JVMTI sets breakpoint in all versions of EMCP methods
1872       // at same location. So we have multiple matching (method_index and bci)
1873       // BreakpointInfo nodes in BreakpointInfo list. We should just delete one
1874       // breakpoint for clear_breakpoint request and keep all other method versions
1875       // BreakpointInfo for future clear_breakpoint request.
1876       // bcivalue of -1 is used to clear all breakpoints (see clear_all_breakpoints)
1877       // which is being called when class is unloaded. We delete all the Breakpoint
1878       // information for all versions of method. We may not correctly restore the original
1879       // bytecode in all method versions, but that is ok. Because the class is being unloaded
1880       // so these methods won't be used anymore.
1881       if (bci >= 0) {
1882         break;
1883       }
1884     } else {
1885       // This one is a keeper.
1886       prev_bp = bp;
1887     }
1888   }
1889 }
1890 
1891 void Method::clear_breakpoint(int bci) {
1892   assert(bci >= 0, "");
1893   clear_matches(this, bci);
1894 }
1895 
1896 void Method::clear_all_breakpoints() {
1897   clear_matches(this, -1);
1898 }
1899 
1900 #endif // INCLUDE_JVMTI
1901 
1902 int Method::invocation_count() const {
1903   MethodCounters* mcs = method_counters();
1904   MethodData* mdo = method_data();
1905   if (((mcs != nullptr) ? mcs->invocation_counter()->carry() : false) ||
1906       ((mdo != nullptr) ? mdo->invocation_counter()->carry() : false)) {
1907     return InvocationCounter::count_limit;
1908   } else {
1909     return ((mcs != nullptr) ? mcs->invocation_counter()->count() : 0) +
1910            ((mdo != nullptr) ? mdo->invocation_counter()->count() : 0);
1911   }
1912 }
1913 
1914 int Method::backedge_count() const {
1915   MethodCounters* mcs = method_counters();
1916   MethodData* mdo = method_data();
1917   if (((mcs != nullptr) ? mcs->backedge_counter()->carry() : false) ||
1918       ((mdo != nullptr) ? mdo->backedge_counter()->carry() : false)) {
1919     return InvocationCounter::count_limit;
1920   } else {
1921     return ((mcs != nullptr) ? mcs->backedge_counter()->count() : 0) +
1922            ((mdo != nullptr) ? mdo->backedge_counter()->count() : 0);
1923   }
1924 }
1925 
1926 int Method::highest_comp_level() const {
1927   const MethodCounters* mcs = method_counters();
1928   if (mcs != nullptr) {
1929     return mcs->highest_comp_level();
1930   } else {
1931     return CompLevel_none;
1932   }
1933 }
1934 
1935 int Method::highest_osr_comp_level() const {
1936   const MethodCounters* mcs = method_counters();
1937   if (mcs != nullptr) {
1938     return mcs->highest_osr_comp_level();
1939   } else {
1940     return CompLevel_none;
1941   }
1942 }
1943 
1944 void Method::set_highest_comp_level(int level) {
1945   MethodCounters* mcs = method_counters();
1946   if (mcs != nullptr) {
1947     mcs->set_highest_comp_level(level);
1948   }
1949 }
1950 
1951 void Method::set_highest_osr_comp_level(int level) {
1952   MethodCounters* mcs = method_counters();
1953   if (mcs != nullptr) {
1954     mcs->set_highest_osr_comp_level(level);
1955   }
1956 }
1957 
1958 #if INCLUDE_JVMTI
1959 
1960 BreakpointInfo::BreakpointInfo(Method* m, int bci) {
1961   _bci = bci;
1962   _name_index = m->name_index();
1963   _signature_index = m->signature_index();
1964   _orig_bytecode = (Bytecodes::Code) *m->bcp_from(_bci);
1965   if (_orig_bytecode == Bytecodes::_breakpoint)
1966     _orig_bytecode = m->orig_bytecode_at(_bci);
1967   _next = nullptr;
1968 }
1969 
1970 void BreakpointInfo::set(Method* method) {
1971 #ifdef ASSERT
1972   {
1973     Bytecodes::Code code = (Bytecodes::Code) *method->bcp_from(_bci);
1974     if (code == Bytecodes::_breakpoint)
1975       code = method->orig_bytecode_at(_bci);
1976     assert(orig_bytecode() == code, "original bytecode must be the same");
1977   }
1978 #endif
1979   Thread *thread = Thread::current();
1980   *method->bcp_from(_bci) = Bytecodes::_breakpoint;
1981   method->incr_number_of_breakpoints(thread);
1982   {
1983     // Deoptimize all dependents on this method
1984     HandleMark hm(thread);
1985     methodHandle mh(thread, method);
1986     CodeCache::mark_dependents_on_method_for_breakpoint(mh);
1987   }
1988 }
1989 
1990 void BreakpointInfo::clear(Method* method) {
1991   *method->bcp_from(_bci) = orig_bytecode();
1992   assert(method->number_of_breakpoints() > 0, "must not go negative");
1993   method->decr_number_of_breakpoints(Thread::current());
1994 }
1995 
1996 #endif // INCLUDE_JVMTI
1997 
1998 // jmethodID handling
1999 
2000 // This is a block allocating object, sort of like JNIHandleBlock, only a
2001 // lot simpler.
2002 // It's allocated on the CHeap because once we allocate a jmethodID, we can
2003 // never get rid of it.
2004 
2005 static const int min_block_size = 8;
2006 
2007 class JNIMethodBlockNode : public CHeapObj<mtClass> {
2008   friend class JNIMethodBlock;
2009   Method**        _methods;
2010   int             _number_of_methods;
2011   int             _top;
2012   JNIMethodBlockNode* _next;
2013 
2014  public:
2015 
2016   JNIMethodBlockNode(int num_methods = min_block_size);
2017 
2018   ~JNIMethodBlockNode() { FREE_C_HEAP_ARRAY(Method*, _methods); }
2019 
2020   void ensure_methods(int num_addl_methods) {
2021     if (_top < _number_of_methods) {
2022       num_addl_methods -= _number_of_methods - _top;
2023       if (num_addl_methods <= 0) {
2024         return;
2025       }
2026     }
2027     if (_next == nullptr) {
2028       _next = new JNIMethodBlockNode(MAX2(num_addl_methods, min_block_size));
2029     } else {
2030       _next->ensure_methods(num_addl_methods);
2031     }
2032   }
2033 };
2034 
2035 class JNIMethodBlock : public CHeapObj<mtClass> {
2036   JNIMethodBlockNode _head;
2037   JNIMethodBlockNode *_last_free;
2038  public:
2039   static Method* const _free_method;
2040 
2041   JNIMethodBlock(int initial_capacity = min_block_size)
2042       : _head(initial_capacity), _last_free(&_head) {}
2043 
2044   void ensure_methods(int num_addl_methods) {
2045     _last_free->ensure_methods(num_addl_methods);
2046   }
2047 
2048   Method** add_method(Method* m) {
2049     for (JNIMethodBlockNode* b = _last_free; b != nullptr; b = b->_next) {
2050       if (b->_top < b->_number_of_methods) {
2051         // top points to the next free entry.
2052         int i = b->_top;
2053         b->_methods[i] = m;
2054         b->_top++;
2055         _last_free = b;
2056         return &(b->_methods[i]);
2057       } else if (b->_top == b->_number_of_methods) {
2058         // if the next free entry ran off the block see if there's a free entry
2059         for (int i = 0; i < b->_number_of_methods; i++) {
2060           if (b->_methods[i] == _free_method) {
2061             b->_methods[i] = m;
2062             _last_free = b;
2063             return &(b->_methods[i]);
2064           }
2065         }
2066         // Only check each block once for frees.  They're very unlikely.
2067         // Increment top past the end of the block.
2068         b->_top++;
2069       }
2070       // need to allocate a next block.
2071       if (b->_next == nullptr) {
2072         b->_next = _last_free = new JNIMethodBlockNode();
2073       }
2074     }
2075     guarantee(false, "Should always allocate a free block");
2076     return nullptr;
2077   }
2078 
2079   bool contains(Method** m) {
2080     if (m == nullptr) return false;
2081     for (JNIMethodBlockNode* b = &_head; b != nullptr; b = b->_next) {
2082       if (b->_methods <= m && m < b->_methods + b->_number_of_methods) {
2083         // This is a bit of extra checking, for two reasons.  One is
2084         // that contains() deals with pointers that are passed in by
2085         // JNI code, so making sure that the pointer is aligned
2086         // correctly is valuable.  The other is that <= and > are
2087         // technically not defined on pointers, so the if guard can
2088         // pass spuriously; no modern compiler is likely to make that
2089         // a problem, though (and if one did, the guard could also
2090         // fail spuriously, which would be bad).
2091         ptrdiff_t idx = m - b->_methods;
2092         if (b->_methods + idx == m) {
2093           return true;
2094         }
2095       }
2096     }
2097     return false;  // not found
2098   }
2099 
2100   // During class unloading the methods are cleared, which is different
2101   // than freed.
2102   void clear_all_methods() {
2103     for (JNIMethodBlockNode* b = &_head; b != nullptr; b = b->_next) {
2104       for (int i = 0; i< b->_number_of_methods; i++) {
2105         b->_methods[i] = nullptr;
2106       }
2107     }
2108   }
2109 #ifndef PRODUCT
2110   int count_methods() {
2111     // count all allocated methods
2112     int count = 0;
2113     for (JNIMethodBlockNode* b = &_head; b != nullptr; b = b->_next) {
2114       for (int i = 0; i< b->_number_of_methods; i++) {
2115         if (b->_methods[i] != _free_method) count++;
2116       }
2117     }
2118     return count;
2119   }
2120 #endif // PRODUCT
2121 };
2122 
2123 // Something that can't be mistaken for an address or a markWord
2124 Method* const JNIMethodBlock::_free_method = (Method*)55;
2125 
2126 JNIMethodBlockNode::JNIMethodBlockNode(int num_methods) : _top(0), _next(nullptr) {
2127   _number_of_methods = MAX2(num_methods, min_block_size);
2128   _methods = NEW_C_HEAP_ARRAY(Method*, _number_of_methods, mtInternal);
2129   for (int i = 0; i < _number_of_methods; i++) {
2130     _methods[i] = JNIMethodBlock::_free_method;
2131   }
2132 }
2133 
2134 void Method::ensure_jmethod_ids(ClassLoaderData* cld, int capacity) {
2135   // Have to add jmethod_ids() to class loader data thread-safely.
2136   // Also have to add the method to the list safely, which the lock
2137   // protects as well.
2138   MutexLocker ml(JmethodIdCreation_lock,  Mutex::_no_safepoint_check_flag);
2139   if (cld->jmethod_ids() == nullptr) {
2140     cld->set_jmethod_ids(new JNIMethodBlock(capacity));
2141   } else {
2142     cld->jmethod_ids()->ensure_methods(capacity);
2143   }
2144 }
2145 
2146 // Add a method id to the jmethod_ids
2147 jmethodID Method::make_jmethod_id(ClassLoaderData* cld, Method* m) {
2148   // Have to add jmethod_ids() to class loader data thread-safely.
2149   // Also have to add the method to the list safely, which the lock
2150   // protects as well.
2151   assert(JmethodIdCreation_lock->owned_by_self(), "sanity check");
2152 
2153   ResourceMark rm;
2154   log_debug(jmethod)("Creating jmethodID for Method %s", m->external_name());
2155   if (cld->jmethod_ids() == nullptr) {
2156     cld->set_jmethod_ids(new JNIMethodBlock());
2157   }
2158   // jmethodID is a pointer to Method*
2159   return (jmethodID)cld->jmethod_ids()->add_method(m);
2160 }
2161 
2162 jmethodID Method::jmethod_id() {
2163   methodHandle mh(Thread::current(), this);
2164   return method_holder()->get_jmethod_id(mh);
2165 }
2166 
2167 void Method::change_method_associated_with_jmethod_id(jmethodID jmid, Method* new_method) {
2168   // Can't assert the method_holder is the same because the new method has the
2169   // scratch method holder.
2170   assert(resolve_jmethod_id(jmid)->method_holder()->class_loader()
2171            == new_method->method_holder()->class_loader() ||
2172            new_method->method_holder()->class_loader() == nullptr, // allow Unsafe substitution
2173          "changing to a different class loader");
2174   // Just change the method in place, jmethodID pointer doesn't change.
2175   *((Method**)jmid) = new_method;
2176 }
2177 
2178 bool Method::is_method_id(jmethodID mid) {
2179   Method* m = resolve_jmethod_id(mid);
2180   assert(m != nullptr, "should be called with non-null method");
2181   InstanceKlass* ik = m->method_holder();
2182   ClassLoaderData* cld = ik->class_loader_data();
2183   if (cld->jmethod_ids() == nullptr) return false;
2184   return (cld->jmethod_ids()->contains((Method**)mid));
2185 }
2186 
2187 Method* Method::checked_resolve_jmethod_id(jmethodID mid) {
2188   if (mid == nullptr) return nullptr;
2189   Method* o = resolve_jmethod_id(mid);
2190   if (o == nullptr || o == JNIMethodBlock::_free_method) {
2191     return nullptr;
2192   }
2193   // Method should otherwise be valid. Assert for testing.
2194   assert(is_valid_method(o), "should be valid jmethodid");
2195   // If the method's class holder object is unreferenced, but not yet marked as
2196   // unloaded, we need to return null here too because after a safepoint, its memory
2197   // will be reclaimed.
2198   return o->method_holder()->is_loader_alive() ? o : nullptr;
2199 };
2200 
2201 void Method::set_on_stack(const bool value) {
2202   // Set both the method itself and its constant pool.  The constant pool
2203   // on stack means some method referring to it is also on the stack.
2204   constants()->set_on_stack(value);
2205 
2206   bool already_set = on_stack_flag();
2207   set_on_stack_flag(value);
2208   if (value && !already_set) {
2209     MetadataOnStackMark::record(this);
2210   }
2211 }
2212 
2213 void Method::record_gc_epoch() {
2214   // If any method is on the stack in continuations, none of them can be reclaimed,
2215   // so save the marking cycle to check for the whole class in the cpCache.
2216   // The cpCache is writeable.
2217   constants()->cache()->record_gc_epoch();
2218 }
2219 
2220 // Called when the class loader is unloaded to make all methods weak.
2221 void Method::clear_jmethod_ids(ClassLoaderData* loader_data) {
2222   loader_data->jmethod_ids()->clear_all_methods();
2223 }
2224 
2225 void Method::clear_jmethod_id() {
2226   // Being at a safepoint prevents racing against other class redefinitions
2227   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
2228   // The jmethodID is not stored in the Method instance, we need to look it up first
2229   jmethodID methodid = find_jmethod_id_or_null();
2230   // We need to make sure that jmethodID actually resolves to this method
2231   // - multiple redefined versions may share jmethodID slots and if a method
2232   //   has already been rewired to a newer version we could be removing reference
2233   //   to a still existing method instance
2234   if (methodid != nullptr && *((Method**)methodid) == this) {
2235     *((Method**)methodid) = nullptr;
2236   }
2237 }
2238 
2239 bool Method::has_method_vptr(const void* ptr) {
2240   Method m;
2241   // This assumes that the vtbl pointer is the first word of a C++ object.
2242   return dereference_vptr(&m) == dereference_vptr(ptr);
2243 }
2244 
2245 // Check that this pointer is valid by checking that the vtbl pointer matches
2246 bool Method::is_valid_method(const Method* m) {
2247   if (m == nullptr) {
2248     return false;
2249   } else if ((intptr_t(m) & (wordSize-1)) != 0) {
2250     // Quick sanity check on pointer.
2251     return false;
2252   } else if (!os::is_readable_range(m, m + 1)) {
2253     return false;
2254   } else if (m->is_shared()) {
2255     return CppVtables::is_valid_shared_method(m);
2256   } else if (Metaspace::contains_non_shared(m)) {
2257     return has_method_vptr((const void*)m);
2258   } else {
2259     return false;
2260   }
2261 }
2262 
2263 #ifndef PRODUCT
2264 void Method::print_jmethod_ids_count(const ClassLoaderData* loader_data, outputStream* out) {
2265   out->print("%d", loader_data->jmethod_ids()->count_methods());
2266 }
2267 #endif // PRODUCT
2268 
2269 
2270 // Printing
2271 
2272 #ifndef PRODUCT
2273 
2274 void Method::print_on(outputStream* st) const {
2275   ResourceMark rm;
2276   assert(is_method(), "must be method");
2277   st->print_cr("%s", internal_name());
2278   st->print_cr(" - this oop:          " PTR_FORMAT, p2i(this));
2279   st->print   (" - method holder:     "); method_holder()->print_value_on(st); st->cr();
2280   st->print   (" - constants:         " PTR_FORMAT " ", p2i(constants()));
2281   constants()->print_value_on(st); st->cr();
2282   st->print   (" - access:            0x%x  ", access_flags().as_int()); access_flags().print_on(st); st->cr();
2283   st->print   (" - flags:             0x%x  ", _flags.as_int()); _flags.print_on(st); st->cr();
2284   st->print   (" - name:              ");    name()->print_value_on(st); st->cr();
2285   st->print   (" - signature:         ");    signature()->print_value_on(st); st->cr();
2286   st->print_cr(" - max stack:         %d",   max_stack());
2287   st->print_cr(" - max locals:        %d",   max_locals());
2288   st->print_cr(" - size of params:    %d",   size_of_parameters());
2289   st->print_cr(" - method size:       %d",   method_size());
2290   if (intrinsic_id() != vmIntrinsics::_none)
2291     st->print_cr(" - intrinsic id:      %d %s", vmIntrinsics::as_int(intrinsic_id()), vmIntrinsics::name_at(intrinsic_id()));
2292   if (highest_comp_level() != CompLevel_none)
2293     st->print_cr(" - highest level:     %d", highest_comp_level());
2294   st->print_cr(" - vtable index:      %d",   _vtable_index);
2295   st->print_cr(" - i2i entry:         " PTR_FORMAT, p2i(interpreter_entry()));
2296   st->print(   " - adapters:          ");
2297   AdapterHandlerEntry* a = ((Method*)this)->adapter();
2298   if (a == nullptr)
2299     st->print_cr(PTR_FORMAT, p2i(a));
2300   else
2301     a->print_adapter_on(st);
2302   st->print_cr(" - compiled entry     " PTR_FORMAT, p2i(from_compiled_entry()));
2303   st->print_cr(" - code size:         %d",   code_size());
2304   if (code_size() != 0) {
2305     st->print_cr(" - code start:        " PTR_FORMAT, p2i(code_base()));
2306     st->print_cr(" - code end (excl):   " PTR_FORMAT, p2i(code_base() + code_size()));
2307   }
2308   if (method_data() != nullptr) {
2309     st->print_cr(" - method data:       " PTR_FORMAT, p2i(method_data()));
2310   }
2311   st->print_cr(" - checked ex length: %d",   checked_exceptions_length());
2312   if (checked_exceptions_length() > 0) {
2313     CheckedExceptionElement* table = checked_exceptions_start();
2314     st->print_cr(" - checked ex start:  " PTR_FORMAT, p2i(table));
2315     if (Verbose) {
2316       for (int i = 0; i < checked_exceptions_length(); i++) {
2317         st->print_cr("   - throws %s", constants()->printable_name_at(table[i].class_cp_index));
2318       }
2319     }
2320   }
2321   if (has_linenumber_table()) {
2322     u_char* table = compressed_linenumber_table();
2323     st->print_cr(" - linenumber start:  " PTR_FORMAT, p2i(table));
2324     if (Verbose) {
2325       CompressedLineNumberReadStream stream(table);
2326       while (stream.read_pair()) {
2327         st->print_cr("   - line %d: %d", stream.line(), stream.bci());
2328       }
2329     }
2330   }
2331   st->print_cr(" - localvar length:   %d",   localvariable_table_length());
2332   if (localvariable_table_length() > 0) {
2333     LocalVariableTableElement* table = localvariable_table_start();
2334     st->print_cr(" - localvar start:    " PTR_FORMAT, p2i(table));
2335     if (Verbose) {
2336       for (int i = 0; i < localvariable_table_length(); i++) {
2337         int bci = table[i].start_bci;
2338         int len = table[i].length;
2339         const char* name = constants()->printable_name_at(table[i].name_cp_index);
2340         const char* desc = constants()->printable_name_at(table[i].descriptor_cp_index);
2341         int slot = table[i].slot;
2342         st->print_cr("   - %s %s bci=%d len=%d slot=%d", desc, name, bci, len, slot);
2343       }
2344     }
2345   }
2346   if (code() != nullptr) {
2347     st->print   (" - compiled code: ");
2348     code()->print_value_on(st);
2349   }
2350   if (is_native()) {
2351     st->print_cr(" - native function:   " PTR_FORMAT, p2i(native_function()));
2352     st->print_cr(" - signature handler: " PTR_FORMAT, p2i(signature_handler()));
2353   }
2354 }
2355 
2356 void Method::print_linkage_flags(outputStream* st) {
2357   access_flags().print_on(st);
2358   if (is_default_method()) {
2359     st->print("default ");
2360   }
2361   if (is_overpass()) {
2362     st->print("overpass ");
2363   }
2364 }
2365 #endif //PRODUCT
2366 
2367 void Method::print_value_on(outputStream* st) const {
2368   assert(is_method(), "must be method");
2369   st->print("%s", internal_name());
2370   print_address_on(st);
2371   st->print(" ");
2372   name()->print_value_on(st);
2373   st->print(" ");
2374   signature()->print_value_on(st);
2375   st->print(" in ");
2376   method_holder()->print_value_on(st);
2377   if (WizardMode) st->print("#%d", _vtable_index);
2378   if (WizardMode) st->print("[%d,%d]", size_of_parameters(), max_locals());
2379   if (WizardMode && code() != nullptr) st->print(" ((nmethod*)%p)", code());
2380 }
2381 
2382 // Verification
2383 
2384 void Method::verify_on(outputStream* st) {
2385   guarantee(is_method(), "object must be method");
2386   guarantee(constants()->is_constantPool(), "should be constant pool");
2387   MethodData* md = method_data();
2388   guarantee(md == nullptr ||
2389       md->is_methodData(), "should be method data");
2390 }