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