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