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