1 /*
  2  * Copyright (c) 2012, 2017, 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 #include "precompiled.hpp"
 25 #include "jvm.h"
 26 #include "asm/codeBuffer.hpp"
 27 #include "classfile/javaClasses.inline.hpp"
 28 #include "code/codeCache.hpp"
 29 #include "compiler/compileBroker.hpp"
 30 #include "compiler/disassembler.hpp"
 31 #include "jvmci/jvmciRuntime.hpp"
 32 #include "jvmci/jvmciCompilerToVM.hpp"
 33 #include "jvmci/jvmciCompiler.hpp"
 34 #include "jvmci/jvmciJavaClasses.hpp"
 35 #include "jvmci/jvmciEnv.hpp"
 36 #include "logging/log.hpp"
 37 #include "memory/oopFactory.hpp"
 38 #include "memory/resourceArea.hpp"
 39 #include "oops/oop.inline.hpp"
 40 #include "oops/objArrayOop.inline.hpp"
 41 #include "runtime/biasedLocking.hpp"
 42 #include "runtime/interfaceSupport.hpp"
 43 #include "runtime/reflection.hpp"
 44 #include "runtime/sharedRuntime.hpp"
 45 #include "runtime/threadSMR.hpp"
 46 #include "utilities/debug.hpp"
 47 #include "utilities/defaultStream.hpp"
 48 #include "utilities/macros.hpp"
 49 
 50 #if defined(_MSC_VER)
 51 #define strtoll _strtoi64
 52 #endif
 53 
 54 jobject JVMCIRuntime::_HotSpotJVMCIRuntime_instance = NULL;
 55 bool JVMCIRuntime::_HotSpotJVMCIRuntime_initialized = false;
 56 bool JVMCIRuntime::_well_known_classes_initialized = false;
 57 int JVMCIRuntime::_trivial_prefixes_count = 0;
 58 char** JVMCIRuntime::_trivial_prefixes = NULL;
 59 JVMCIRuntime::CompLevelAdjustment JVMCIRuntime::_comp_level_adjustment = JVMCIRuntime::none;
 60 bool JVMCIRuntime::_shutdown_called = false;
 61 
 62 BasicType JVMCIRuntime::kindToBasicType(Handle kind, TRAPS) {
 63   if (kind.is_null()) {
 64     THROW_(vmSymbols::java_lang_NullPointerException(), T_ILLEGAL);
 65   }
 66   jchar ch = JavaKind::typeChar(kind);
 67   switch(ch) {
 68     case 'Z': return T_BOOLEAN;
 69     case 'B': return T_BYTE;
 70     case 'S': return T_SHORT;
 71     case 'C': return T_CHAR;
 72     case 'I': return T_INT;
 73     case 'F': return T_FLOAT;
 74     case 'J': return T_LONG;
 75     case 'D': return T_DOUBLE;
 76     case 'A': return T_OBJECT;
 77     case '-': return T_ILLEGAL;
 78     default:
 79       JVMCI_ERROR_(T_ILLEGAL, "unexpected Kind: %c", ch);
 80   }
 81 }
 82 
 83 // Simple helper to see if the caller of a runtime stub which
 84 // entered the VM has been deoptimized
 85 
 86 static bool caller_is_deopted() {
 87   JavaThread* thread = JavaThread::current();
 88   RegisterMap reg_map(thread, false);
 89   frame runtime_frame = thread->last_frame();
 90   frame caller_frame = runtime_frame.sender(&reg_map);
 91   assert(caller_frame.is_compiled_frame(), "must be compiled");
 92   return caller_frame.is_deoptimized_frame();
 93 }
 94 
 95 // Stress deoptimization
 96 static void deopt_caller() {
 97   if ( !caller_is_deopted()) {
 98     JavaThread* thread = JavaThread::current();
 99     RegisterMap reg_map(thread, false);
100     frame runtime_frame = thread->last_frame();
101     frame caller_frame = runtime_frame.sender(&reg_map);
102     Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
103     assert(caller_is_deopted(), "Must be deoptimized");
104   }
105 }
106 
107 JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_instance(JavaThread* thread, Klass* klass))
108   JRT_BLOCK;
109   assert(klass->is_klass(), "not a class");
110   Handle holder(THREAD, klass->klass_holder()); // keep the klass alive
111   InstanceKlass* ik = InstanceKlass::cast(klass);
112   ik->check_valid_for_instantiation(true, CHECK);
113   // make sure klass is initialized
114   ik->initialize(CHECK);
115   // allocate instance and return via TLS
116   oop obj = ik->allocate_instance(CHECK);
117   thread->set_vm_result(obj);
118   JRT_BLOCK_END;
119   SharedRuntime::on_slowpath_allocation_exit(thread);
120 JRT_END
121 
122 JRT_BLOCK_ENTRY(void, JVMCIRuntime::new_array(JavaThread* thread, Klass* array_klass, jint length))
123   JRT_BLOCK;
124   // Note: no handle for klass needed since they are not used
125   //       anymore after new_objArray() and no GC can happen before.
126   //       (This may have to change if this code changes!)
127   assert(array_klass->is_klass(), "not a class");
128   oop obj;
129   if (array_klass->is_typeArray_klass()) {
130     BasicType elt_type = TypeArrayKlass::cast(array_klass)->element_type();
131     obj = oopFactory::new_typeArray(elt_type, length, CHECK);
132   } else {
133     Handle holder(THREAD, array_klass->klass_holder()); // keep the klass alive
134     Klass* elem_klass = ObjArrayKlass::cast(array_klass)->element_klass();
135     obj = oopFactory::new_objArray(elem_klass, length, CHECK);
136   }
137   thread->set_vm_result(obj);
138   // This is pretty rare but this runtime patch is stressful to deoptimization
139   // if we deoptimize here so force a deopt to stress the path.
140   if (DeoptimizeALot) {
141     static int deopts = 0;
142     // Alternate between deoptimizing and raising an error (which will also cause a deopt)
143     if (deopts++ % 2 == 0) {
144       ResourceMark rm(THREAD);
145       THROW(vmSymbols::java_lang_OutOfMemoryError());
146     } else {
147       deopt_caller();
148     }
149   }
150   JRT_BLOCK_END;
151   SharedRuntime::on_slowpath_allocation_exit(thread);
152 JRT_END
153 
154 JRT_ENTRY(void, JVMCIRuntime::new_multi_array(JavaThread* thread, Klass* klass, int rank, jint* dims))
155   assert(klass->is_klass(), "not a class");
156   assert(rank >= 1, "rank must be nonzero");
157   Handle holder(THREAD, klass->klass_holder()); // keep the klass alive
158   oop obj = ArrayKlass::cast(klass)->multi_allocate(rank, dims, CHECK);
159   thread->set_vm_result(obj);
160 JRT_END
161 
162 JRT_ENTRY(void, JVMCIRuntime::dynamic_new_array(JavaThread* thread, oopDesc* element_mirror, jint length))
163   oop obj = Reflection::reflect_new_array(element_mirror, length, CHECK);
164   thread->set_vm_result(obj);
165 JRT_END
166 
167 JRT_ENTRY(void, JVMCIRuntime::dynamic_new_instance(JavaThread* thread, oopDesc* type_mirror))
168   InstanceKlass* klass = InstanceKlass::cast(java_lang_Class::as_Klass(type_mirror));
169 
170   if (klass == NULL) {
171     ResourceMark rm(THREAD);
172     THROW(vmSymbols::java_lang_InstantiationException());
173   }
174 
175   // Create new instance (the receiver)
176   klass->check_valid_for_instantiation(false, CHECK);
177 
178   // Make sure klass gets initialized
179   klass->initialize(CHECK);
180 
181   oop obj = klass->allocate_instance(CHECK);
182   thread->set_vm_result(obj);
183 JRT_END
184 
185 extern void vm_exit(int code);
186 
187 // Enter this method from compiled code handler below. This is where we transition
188 // to VM mode. This is done as a helper routine so that the method called directly
189 // from compiled code does not have to transition to VM. This allows the entry
190 // method to see if the nmethod that we have just looked up a handler for has
191 // been deoptimized while we were in the vm. This simplifies the assembly code
192 // cpu directories.
193 //
194 // We are entering here from exception stub (via the entry method below)
195 // If there is a compiled exception handler in this method, we will continue there;
196 // otherwise we will unwind the stack and continue at the caller of top frame method
197 // Note: we enter in Java using a special JRT wrapper. This wrapper allows us to
198 // control the area where we can allow a safepoint. After we exit the safepoint area we can
199 // check to see if the handler we are going to return is now in a nmethod that has
200 // been deoptimized. If that is the case we return the deopt blob
201 // unpack_with_exception entry instead. This makes life for the exception blob easier
202 // because making that same check and diverting is painful from assembly language.
203 JRT_ENTRY_NO_ASYNC(static address, exception_handler_for_pc_helper(JavaThread* thread, oopDesc* ex, address pc, CompiledMethod*& cm))
204   // Reset method handle flag.
205   thread->set_is_method_handle_return(false);
206 
207   Handle exception(thread, ex);
208   cm = CodeCache::find_compiled(pc);
209   assert(cm != NULL, "this is not a compiled method");
210   // Adjust the pc as needed/
211   if (cm->is_deopt_pc(pc)) {
212     RegisterMap map(thread, false);
213     frame exception_frame = thread->last_frame().sender(&map);
214     // if the frame isn't deopted then pc must not correspond to the caller of last_frame
215     assert(exception_frame.is_deoptimized_frame(), "must be deopted");
216     pc = exception_frame.pc();
217   }
218 #ifdef ASSERT
219   assert(exception.not_null(), "NULL exceptions should be handled by throw_exception");
220   // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
221   if (!(exception->is_a(SystemDictionary::Throwable_klass()))) {
222     if (ExitVMOnVerifyError) vm_exit(-1);
223     ShouldNotReachHere();
224   }
225 #endif
226 
227   // Check the stack guard pages and reenable them if necessary and there is
228   // enough space on the stack to do so.  Use fast exceptions only if the guard
229   // pages are enabled.
230   bool guard_pages_enabled = thread->stack_guards_enabled();
231   if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack();
232 
233   if (JvmtiExport::can_post_on_exceptions()) {
234     // To ensure correct notification of exception catches and throws
235     // we have to deoptimize here.  If we attempted to notify the
236     // catches and throws during this exception lookup it's possible
237     // we could deoptimize on the way out of the VM and end back in
238     // the interpreter at the throw site.  This would result in double
239     // notifications since the interpreter would also notify about
240     // these same catches and throws as it unwound the frame.
241 
242     RegisterMap reg_map(thread);
243     frame stub_frame = thread->last_frame();
244     frame caller_frame = stub_frame.sender(&reg_map);
245 
246     // We don't really want to deoptimize the nmethod itself since we
247     // can actually continue in the exception handler ourselves but I
248     // don't see an easy way to have the desired effect.
249     Deoptimization::deoptimize_frame(thread, caller_frame.id(), Deoptimization::Reason_constraint);
250     assert(caller_is_deopted(), "Must be deoptimized");
251 
252     return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
253   }
254 
255   // ExceptionCache is used only for exceptions at call sites and not for implicit exceptions
256   if (guard_pages_enabled) {
257     address fast_continuation = cm->handler_for_exception_and_pc(exception, pc);
258     if (fast_continuation != NULL) {
259       // Set flag if return address is a method handle call site.
260       thread->set_is_method_handle_return(cm->is_method_handle_return(pc));
261       return fast_continuation;
262     }
263   }
264 
265   // If the stack guard pages are enabled, check whether there is a handler in
266   // the current method.  Otherwise (guard pages disabled), force an unwind and
267   // skip the exception cache update (i.e., just leave continuation==NULL).
268   address continuation = NULL;
269   if (guard_pages_enabled) {
270 
271     // New exception handling mechanism can support inlined methods
272     // with exception handlers since the mappings are from PC to PC
273 
274     // debugging support
275     // tracing
276     if (log_is_enabled(Info, exceptions)) {
277       ResourceMark rm;
278       stringStream tempst;
279       tempst.print("compiled method <%s>\n"
280                    " at PC" INTPTR_FORMAT " for thread " INTPTR_FORMAT,
281                    cm->method()->print_value_string(), p2i(pc), p2i(thread));
282       Exceptions::log_exception(exception, tempst);
283     }
284     // for AbortVMOnException flag
285     NOT_PRODUCT(Exceptions::debug_check_abort(exception));
286 
287     // Clear out the exception oop and pc since looking up an
288     // exception handler can cause class loading, which might throw an
289     // exception and those fields are expected to be clear during
290     // normal bytecode execution.
291     thread->clear_exception_oop_and_pc();
292 
293     bool recursive_exception = false;
294     continuation = SharedRuntime::compute_compiled_exc_handler(cm, pc, exception, false, false, recursive_exception);
295     // If an exception was thrown during exception dispatch, the exception oop may have changed
296     thread->set_exception_oop(exception());
297     thread->set_exception_pc(pc);
298 
299     // the exception cache is used only by non-implicit exceptions
300     // Update the exception cache only when there didn't happen
301     // another exception during the computation of the compiled
302     // exception handler. Checking for exception oop equality is not
303     // sufficient because some exceptions are pre-allocated and reused.
304     if (continuation != NULL && !recursive_exception && !SharedRuntime::deopt_blob()->contains(continuation)) {
305       cm->add_handler_for_exception_and_pc(exception, pc, continuation);
306     }
307   }
308 
309   // Set flag if return address is a method handle call site.
310   thread->set_is_method_handle_return(cm->is_method_handle_return(pc));
311 
312   if (log_is_enabled(Info, exceptions)) {
313     ResourceMark rm;
314     log_info(exceptions)("Thread " PTR_FORMAT " continuing at PC " PTR_FORMAT
315                          " for exception thrown at PC " PTR_FORMAT,
316                          p2i(thread), p2i(continuation), p2i(pc));
317   }
318 
319   return continuation;
320 JRT_END
321 
322 // Enter this method from compiled code only if there is a Java exception handler
323 // in the method handling the exception.
324 // We are entering here from exception stub. We don't do a normal VM transition here.
325 // We do it in a helper. This is so we can check to see if the nmethod we have just
326 // searched for an exception handler has been deoptimized in the meantime.
327 address JVMCIRuntime::exception_handler_for_pc(JavaThread* thread) {
328   oop exception = thread->exception_oop();
329   address pc = thread->exception_pc();
330   // Still in Java mode
331   DEBUG_ONLY(ResetNoHandleMark rnhm);
332   CompiledMethod* cm = NULL;
333   address continuation = NULL;
334   {
335     // Enter VM mode by calling the helper
336     ResetNoHandleMark rnhm;
337     continuation = exception_handler_for_pc_helper(thread, exception, pc, cm);
338   }
339   // Back in JAVA, use no oops DON'T safepoint
340 
341   // Now check to see if the compiled method we were called from is now deoptimized.
342   // If so we must return to the deopt blob and deoptimize the nmethod
343   if (cm != NULL && caller_is_deopted()) {
344     continuation = SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
345   }
346 
347   assert(continuation != NULL, "no handler found");
348   return continuation;
349 }
350 
351 JRT_ENTRY_NO_ASYNC(void, JVMCIRuntime::monitorenter(JavaThread* thread, oopDesc* obj, BasicLock* lock))
352   IF_TRACE_jvmci_3 {
353     char type[O_BUFLEN];
354     obj->klass()->name()->as_C_string(type, O_BUFLEN);
355     markOop mark = obj->mark();
356     TRACE_jvmci_3("%s: entered locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(mark), p2i(lock));
357     tty->flush();
358   }
359 #ifdef ASSERT
360   if (PrintBiasedLockingStatistics) {
361     Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
362   }
363 #endif
364   Handle h_obj(thread, obj);
365   if (UseBiasedLocking) {
366     // Retry fast entry if bias is revoked to avoid unnecessary inflation
367     ObjectSynchronizer::fast_enter(h_obj, lock, true, CHECK);
368   } else {
369     if (JVMCIUseFastLocking) {
370       // When using fast locking, the compiled code has already tried the fast case
371       ObjectSynchronizer::slow_enter(h_obj, lock, THREAD);
372     } else {
373       ObjectSynchronizer::fast_enter(h_obj, lock, false, THREAD);
374     }
375   }
376   TRACE_jvmci_3("%s: exiting locking slow with obj=" INTPTR_FORMAT, thread->name(), p2i(obj));
377 JRT_END
378 
379 JRT_LEAF(void, JVMCIRuntime::monitorexit(JavaThread* thread, oopDesc* obj, BasicLock* lock))
380   assert(thread == JavaThread::current(), "threads must correspond");
381   assert(thread->last_Java_sp(), "last_Java_sp must be set");
382   // monitorexit is non-blocking (leaf routine) => no exceptions can be thrown
383   EXCEPTION_MARK;
384 
385 #ifdef DEBUG
386   if (!oopDesc::is_oop(obj)) {
387     ResetNoHandleMark rhm;
388     nmethod* method = thread->last_frame().cb()->as_nmethod_or_null();
389     if (method != NULL) {
390       tty->print_cr("ERROR in monitorexit in method %s wrong obj " INTPTR_FORMAT, method->name(), p2i(obj));
391     }
392     thread->print_stack_on(tty);
393     assert(false, "invalid lock object pointer dected");
394   }
395 #endif
396 
397   if (JVMCIUseFastLocking) {
398     // When using fast locking, the compiled code has already tried the fast case
399     ObjectSynchronizer::slow_exit(obj, lock, THREAD);
400   } else {
401     ObjectSynchronizer::fast_exit(obj, lock, THREAD);
402   }
403   IF_TRACE_jvmci_3 {
404     char type[O_BUFLEN];
405     obj->klass()->name()->as_C_string(type, O_BUFLEN);
406     TRACE_jvmci_3("%s: exited locking slow case with obj=" INTPTR_FORMAT ", type=%s, mark=" INTPTR_FORMAT ", lock=" INTPTR_FORMAT, thread->name(), p2i(obj), type, p2i(obj->mark()), p2i(lock));
407     tty->flush();
408   }
409 JRT_END
410 
411 JRT_ENTRY(void, JVMCIRuntime::throw_and_post_jvmti_exception(JavaThread* thread, const char* exception, const char* message))
412   TempNewSymbol symbol = SymbolTable::new_symbol(exception, CHECK);
413   SharedRuntime::throw_and_post_jvmti_exception(thread, symbol, message);
414 JRT_END
415 
416 JRT_ENTRY(void, JVMCIRuntime::throw_klass_external_name_exception(JavaThread* thread, const char* exception, Klass* klass))
417   ResourceMark rm(thread);
418   TempNewSymbol symbol = SymbolTable::new_symbol(exception, CHECK);
419   SharedRuntime::throw_and_post_jvmti_exception(thread, symbol, klass->external_name());
420 JRT_END
421 
422 JRT_ENTRY(void, JVMCIRuntime::throw_class_cast_exception(JavaThread* thread, const char* exception, Klass* caster_klass, Klass* target_klass))
423   ResourceMark rm(thread);
424   const char* message = SharedRuntime::generate_class_cast_message(caster_klass, target_klass);
425   TempNewSymbol symbol = SymbolTable::new_symbol(exception, CHECK);
426   SharedRuntime::throw_and_post_jvmti_exception(thread, symbol, message);
427 JRT_END
428 
429 JRT_LEAF(void, JVMCIRuntime::log_object(JavaThread* thread, oopDesc* obj, bool as_string, bool newline))
430   ttyLocker ttyl;
431 
432   if (obj == NULL) {
433     tty->print("NULL");
434   } else if (oopDesc::is_oop_or_null(obj, true) && (!as_string || !java_lang_String::is_instance(obj))) {
435     if (oopDesc::is_oop_or_null(obj, true)) {
436       char buf[O_BUFLEN];
437       tty->print("%s@" INTPTR_FORMAT, obj->klass()->name()->as_C_string(buf, O_BUFLEN), p2i(obj));
438     } else {
439       tty->print(INTPTR_FORMAT, p2i(obj));
440     }
441   } else {
442     ResourceMark rm;
443     assert(obj != NULL && java_lang_String::is_instance(obj), "must be");
444     char *buf = java_lang_String::as_utf8_string(obj);
445     tty->print_raw(buf);
446   }
447   if (newline) {
448     tty->cr();
449   }
450 JRT_END
451 
452 JRT_LEAF(void, JVMCIRuntime::write_barrier_pre(JavaThread* thread, oopDesc* obj))
453   thread->satb_mark_queue().enqueue(obj);
454 JRT_END
455 
456 JRT_LEAF(void, JVMCIRuntime::write_barrier_post(JavaThread* thread, void* card_addr))
457   thread->dirty_card_queue().enqueue(card_addr);
458 JRT_END
459 
460 JRT_LEAF(jboolean, JVMCIRuntime::validate_object(JavaThread* thread, oopDesc* parent, oopDesc* child))
461   bool ret = true;
462   if(!Universe::heap()->is_in_closed_subset(parent)) {
463     tty->print_cr("Parent Object " INTPTR_FORMAT " not in heap", p2i(parent));
464     parent->print();
465     ret=false;
466   }
467   if(!Universe::heap()->is_in_closed_subset(child)) {
468     tty->print_cr("Child Object " INTPTR_FORMAT " not in heap", p2i(child));
469     child->print();
470     ret=false;
471   }
472   return (jint)ret;
473 JRT_END
474 
475 JRT_ENTRY(void, JVMCIRuntime::vm_error(JavaThread* thread, jlong where, jlong format, jlong value))
476   ResourceMark rm;
477   const char *error_msg = where == 0L ? "<internal JVMCI error>" : (char*) (address) where;
478   char *detail_msg = NULL;
479   if (format != 0L) {
480     const char* buf = (char*) (address) format;
481     size_t detail_msg_length = strlen(buf) * 2;
482     detail_msg = (char *) NEW_RESOURCE_ARRAY(u_char, detail_msg_length);
483     jio_snprintf(detail_msg, detail_msg_length, buf, value);
484     report_vm_error(__FILE__, __LINE__, error_msg, "%s", detail_msg);
485   } else {
486     report_vm_error(__FILE__, __LINE__, error_msg);
487   }
488 JRT_END
489 
490 JRT_LEAF(oopDesc*, JVMCIRuntime::load_and_clear_exception(JavaThread* thread))
491   oop exception = thread->exception_oop();
492   assert(exception != NULL, "npe");
493   thread->set_exception_oop(NULL);
494   thread->set_exception_pc(0);
495   return exception;
496 JRT_END
497 
498 PRAGMA_DIAG_PUSH
499 PRAGMA_FORMAT_NONLITERAL_IGNORED
500 JRT_LEAF(void, JVMCIRuntime::log_printf(JavaThread* thread, oopDesc* format, jlong v1, jlong v2, jlong v3))
501   ResourceMark rm;
502   assert(format != NULL && java_lang_String::is_instance(format), "must be");
503   char *buf = java_lang_String::as_utf8_string(format);
504   tty->print((const char*)buf, v1, v2, v3);
505 JRT_END
506 PRAGMA_DIAG_POP
507 
508 static void decipher(jlong v, bool ignoreZero) {
509   if (v != 0 || !ignoreZero) {
510     void* p = (void *)(address) v;
511     CodeBlob* cb = CodeCache::find_blob(p);
512     if (cb) {
513       if (cb->is_nmethod()) {
514         char buf[O_BUFLEN];
515         tty->print("%s [" INTPTR_FORMAT "+" JLONG_FORMAT "]", cb->as_nmethod_or_null()->method()->name_and_sig_as_C_string(buf, O_BUFLEN), p2i(cb->code_begin()), (jlong)((address)v - cb->code_begin()));
516         return;
517       }
518       cb->print_value_on(tty);
519       return;
520     }
521     if (Universe::heap()->is_in(p)) {
522       oop obj = oop(p);
523       obj->print_value_on(tty);
524       return;
525     }
526     tty->print(INTPTR_FORMAT " [long: " JLONG_FORMAT ", double %lf, char %c]",p2i((void *)v), (jlong)v, (jdouble)v, (char)v);
527   }
528 }
529 
530 PRAGMA_DIAG_PUSH
531 PRAGMA_FORMAT_NONLITERAL_IGNORED
532 JRT_LEAF(void, JVMCIRuntime::vm_message(jboolean vmError, jlong format, jlong v1, jlong v2, jlong v3))
533   ResourceMark rm;
534   const char *buf = (const char*) (address) format;
535   if (vmError) {
536     if (buf != NULL) {
537       fatal(buf, v1, v2, v3);
538     } else {
539       fatal("<anonymous error>");
540     }
541   } else if (buf != NULL) {
542     tty->print(buf, v1, v2, v3);
543   } else {
544     assert(v2 == 0, "v2 != 0");
545     assert(v3 == 0, "v3 != 0");
546     decipher(v1, false);
547   }
548 JRT_END
549 PRAGMA_DIAG_POP
550 
551 JRT_LEAF(void, JVMCIRuntime::log_primitive(JavaThread* thread, jchar typeChar, jlong value, jboolean newline))
552   union {
553       jlong l;
554       jdouble d;
555       jfloat f;
556   } uu;
557   uu.l = value;
558   switch (typeChar) {
559     case 'Z': tty->print(value == 0 ? "false" : "true"); break;
560     case 'B': tty->print("%d", (jbyte) value); break;
561     case 'C': tty->print("%c", (jchar) value); break;
562     case 'S': tty->print("%d", (jshort) value); break;
563     case 'I': tty->print("%d", (jint) value); break;
564     case 'F': tty->print("%f", uu.f); break;
565     case 'J': tty->print(JLONG_FORMAT, value); break;
566     case 'D': tty->print("%lf", uu.d); break;
567     default: assert(false, "unknown typeChar"); break;
568   }
569   if (newline) {
570     tty->cr();
571   }
572 JRT_END
573 
574 JRT_ENTRY(jint, JVMCIRuntime::identity_hash_code(JavaThread* thread, oopDesc* obj))
575   return (jint) obj->identity_hash();
576 JRT_END
577 
578 JRT_ENTRY(jboolean, JVMCIRuntime::thread_is_interrupted(JavaThread* thread, oopDesc* receiver, jboolean clear_interrupted))
579   Handle receiverHandle(thread, receiver);
580   // A nested ThreadsListHandle may require the Threads_lock which
581   // requires thread_in_vm which is why this method cannot be JRT_LEAF.
582   ThreadsListHandle tlh;
583 
584   JavaThread* receiverThread = java_lang_Thread::thread(receiverHandle());
585   if (receiverThread == NULL || (EnableThreadSMRExtraValidityChecks && !tlh.includes(receiverThread))) {
586     // The other thread may exit during this process, which is ok so return false.
587     return JNI_FALSE;
588   } else {
589     return (jint) Thread::is_interrupted(receiverThread, clear_interrupted != 0);
590   }
591 JRT_END
592 
593 JRT_ENTRY(int, JVMCIRuntime::test_deoptimize_call_int(JavaThread* thread, int value))
594   deopt_caller();
595   return value;
596 JRT_END
597 
598 void JVMCIRuntime::force_initialization(TRAPS) {
599   JVMCIRuntime::initialize_well_known_classes(CHECK);
600 
601   ResourceMark rm;
602   TempNewSymbol getCompiler = SymbolTable::new_symbol("getCompiler", CHECK);
603   TempNewSymbol sig = SymbolTable::new_symbol("()Ljdk/vm/ci/runtime/JVMCICompiler;", CHECK);
604   Handle jvmciRuntime = JVMCIRuntime::get_HotSpotJVMCIRuntime(CHECK);
605   JavaValue result(T_OBJECT);
606   JavaCalls::call_virtual(&result, jvmciRuntime, HotSpotJVMCIRuntime::klass(), getCompiler, sig, CHECK);
607 }
608 
609 // private static JVMCIRuntime JVMCI.initializeRuntime()
610 JVM_ENTRY(jobject, JVM_GetJVMCIRuntime(JNIEnv *env, jclass c))
611   if (!EnableJVMCI) {
612     THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVMCI is not enabled")
613   }
614   JVMCIRuntime::initialize_HotSpotJVMCIRuntime(CHECK_NULL);
615   jobject ret = JVMCIRuntime::get_HotSpotJVMCIRuntime_jobject(CHECK_NULL);
616   return ret;
617 JVM_END
618 
619 Handle JVMCIRuntime::callStatic(const char* className, const char* methodName, const char* signature, JavaCallArguments* args, TRAPS) {
620   TempNewSymbol name = SymbolTable::new_symbol(className, CHECK_(Handle()));
621   Klass* klass = SystemDictionary::resolve_or_fail(name, true, CHECK_(Handle()));
622   TempNewSymbol runtime = SymbolTable::new_symbol(methodName, CHECK_(Handle()));
623   TempNewSymbol sig = SymbolTable::new_symbol(signature, CHECK_(Handle()));
624   JavaValue result(T_OBJECT);
625   if (args == NULL) {
626     JavaCalls::call_static(&result, klass, runtime, sig, CHECK_(Handle()));
627   } else {
628     JavaCalls::call_static(&result, klass, runtime, sig, args, CHECK_(Handle()));
629   }
630   return Handle(THREAD, (oop)result.get_jobject());
631 }
632 
633 void JVMCIRuntime::initialize_HotSpotJVMCIRuntime(TRAPS) {
634   guarantee(!_HotSpotJVMCIRuntime_initialized, "cannot reinitialize HotSpotJVMCIRuntime");
635   JVMCIRuntime::initialize_well_known_classes(CHECK);
636   // This should only be called in the context of the JVMCI class being initialized
637   InstanceKlass* klass = SystemDictionary::JVMCI_klass();
638   guarantee(klass->is_being_initialized() && klass->is_reentrant_initialization(THREAD),
639          "HotSpotJVMCIRuntime initialization should only be triggered through JVMCI initialization");
640 
641   Handle result = callStatic("jdk/vm/ci/hotspot/HotSpotJVMCIRuntime",
642                              "runtime",
643                              "()Ljdk/vm/ci/hotspot/HotSpotJVMCIRuntime;", NULL, CHECK);
644   objArrayOop trivial_prefixes = HotSpotJVMCIRuntime::trivialPrefixes(result);
645   if (trivial_prefixes != NULL) {
646     char** prefixes = NEW_C_HEAP_ARRAY(char*, trivial_prefixes->length(), mtCompiler);
647     for (int i = 0; i < trivial_prefixes->length(); i++) {
648       oop str = trivial_prefixes->obj_at(i);
649       if (str == NULL) {
650         THROW(vmSymbols::java_lang_NullPointerException());
651       } else {
652         prefixes[i] = strdup(java_lang_String::as_utf8_string(str));
653       }
654     }
655     _trivial_prefixes = prefixes;
656     _trivial_prefixes_count = trivial_prefixes->length();
657   }
658   int adjustment = HotSpotJVMCIRuntime::compilationLevelAdjustment(result);
659   assert(adjustment >= JVMCIRuntime::none &&
660          adjustment <= JVMCIRuntime::by_full_signature,
661          "compilation level adjustment out of bounds");
662   _comp_level_adjustment = (CompLevelAdjustment) adjustment;
663   _HotSpotJVMCIRuntime_initialized = true;
664   _HotSpotJVMCIRuntime_instance = JNIHandles::make_global(result);
665 }
666 
667 void JVMCIRuntime::initialize_JVMCI(TRAPS) {
668   if (JNIHandles::resolve(_HotSpotJVMCIRuntime_instance) == NULL) {
669     callStatic("jdk/vm/ci/runtime/JVMCI",
670                "getRuntime",
671                "()Ljdk/vm/ci/runtime/JVMCIRuntime;", NULL, CHECK);
672   }
673   assert(_HotSpotJVMCIRuntime_initialized == true, "what?");
674 }
675 
676 bool JVMCIRuntime::can_initialize_JVMCI() {
677   // Initializing JVMCI requires the module system to be initialized past phase 3.
678   // The JVMCI API itself isn't available until phase 2 and ServiceLoader (which
679   // JVMCI initialization requires) isn't usable until after phase 3. Testing
680   // whether the system loader is initialized satisfies all these invariants.
681   if (SystemDictionary::java_system_loader() == NULL) {
682     return false;
683   }
684   assert(Universe::is_module_initialized(), "must be");
685   return true;
686 }
687 
688 void JVMCIRuntime::initialize_well_known_classes(TRAPS) {
689   if (JVMCIRuntime::_well_known_classes_initialized == false) {
690     guarantee(can_initialize_JVMCI(), "VM is not yet sufficiently booted to initialize JVMCI");
691     SystemDictionary::WKID scan = SystemDictionary::FIRST_JVMCI_WKID;
692     SystemDictionary::initialize_wk_klasses_through(SystemDictionary::LAST_JVMCI_WKID, scan, CHECK);
693     JVMCIJavaClasses::compute_offsets(CHECK);
694     JVMCIRuntime::_well_known_classes_initialized = true;
695   }
696 }
697 
698 void JVMCIRuntime::metadata_do(void f(Metadata*)) {
699   // For simplicity, the existence of HotSpotJVMCIMetaAccessContext in
700   // the SystemDictionary well known classes should ensure the other
701   // classes have already been loaded, so make sure their order in the
702   // table enforces that.
703   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotResolvedJavaMethodImpl) <
704          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
705   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotConstantPool) <
706          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
707   assert(SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotResolvedObjectTypeImpl) <
708          SystemDictionary::WK_KLASS_ENUM_NAME(jdk_vm_ci_hotspot_HotSpotJVMCIMetaAccessContext), "must be loaded earlier");
709 
710   if (HotSpotJVMCIMetaAccessContext::klass() == NULL ||
711       !HotSpotJVMCIMetaAccessContext::klass()->is_linked()) {
712     // Nothing could be registered yet
713     return;
714   }
715 
716   // WeakReference<HotSpotJVMCIMetaAccessContext>[]
717   objArrayOop allContexts = HotSpotJVMCIMetaAccessContext::allContexts();
718   if (allContexts == NULL) {
719     return;
720   }
721 
722   // These must be loaded at this point but the linking state doesn't matter.
723   assert(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass() != NULL, "must be loaded");
724   assert(SystemDictionary::HotSpotConstantPool_klass() != NULL, "must be loaded");
725   assert(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass() != NULL, "must be loaded");
726 
727   for (int i = 0; i < allContexts->length(); i++) {
728     oop ref = allContexts->obj_at(i);
729     if (ref != NULL) {
730       oop referent = java_lang_ref_Reference::referent(ref);
731       if (referent != NULL) {
732         // Chunked Object[] with last element pointing to next chunk
733         objArrayOop metadataRoots = HotSpotJVMCIMetaAccessContext::metadataRoots(referent);
734         while (metadataRoots != NULL) {
735           for (int typeIndex = 0; typeIndex < metadataRoots->length() - 1; typeIndex++) {
736             oop reference = metadataRoots->obj_at(typeIndex);
737             if (reference == NULL) {
738               continue;
739             }
740             oop metadataRoot = java_lang_ref_Reference::referent(reference);
741             if (metadataRoot == NULL) {
742               continue;
743             }
744             if (metadataRoot->is_a(SystemDictionary::HotSpotResolvedJavaMethodImpl_klass())) {
745               Method* method = CompilerToVM::asMethod(metadataRoot);
746               f(method);
747             } else if (metadataRoot->is_a(SystemDictionary::HotSpotConstantPool_klass())) {
748               ConstantPool* constantPool = CompilerToVM::asConstantPool(metadataRoot);
749               f(constantPool);
750             } else if (metadataRoot->is_a(SystemDictionary::HotSpotResolvedObjectTypeImpl_klass())) {
751               Klass* klass = CompilerToVM::asKlass(metadataRoot);
752               f(klass);
753             } else {
754               metadataRoot->print();
755               ShouldNotReachHere();
756             }
757           }
758           metadataRoots = (objArrayOop)metadataRoots->obj_at(metadataRoots->length() - 1);
759           assert(metadataRoots == NULL || metadataRoots->is_objArray(), "wrong type");
760         }
761       }
762     }
763   }
764 }
765 
766 // private static void CompilerToVM.registerNatives()
767 JVM_ENTRY(void, JVM_RegisterJVMCINatives(JNIEnv *env, jclass c2vmClass))
768   if (!EnableJVMCI) {
769     THROW_MSG(vmSymbols::java_lang_InternalError(), "JVMCI is not enabled");
770   }
771 
772 #ifdef _LP64
773 #ifndef SPARC
774   uintptr_t heap_end = (uintptr_t) Universe::heap()->reserved_region().end();
775   uintptr_t allocation_end = heap_end + ((uintptr_t)16) * 1024 * 1024 * 1024;
776   guarantee(heap_end < allocation_end, "heap end too close to end of address space (might lead to erroneous TLAB allocations)");
777 #endif // !SPARC
778 #else
779   fatal("check TLAB allocation code for address space conflicts");
780 #endif // _LP64
781 
782   JVMCIRuntime::initialize_well_known_classes(CHECK);
783 
784   {
785     ThreadToNativeFromVM trans(thread);
786     env->RegisterNatives(c2vmClass, CompilerToVM::methods, CompilerToVM::methods_count());
787   }
788 JVM_END
789 
790 void JVMCIRuntime::shutdown(TRAPS) {
791   if (_HotSpotJVMCIRuntime_instance != NULL) {
792     _shutdown_called = true;
793     HandleMark hm(THREAD);
794     Handle receiver = get_HotSpotJVMCIRuntime(CHECK);
795     JavaValue result(T_VOID);
796     JavaCallArguments args;
797     args.push_oop(receiver);
798     JavaCalls::call_special(&result, receiver->klass(), vmSymbols::shutdown_method_name(), vmSymbols::void_method_signature(), &args, CHECK);
799   }
800 }
801 
802 CompLevel JVMCIRuntime::adjust_comp_level_inner(const methodHandle& method, bool is_osr, CompLevel level, JavaThread* thread) {
803   JVMCICompiler* compiler = JVMCICompiler::instance(false, thread);
804   if (compiler != NULL && compiler->is_bootstrapping()) {
805     return level;
806   }
807   if (!is_HotSpotJVMCIRuntime_initialized() || _comp_level_adjustment == JVMCIRuntime::none) {
808     // JVMCI cannot participate in compilation scheduling until
809     // JVMCI is initialized and indicates it wants to participate.
810     return level;
811   }
812 
813 #define CHECK_RETURN THREAD); \
814   if (HAS_PENDING_EXCEPTION) { \
815     Handle exception(THREAD, PENDING_EXCEPTION); \
816     CLEAR_PENDING_EXCEPTION; \
817   \
818     if (exception->is_a(SystemDictionary::ThreadDeath_klass())) { \
819       /* In the special case of ThreadDeath, we need to reset the */ \
820       /* pending async exception so that it is propagated.        */ \
821       thread->set_pending_async_exception(exception()); \
822       return level; \
823     } \
824     tty->print("Uncaught exception while adjusting compilation level: "); \
825     java_lang_Throwable::print(exception(), tty); \
826     tty->cr(); \
827     java_lang_Throwable::print_stack_trace(exception, tty); \
828     if (HAS_PENDING_EXCEPTION) { \
829       CLEAR_PENDING_EXCEPTION; \
830     } \
831     return level; \
832   } \
833   (void)(0
834 
835 
836   Thread* THREAD = thread;
837   HandleMark hm;
838   Handle receiver = JVMCIRuntime::get_HotSpotJVMCIRuntime(CHECK_RETURN);
839   Handle name;
840   Handle sig;
841   if (_comp_level_adjustment == JVMCIRuntime::by_full_signature) {
842     name = java_lang_String::create_from_symbol(method->name(), CHECK_RETURN);
843     sig = java_lang_String::create_from_symbol(method->signature(), CHECK_RETURN);
844   } else {
845     name = Handle();
846     sig = Handle();
847   }
848 
849   JavaValue result(T_INT);
850   JavaCallArguments args;
851   args.push_oop(receiver);
852   args.push_oop(Handle(THREAD, method->method_holder()->java_mirror()));
853   args.push_oop(name);
854   args.push_oop(sig);
855   args.push_int(is_osr);
856   args.push_int(level);
857   JavaCalls::call_special(&result, receiver->klass(), vmSymbols::adjustCompilationLevel_name(),
858                           vmSymbols::adjustCompilationLevel_signature(), &args, CHECK_RETURN);
859 
860   int comp_level = result.get_jint();
861   if (comp_level < CompLevel_none || comp_level > CompLevel_full_optimization) {
862     assert(false, "compilation level out of bounds");
863     return level;
864   }
865   return (CompLevel) comp_level;
866 #undef CHECK_RETURN
867 }
868 
869 void JVMCIRuntime::bootstrap_finished(TRAPS) {
870   HandleMark hm(THREAD);
871   Handle receiver = get_HotSpotJVMCIRuntime(CHECK);
872   JavaValue result(T_VOID);
873   JavaCallArguments args;
874   args.push_oop(receiver);
875   JavaCalls::call_special(&result, receiver->klass(), vmSymbols::bootstrapFinished_method_name(), vmSymbols::void_method_signature(), &args, CHECK);
876 }
877 
878 bool JVMCIRuntime::treat_as_trivial(Method* method) {
879   if (_HotSpotJVMCIRuntime_initialized) {
880     for (int i = 0; i < _trivial_prefixes_count; i++) {
881       if (method->method_holder()->name()->starts_with(_trivial_prefixes[i])) {
882         return true;
883       }
884     }
885   }
886   return false;
887 }