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