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