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