1 /*
   2  * Copyright (c) 1997, 2010, 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 "incls/_precompiled.incl"
  26 #include "incls/_interpreterRuntime.cpp.incl"
  27 
  28 class UnlockFlagSaver {
  29   private:
  30     JavaThread* _thread;
  31     bool _do_not_unlock;
  32   public:
  33     UnlockFlagSaver(JavaThread* t) {
  34       _thread = t;
  35       _do_not_unlock = t->do_not_unlock_if_synchronized();
  36       t->set_do_not_unlock_if_synchronized(false);
  37     }
  38     ~UnlockFlagSaver() {
  39       _thread->set_do_not_unlock_if_synchronized(_do_not_unlock);
  40     }
  41 };
  42 
  43 //------------------------------------------------------------------------------------------------------------------------
  44 // State accessors
  45 
  46 void InterpreterRuntime::set_bcp_and_mdp(address bcp, JavaThread *thread) {
  47   last_frame(thread).interpreter_frame_set_bcp(bcp);
  48   if (ProfileInterpreter) {
  49     // ProfileTraps uses MDOs independently of ProfileInterpreter.
  50     // That is why we must check both ProfileInterpreter and mdo != NULL.
  51     methodDataOop mdo = last_frame(thread).interpreter_frame_method()->method_data();
  52     if (mdo != NULL) {
  53       NEEDS_CLEANUP;
  54       last_frame(thread).interpreter_frame_set_mdp(mdo->bci_to_dp(last_frame(thread).interpreter_frame_bci()));
  55     }
  56   }
  57 }
  58 
  59 //------------------------------------------------------------------------------------------------------------------------
  60 // Constants
  61 
  62 
  63 IRT_ENTRY(void, InterpreterRuntime::ldc(JavaThread* thread, bool wide))
  64   // access constant pool
  65   constantPoolOop pool = method(thread)->constants();
  66   int index = wide ? get_index_u2(thread, Bytecodes::_ldc_w) : get_index_u1(thread, Bytecodes::_ldc);
  67   constantTag tag = pool->tag_at(index);
  68 
  69   if (tag.is_unresolved_klass() || tag.is_klass()) {
  70     klassOop klass = pool->klass_at(index, CHECK);
  71     oop java_class = klass->klass_part()->java_mirror();
  72     thread->set_vm_result(java_class);
  73   } else {
  74 #ifdef ASSERT
  75     // If we entered this runtime routine, we believed the tag contained
  76     // an unresolved string, an unresolved class or a resolved class.
  77     // However, another thread could have resolved the unresolved string
  78     // or class by the time we go there.
  79     assert(tag.is_unresolved_string()|| tag.is_string(), "expected string");
  80 #endif
  81     oop s_oop = pool->string_at(index, CHECK);
  82     thread->set_vm_result(s_oop);
  83   }
  84 IRT_END
  85 
  86 IRT_ENTRY(void, InterpreterRuntime::resolve_ldc(JavaThread* thread, Bytecodes::Code bytecode)) {
  87   assert(bytecode == Bytecodes::_fast_aldc ||
  88          bytecode == Bytecodes::_fast_aldc_w, "wrong bc");
  89   ResourceMark rm(thread);
  90   methodHandle m (thread, method(thread));
  91   Bytecode_loadconstant* ldc = Bytecode_loadconstant_at(m, bci(thread));
  92   oop result = ldc->resolve_constant(THREAD);
  93   DEBUG_ONLY(ConstantPoolCacheEntry* cpce = m->constants()->cache()->entry_at(ldc->cache_index()));
  94   assert(result == cpce->f1(), "expected result for assembly code");
  95 }
  96 IRT_END
  97 
  98 
  99 //------------------------------------------------------------------------------------------------------------------------
 100 // Allocation
 101 
 102 IRT_ENTRY(void, InterpreterRuntime::_new(JavaThread* thread, constantPoolOopDesc* pool, int index))
 103   klassOop k_oop = pool->klass_at(index, CHECK);
 104   instanceKlassHandle klass (THREAD, k_oop);
 105 
 106   // Make sure we are not instantiating an abstract klass
 107   klass->check_valid_for_instantiation(true, CHECK);
 108 
 109   // Make sure klass is initialized
 110   klass->initialize(CHECK);
 111 
 112   // At this point the class may not be fully initialized
 113   // because of recursive initialization. If it is fully
 114   // initialized & has_finalized is not set, we rewrite
 115   // it into its fast version (Note: no locking is needed
 116   // here since this is an atomic byte write and can be
 117   // done more than once).
 118   //
 119   // Note: In case of classes with has_finalized we don't
 120   //       rewrite since that saves us an extra check in
 121   //       the fast version which then would call the
 122   //       slow version anyway (and do a call back into
 123   //       Java).
 124   //       If we have a breakpoint, then we don't rewrite
 125   //       because the _breakpoint bytecode would be lost.
 126   oop obj = klass->allocate_instance(CHECK);
 127   thread->set_vm_result(obj);
 128 IRT_END
 129 
 130 
 131 IRT_ENTRY(void, InterpreterRuntime::newarray(JavaThread* thread, BasicType type, jint size))
 132   oop obj = oopFactory::new_typeArray(type, size, CHECK);
 133   thread->set_vm_result(obj);
 134 IRT_END
 135 
 136 
 137 IRT_ENTRY(void, InterpreterRuntime::anewarray(JavaThread* thread, constantPoolOopDesc* pool, int index, jint size))
 138   // Note: no oopHandle for pool & klass needed since they are not used
 139   //       anymore after new_objArray() and no GC can happen before.
 140   //       (This may have to change if this code changes!)
 141   klassOop  klass = pool->klass_at(index, CHECK);
 142   objArrayOop obj = oopFactory::new_objArray(klass, size, CHECK);
 143   thread->set_vm_result(obj);
 144 IRT_END
 145 
 146 
 147 IRT_ENTRY(void, InterpreterRuntime::multianewarray(JavaThread* thread, jint* first_size_address))
 148   // We may want to pass in more arguments - could make this slightly faster
 149   constantPoolOop constants = method(thread)->constants();
 150   int          i = get_index_u2(thread, Bytecodes::_multianewarray);
 151   klassOop klass = constants->klass_at(i, CHECK);
 152   int   nof_dims = number_of_dimensions(thread);
 153   assert(oop(klass)->is_klass(), "not a class");
 154   assert(nof_dims >= 1, "multianewarray rank must be nonzero");
 155 
 156   // We must create an array of jints to pass to multi_allocate.
 157   ResourceMark rm(thread);
 158   const int small_dims = 10;
 159   jint dim_array[small_dims];
 160   jint *dims = &dim_array[0];
 161   if (nof_dims > small_dims) {
 162     dims = (jint*) NEW_RESOURCE_ARRAY(jint, nof_dims);
 163   }
 164   for (int index = 0; index < nof_dims; index++) {
 165     // offset from first_size_address is addressed as local[index]
 166     int n = Interpreter::local_offset_in_bytes(index)/jintSize;
 167     dims[index] = first_size_address[n];
 168   }
 169   oop obj = arrayKlass::cast(klass)->multi_allocate(nof_dims, dims, CHECK);
 170   thread->set_vm_result(obj);
 171 IRT_END
 172 
 173 
 174 IRT_ENTRY(void, InterpreterRuntime::register_finalizer(JavaThread* thread, oopDesc* obj))
 175   assert(obj->is_oop(), "must be a valid oop");
 176   assert(obj->klass()->klass_part()->has_finalizer(), "shouldn't be here otherwise");
 177   instanceKlass::register_finalizer(instanceOop(obj), CHECK);
 178 IRT_END
 179 
 180 
 181 // Quicken instance-of and check-cast bytecodes
 182 IRT_ENTRY(void, InterpreterRuntime::quicken_io_cc(JavaThread* thread))
 183   // Force resolving; quicken the bytecode
 184   int which = get_index_u2(thread, Bytecodes::_checkcast);
 185   constantPoolOop cpool = method(thread)->constants();
 186   // We'd expect to assert that we're only here to quicken bytecodes, but in a multithreaded
 187   // program we might have seen an unquick'd bytecode in the interpreter but have another
 188   // thread quicken the bytecode before we get here.
 189   // assert( cpool->tag_at(which).is_unresolved_klass(), "should only come here to quicken bytecodes" );
 190   klassOop klass = cpool->klass_at(which, CHECK);
 191   thread->set_vm_result(klass);
 192 IRT_END
 193 
 194 
 195 //------------------------------------------------------------------------------------------------------------------------
 196 // Exceptions
 197 
 198 // Assume the compiler is (or will be) interested in this event.
 199 // If necessary, create an MDO to hold the information, and record it.
 200 void InterpreterRuntime::note_trap(JavaThread* thread, int reason, TRAPS) {
 201   assert(ProfileTraps, "call me only if profiling");
 202   methodHandle trap_method(thread, method(thread));
 203 
 204   if (trap_method.not_null()) {
 205     methodDataHandle trap_mdo(thread, trap_method->method_data());
 206     if (trap_mdo.is_null()) {
 207       methodOopDesc::build_interpreter_method_data(trap_method, THREAD);
 208       if (HAS_PENDING_EXCEPTION) {
 209         assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
 210         CLEAR_PENDING_EXCEPTION;
 211       }
 212       trap_mdo = methodDataHandle(thread, trap_method->method_data());
 213       // and fall through...
 214     }
 215     if (trap_mdo.not_null()) {
 216       // Update per-method count of trap events.  The interpreter
 217       // is updating the MDO to simulate the effect of compiler traps.
 218       int trap_bci = trap_method->bci_from(bcp(thread));
 219       Deoptimization::update_method_data_from_interpreter(trap_mdo, trap_bci, reason);
 220     }
 221   }
 222 }
 223 
 224 static Handle get_preinitialized_exception(klassOop k, TRAPS) {
 225   // get klass
 226   instanceKlass* klass = instanceKlass::cast(k);
 227   assert(klass->is_initialized(),
 228          "this klass should have been initialized during VM initialization");
 229   // create instance - do not call constructor since we may have no
 230   // (java) stack space left (should assert constructor is empty)
 231   Handle exception;
 232   oop exception_oop = klass->allocate_instance(CHECK_(exception));
 233   exception = Handle(THREAD, exception_oop);
 234   if (StackTraceInThrowable) {
 235     java_lang_Throwable::fill_in_stack_trace(exception);
 236   }
 237   return exception;
 238 }
 239 
 240 // Special handling for stack overflow: since we don't have any (java) stack
 241 // space left we use the pre-allocated & pre-initialized StackOverflowError
 242 // klass to create an stack overflow error instance.  We do not call its
 243 // constructor for the same reason (it is empty, anyway).
 244 IRT_ENTRY(void, InterpreterRuntime::throw_StackOverflowError(JavaThread* thread))
 245   Handle exception = get_preinitialized_exception(
 246                                  SystemDictionary::StackOverflowError_klass(),
 247                                  CHECK);
 248   THROW_HANDLE(exception);
 249 IRT_END
 250 
 251 
 252 IRT_ENTRY(void, InterpreterRuntime::create_exception(JavaThread* thread, char* name, char* message))
 253   // lookup exception klass
 254   symbolHandle s = oopFactory::new_symbol_handle(name, CHECK);
 255   if (ProfileTraps) {
 256     if (s == vmSymbols::java_lang_ArithmeticException()) {
 257       note_trap(thread, Deoptimization::Reason_div0_check, CHECK);
 258     } else if (s == vmSymbols::java_lang_NullPointerException()) {
 259       note_trap(thread, Deoptimization::Reason_null_check, CHECK);
 260     }
 261   }
 262   // create exception
 263   Handle exception = Exceptions::new_exception(thread, s(), message);
 264   thread->set_vm_result(exception());
 265 IRT_END
 266 
 267 
 268 IRT_ENTRY(void, InterpreterRuntime::create_klass_exception(JavaThread* thread, char* name, oopDesc* obj))
 269   ResourceMark rm(thread);
 270   const char* klass_name = Klass::cast(obj->klass())->external_name();
 271   // lookup exception klass
 272   symbolHandle s = oopFactory::new_symbol_handle(name, CHECK);
 273   if (ProfileTraps) {
 274     note_trap(thread, Deoptimization::Reason_class_check, CHECK);
 275   }
 276   // create exception, with klass name as detail message
 277   Handle exception = Exceptions::new_exception(thread, s(), klass_name);
 278   thread->set_vm_result(exception());
 279 IRT_END
 280 
 281 
 282 IRT_ENTRY(void, InterpreterRuntime::throw_ArrayIndexOutOfBoundsException(JavaThread* thread, char* name, jint index))
 283   char message[jintAsStringSize];
 284   // lookup exception klass
 285   symbolHandle s = oopFactory::new_symbol_handle(name, CHECK);
 286   if (ProfileTraps) {
 287     note_trap(thread, Deoptimization::Reason_range_check, CHECK);
 288   }
 289   // create exception
 290   sprintf(message, "%d", index);
 291   THROW_MSG(s(), message);
 292 IRT_END
 293 
 294 IRT_ENTRY(void, InterpreterRuntime::throw_ClassCastException(
 295   JavaThread* thread, oopDesc* obj))
 296 
 297   ResourceMark rm(thread);
 298   char* message = SharedRuntime::generate_class_cast_message(
 299     thread, Klass::cast(obj->klass())->external_name());
 300 
 301   if (ProfileTraps) {
 302     note_trap(thread, Deoptimization::Reason_class_check, CHECK);
 303   }
 304 
 305   // create exception
 306   THROW_MSG(vmSymbols::java_lang_ClassCastException(), message);
 307 IRT_END
 308 
 309 // required can be either a MethodType, or a Class (for a single argument)
 310 // actual (if not null) can be either a MethodHandle, or an arbitrary value (for a single argument)
 311 IRT_ENTRY(void, InterpreterRuntime::throw_WrongMethodTypeException(JavaThread* thread,
 312                                                                    oopDesc* required,
 313                                                                    oopDesc* actual)) {
 314   ResourceMark rm(thread);
 315   char* message = SharedRuntime::generate_wrong_method_type_message(thread, required, actual);
 316 
 317   if (ProfileTraps) {
 318     note_trap(thread, Deoptimization::Reason_constraint, CHECK);
 319   }
 320 
 321   // create exception
 322   THROW_MSG(vmSymbols::java_dyn_WrongMethodTypeException(), message);
 323 }
 324 IRT_END
 325 
 326 
 327 
 328 // exception_handler_for_exception(...) returns the continuation address,
 329 // the exception oop (via TLS) and sets the bci/bcp for the continuation.
 330 // The exception oop is returned to make sure it is preserved over GC (it
 331 // is only on the stack if the exception was thrown explicitly via athrow).
 332 // During this operation, the expression stack contains the values for the
 333 // bci where the exception happened. If the exception was propagated back
 334 // from a call, the expression stack contains the values for the bci at the
 335 // invoke w/o arguments (i.e., as if one were inside the call).
 336 IRT_ENTRY(address, InterpreterRuntime::exception_handler_for_exception(JavaThread* thread, oopDesc* exception))
 337 
 338   Handle             h_exception(thread, exception);
 339   methodHandle       h_method   (thread, method(thread));
 340   constantPoolHandle h_constants(thread, h_method->constants());
 341   typeArrayHandle    h_extable  (thread, h_method->exception_table());
 342   bool               should_repeat;
 343   int                handler_bci;
 344   int                current_bci = bci(thread);
 345 
 346   // Need to do this check first since when _do_not_unlock_if_synchronized
 347   // is set, we don't want to trigger any classloading which may make calls
 348   // into java, or surprisingly find a matching exception handler for bci 0
 349   // since at this moment the method hasn't been "officially" entered yet.
 350   if (thread->do_not_unlock_if_synchronized()) {
 351     ResourceMark rm;
 352     assert(current_bci == 0,  "bci isn't zero for do_not_unlock_if_synchronized");
 353     thread->set_vm_result(exception);
 354 #ifdef CC_INTERP
 355     return (address) -1;
 356 #else
 357     return Interpreter::remove_activation_entry();
 358 #endif
 359   }
 360 
 361   do {
 362     should_repeat = false;
 363 
 364     // assertions
 365 #ifdef ASSERT
 366     assert(h_exception.not_null(), "NULL exceptions should be handled by athrow");
 367     assert(h_exception->is_oop(), "just checking");
 368     // Check that exception is a subclass of Throwable, otherwise we have a VerifyError
 369     if (!(h_exception->is_a(SystemDictionary::Throwable_klass()))) {
 370       if (ExitVMOnVerifyError) vm_exit(-1);
 371       ShouldNotReachHere();
 372     }
 373 #endif
 374 
 375     // tracing
 376     if (TraceExceptions) {
 377       ttyLocker ttyl;
 378       ResourceMark rm(thread);
 379       tty->print_cr("Exception <%s> (" INTPTR_FORMAT ")", h_exception->print_value_string(), (address)h_exception());
 380       tty->print_cr(" thrown in interpreter method <%s>", h_method->print_value_string());
 381       tty->print_cr(" at bci %d for thread " INTPTR_FORMAT, current_bci, thread);
 382     }
 383 // Don't go paging in something which won't be used.
 384 //     else if (h_extable->length() == 0) {
 385 //       // disabled for now - interpreter is not using shortcut yet
 386 //       // (shortcut is not to call runtime if we have no exception handlers)
 387 //       // warning("performance bug: should not call runtime if method has no exception handlers");
 388 //     }
 389     // for AbortVMOnException flag
 390     NOT_PRODUCT(Exceptions::debug_check_abort(h_exception));
 391 
 392     // exception handler lookup
 393     KlassHandle h_klass(THREAD, h_exception->klass());
 394     handler_bci = h_method->fast_exception_handler_bci_for(h_klass, current_bci, THREAD);
 395     if (HAS_PENDING_EXCEPTION) {
 396       // We threw an exception while trying to find the exception handler.
 397       // Transfer the new exception to the exception handle which will
 398       // be set into thread local storage, and do another lookup for an
 399       // exception handler for this exception, this time starting at the
 400       // BCI of the exception handler which caused the exception to be
 401       // thrown (bug 4307310).
 402       h_exception = Handle(THREAD, PENDING_EXCEPTION);
 403       CLEAR_PENDING_EXCEPTION;
 404       if (handler_bci >= 0) {
 405         current_bci = handler_bci;
 406         should_repeat = true;
 407       }
 408     }
 409   } while (should_repeat == true);
 410 
 411   // notify JVMTI of an exception throw; JVMTI will detect if this is a first
 412   // time throw or a stack unwinding throw and accordingly notify the debugger
 413   if (JvmtiExport::can_post_on_exceptions()) {
 414     JvmtiExport::post_exception_throw(thread, h_method(), bcp(thread), h_exception());
 415   }
 416 
 417 #ifdef CC_INTERP
 418   address continuation = (address)(intptr_t) handler_bci;
 419 #else
 420   address continuation = NULL;
 421 #endif
 422   address handler_pc = NULL;
 423   if (handler_bci < 0 || !thread->reguard_stack((address) &continuation)) {
 424     // Forward exception to callee (leaving bci/bcp untouched) because (a) no
 425     // handler in this method, or (b) after a stack overflow there is not yet
 426     // enough stack space available to reprotect the stack.
 427 #ifndef CC_INTERP
 428     continuation = Interpreter::remove_activation_entry();
 429 #endif
 430     // Count this for compilation purposes
 431     h_method->interpreter_throwout_increment();
 432   } else {
 433     // handler in this method => change bci/bcp to handler bci/bcp and continue there
 434     handler_pc = h_method->code_base() + handler_bci;
 435 #ifndef CC_INTERP
 436     set_bcp_and_mdp(handler_pc, thread);
 437     continuation = Interpreter::dispatch_table(vtos)[*handler_pc];
 438 #endif
 439   }
 440   // notify debugger of an exception catch
 441   // (this is good for exceptions caught in native methods as well)
 442   if (JvmtiExport::can_post_on_exceptions()) {
 443     JvmtiExport::notice_unwind_due_to_exception(thread, h_method(), handler_pc, h_exception(), (handler_pc != NULL));
 444   }
 445 
 446   thread->set_vm_result(h_exception());
 447   return continuation;
 448 IRT_END
 449 
 450 
 451 IRT_ENTRY(void, InterpreterRuntime::throw_pending_exception(JavaThread* thread))
 452   assert(thread->has_pending_exception(), "must only ne called if there's an exception pending");
 453   // nothing to do - eventually we should remove this code entirely (see comments @ call sites)
 454 IRT_END
 455 
 456 
 457 IRT_ENTRY(void, InterpreterRuntime::throw_AbstractMethodError(JavaThread* thread))
 458   THROW(vmSymbols::java_lang_AbstractMethodError());
 459 IRT_END
 460 
 461 
 462 IRT_ENTRY(void, InterpreterRuntime::throw_IncompatibleClassChangeError(JavaThread* thread))
 463   THROW(vmSymbols::java_lang_IncompatibleClassChangeError());
 464 IRT_END
 465 
 466 
 467 //------------------------------------------------------------------------------------------------------------------------
 468 // Fields
 469 //
 470 
 471 IRT_ENTRY(void, InterpreterRuntime::resolve_get_put(JavaThread* thread, Bytecodes::Code bytecode))
 472   // resolve field
 473   FieldAccessInfo info;
 474   constantPoolHandle pool(thread, method(thread)->constants());
 475   bool is_static = (bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic);
 476 
 477   {
 478     JvmtiHideSingleStepping jhss(thread);
 479     LinkResolver::resolve_field(info, pool, get_index_u2_cpcache(thread, bytecode),
 480                                 bytecode, false, CHECK);
 481   } // end JvmtiHideSingleStepping
 482 
 483   // check if link resolution caused cpCache to be updated
 484   if (already_resolved(thread)) return;
 485 
 486   // compute auxiliary field attributes
 487   TosState state  = as_TosState(info.field_type());
 488 
 489   // We need to delay resolving put instructions on final fields
 490   // until we actually invoke one. This is required so we throw
 491   // exceptions at the correct place. If we do not resolve completely
 492   // in the current pass, leaving the put_code set to zero will
 493   // cause the next put instruction to reresolve.
 494   bool is_put = (bytecode == Bytecodes::_putfield ||
 495                  bytecode == Bytecodes::_putstatic);
 496   Bytecodes::Code put_code = (Bytecodes::Code)0;
 497 
 498   // We also need to delay resolving getstatic instructions until the
 499   // class is intitialized.  This is required so that access to the static
 500   // field will call the initialization function every time until the class
 501   // is completely initialized ala. in 2.17.5 in JVM Specification.
 502   instanceKlass *klass = instanceKlass::cast(info.klass()->as_klassOop());
 503   bool uninitialized_static = ((bytecode == Bytecodes::_getstatic || bytecode == Bytecodes::_putstatic) &&
 504                                !klass->is_initialized());
 505   Bytecodes::Code get_code = (Bytecodes::Code)0;
 506 
 507 
 508   if (!uninitialized_static) {
 509     get_code = ((is_static) ? Bytecodes::_getstatic : Bytecodes::_getfield);
 510     if (is_put || !info.access_flags().is_final()) {
 511       put_code = ((is_static) ? Bytecodes::_putstatic : Bytecodes::_putfield);
 512     }
 513   }
 514 
 515   cache_entry(thread)->set_field(
 516     get_code,
 517     put_code,
 518     info.klass(),
 519     info.field_index(),
 520     info.field_offset(),
 521     state,
 522     info.access_flags().is_final(),
 523     info.access_flags().is_volatile()
 524   );
 525 IRT_END
 526 
 527 
 528 //------------------------------------------------------------------------------------------------------------------------
 529 // Synchronization
 530 //
 531 // The interpreter's synchronization code is factored out so that it can
 532 // be shared by method invocation and synchronized blocks.
 533 //%note synchronization_3
 534 
 535 static void trace_locking(Handle& h_locking_obj, bool is_locking) {
 536   ObjectSynchronizer::trace_locking(h_locking_obj, false, true, is_locking);
 537 }
 538 
 539 
 540 //%note monitor_1
 541 IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
 542 #ifdef ASSERT
 543   thread->last_frame().interpreter_frame_verify_monitor(elem);
 544 #endif
 545   if (PrintBiasedLockingStatistics) {
 546     Atomic::inc(BiasedLocking::slow_path_entry_count_addr());
 547   }
 548   Handle h_obj(thread, elem->obj());
 549   assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
 550          "must be NULL or an object");
 551   if (UseBiasedLocking) {
 552     // Retry fast entry if bias is revoked to avoid unnecessary inflation
 553     ObjectSynchronizer::fast_enter(h_obj, elem->lock(), true, CHECK);
 554   } else {
 555     ObjectSynchronizer::slow_enter(h_obj, elem->lock(), CHECK);
 556   }
 557   assert(Universe::heap()->is_in_reserved_or_null(elem->obj()),
 558          "must be NULL or an object");
 559 #ifdef ASSERT
 560   thread->last_frame().interpreter_frame_verify_monitor(elem);
 561 #endif
 562 IRT_END
 563 
 564 
 565 //%note monitor_1
 566 IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorexit(JavaThread* thread, BasicObjectLock* elem))
 567 #ifdef ASSERT
 568   thread->last_frame().interpreter_frame_verify_monitor(elem);
 569 #endif
 570   Handle h_obj(thread, elem->obj());
 571   assert(Universe::heap()->is_in_reserved_or_null(h_obj()),
 572          "must be NULL or an object");
 573   if (elem == NULL || h_obj()->is_unlocked()) {
 574     THROW(vmSymbols::java_lang_IllegalMonitorStateException());
 575   }
 576   ObjectSynchronizer::slow_exit(h_obj(), elem->lock(), thread);
 577   // Free entry. This must be done here, since a pending exception might be installed on
 578   // exit. If it is not cleared, the exception handling code will try to unlock the monitor again.
 579   elem->set_obj(NULL);
 580 #ifdef ASSERT
 581   thread->last_frame().interpreter_frame_verify_monitor(elem);
 582 #endif
 583 IRT_END
 584 
 585 
 586 IRT_ENTRY(void, InterpreterRuntime::throw_illegal_monitor_state_exception(JavaThread* thread))
 587   THROW(vmSymbols::java_lang_IllegalMonitorStateException());
 588 IRT_END
 589 
 590 
 591 IRT_ENTRY(void, InterpreterRuntime::new_illegal_monitor_state_exception(JavaThread* thread))
 592   // Returns an illegal exception to install into the current thread. The
 593   // pending_exception flag is cleared so normal exception handling does not
 594   // trigger. Any current installed exception will be overwritten. This
 595   // method will be called during an exception unwind.
 596 
 597   assert(!HAS_PENDING_EXCEPTION, "no pending exception");
 598   Handle exception(thread, thread->vm_result());
 599   assert(exception() != NULL, "vm result should be set");
 600   thread->set_vm_result(NULL); // clear vm result before continuing (may cause memory leaks and assert failures)
 601   if (!exception->is_a(SystemDictionary::ThreadDeath_klass())) {
 602     exception = get_preinitialized_exception(
 603                        SystemDictionary::IllegalMonitorStateException_klass(),
 604                        CATCH);
 605   }
 606   thread->set_vm_result(exception());
 607 IRT_END
 608 
 609 
 610 //------------------------------------------------------------------------------------------------------------------------
 611 // Invokes
 612 
 613 IRT_ENTRY(Bytecodes::Code, InterpreterRuntime::get_original_bytecode_at(JavaThread* thread, methodOopDesc* method, address bcp))
 614   return method->orig_bytecode_at(method->bci_from(bcp));
 615 IRT_END
 616 
 617 IRT_ENTRY(void, InterpreterRuntime::set_original_bytecode_at(JavaThread* thread, methodOopDesc* method, address bcp, Bytecodes::Code new_code))
 618   method->set_orig_bytecode_at(method->bci_from(bcp), new_code);
 619 IRT_END
 620 
 621 IRT_ENTRY(void, InterpreterRuntime::_breakpoint(JavaThread* thread, methodOopDesc* method, address bcp))
 622   JvmtiExport::post_raw_breakpoint(thread, method, bcp);
 623 IRT_END
 624 
 625 IRT_ENTRY(void, InterpreterRuntime::resolve_invoke(JavaThread* thread, Bytecodes::Code bytecode))
 626   // extract receiver from the outgoing argument list if necessary
 627   Handle receiver(thread, NULL);
 628   if (bytecode == Bytecodes::_invokevirtual || bytecode == Bytecodes::_invokeinterface) {
 629     ResourceMark rm(thread);
 630     methodHandle m (thread, method(thread));
 631     Bytecode_invoke* call = Bytecode_invoke_at(m, bci(thread));
 632     symbolHandle signature (thread, call->signature());
 633     receiver = Handle(thread,
 634                   thread->last_frame().interpreter_callee_receiver(signature));
 635     assert(Universe::heap()->is_in_reserved_or_null(receiver()),
 636            "sanity check");
 637     assert(receiver.is_null() ||
 638            Universe::heap()->is_in_reserved(receiver->klass()),
 639            "sanity check");
 640   }
 641 
 642   // resolve method
 643   CallInfo info;
 644   constantPoolHandle pool(thread, method(thread)->constants());
 645 
 646   {
 647     JvmtiHideSingleStepping jhss(thread);
 648     LinkResolver::resolve_invoke(info, receiver, pool,
 649                                  get_index_u2_cpcache(thread, bytecode), bytecode, CHECK);
 650     if (JvmtiExport::can_hotswap_or_post_breakpoint()) {
 651       int retry_count = 0;
 652       while (info.resolved_method()->is_old()) {
 653         // It is very unlikely that method is redefined more than 100 times
 654         // in the middle of resolve. If it is looping here more than 100 times
 655         // means then there could be a bug here.
 656         guarantee((retry_count++ < 100),
 657                   "Could not resolve to latest version of redefined method");
 658         // method is redefined in the middle of resolve so re-try.
 659         LinkResolver::resolve_invoke(info, receiver, pool,
 660                                      get_index_u2_cpcache(thread, bytecode), bytecode, CHECK);
 661       }
 662     }
 663   } // end JvmtiHideSingleStepping
 664 
 665   // check if link resolution caused cpCache to be updated
 666   if (already_resolved(thread)) return;
 667 
 668   if (bytecode == Bytecodes::_invokeinterface) {
 669 
 670     if (TraceItables && Verbose) {
 671       ResourceMark rm(thread);
 672       tty->print_cr("Resolving: klass: %s to method: %s", info.resolved_klass()->name()->as_C_string(), info.resolved_method()->name()->as_C_string());
 673     }
 674     if (info.resolved_method()->method_holder() ==
 675                                             SystemDictionary::Object_klass()) {
 676       // NOTE: THIS IS A FIX FOR A CORNER CASE in the JVM spec
 677       // (see also cpCacheOop.cpp for details)
 678       methodHandle rm = info.resolved_method();
 679       assert(rm->is_final() || info.has_vtable_index(),
 680              "should have been set already");
 681       cache_entry(thread)->set_method(bytecode, rm, info.vtable_index());
 682     } else {
 683       // Setup itable entry
 684       int index = klassItable::compute_itable_index(info.resolved_method()());
 685       cache_entry(thread)->set_interface_call(info.resolved_method(), index);
 686     }
 687   } else {
 688     cache_entry(thread)->set_method(
 689       bytecode,
 690       info.resolved_method(),
 691       info.vtable_index());
 692   }
 693 IRT_END
 694 
 695 
 696 // First time execution:  Resolve symbols, create a permanent CallSite object.
 697 IRT_ENTRY(void, InterpreterRuntime::resolve_invokedynamic(JavaThread* thread)) {
 698   ResourceMark rm(thread);
 699 
 700   assert(EnableInvokeDynamic, "");
 701 
 702   const Bytecodes::Code bytecode = Bytecodes::_invokedynamic;
 703 
 704   methodHandle caller_method(thread, method(thread));
 705 
 706   constantPoolHandle pool(thread, caller_method->constants());
 707   pool->set_invokedynamic();    // mark header to flag active call sites
 708 
 709   int caller_bci = 0;
 710   int site_index = 0;
 711   { address caller_bcp = bcp(thread);
 712     caller_bci = caller_method->bci_from(caller_bcp);
 713     site_index = Bytes::get_native_u4(caller_bcp+1);
 714   }
 715   assert(site_index == InterpreterRuntime::bytecode(thread)->get_index_u4(bytecode), "");
 716   assert(constantPoolCacheOopDesc::is_secondary_index(site_index), "proper format");
 717   // there is a second CPC entries that is of interest; it caches signature info:
 718   int main_index = pool->cache()->secondary_entry_at(site_index)->main_entry_index();
 719 
 720   // first resolve the signature to a MH.invoke methodOop
 721   if (!pool->cache()->entry_at(main_index)->is_resolved(bytecode)) {
 722     JvmtiHideSingleStepping jhss(thread);
 723     CallInfo info;
 724     LinkResolver::resolve_invoke(info, Handle(), pool,
 725                                  site_index, bytecode, CHECK);
 726     // The main entry corresponds to a JVM_CONSTANT_InvokeDynamic, and serves
 727     // as a common reference point for all invokedynamic call sites with
 728     // that exact call descriptor.  We will link it in the CP cache exactly
 729     // as if it were an invokevirtual of MethodHandle.invoke.
 730     pool->cache()->entry_at(main_index)->set_method(
 731       bytecode,
 732       info.resolved_method(),
 733       info.vtable_index());
 734   }
 735 
 736   // The method (f2 entry) of the main entry is the MH.invoke for the
 737   // invokedynamic target call signature.
 738   oop f1_value = pool->cache()->entry_at(main_index)->f1();
 739   methodHandle signature_invoker(THREAD, (methodOop) f1_value);
 740   assert(signature_invoker.not_null() && signature_invoker->is_method() && signature_invoker->is_method_handle_invoke(),
 741          "correct result from LinkResolver::resolve_invokedynamic");
 742 
 743   Handle bootm = SystemDictionary::find_bootstrap_method(caller_method, caller_bci,
 744                                                          main_index, CHECK);
 745   if (bootm.is_null()) {
 746     THROW_MSG(vmSymbols::java_lang_IllegalStateException(),
 747               "no bootstrap method found for invokedynamic");
 748   }
 749 
 750   // Short circuit if CallSite has been bound already:
 751   if (!pool->cache()->secondary_entry_at(site_index)->is_f1_null())
 752     return;
 753 
 754   symbolHandle call_site_name(THREAD, pool->name_ref_at(site_index));
 755 
 756   Handle info;  // NYI: Other metadata from a new kind of CP entry.  (Annotations?)
 757 
 758   Handle call_site
 759     = SystemDictionary::make_dynamic_call_site(bootm,
 760                                                // Callee information:
 761                                                call_site_name,
 762                                                signature_invoker,
 763                                                info,
 764                                                // Caller information:
 765                                                caller_method,
 766                                                caller_bci,
 767                                                CHECK);
 768 
 769   // In the secondary entry, the f1 field is the call site, and the f2 (index)
 770   // field is some data about the invoke site.  Currently, it is just the BCI.
 771   // Later, it might be changed to help manage inlining dependencies.
 772   pool->cache()->secondary_entry_at(site_index)->set_dynamic_call(call_site, signature_invoker);
 773 }
 774 IRT_END
 775 
 776 
 777 //------------------------------------------------------------------------------------------------------------------------
 778 // Miscellaneous
 779 
 780 
 781 nmethod* InterpreterRuntime::frequency_counter_overflow(JavaThread* thread, address branch_bcp) {
 782   nmethod* nm = frequency_counter_overflow_inner(thread, branch_bcp);
 783   assert(branch_bcp != NULL || nm == NULL, "always returns null for non OSR requests");
 784   if (branch_bcp != NULL && nm != NULL) {
 785     // This was a successful request for an OSR nmethod.  Because
 786     // frequency_counter_overflow_inner ends with a safepoint check,
 787     // nm could have been unloaded so look it up again.  It's unsafe
 788     // to examine nm directly since it might have been freed and used
 789     // for something else.
 790     frame fr = thread->last_frame();
 791     methodOop method =  fr.interpreter_frame_method();
 792     int bci = method->bci_from(fr.interpreter_frame_bcp());
 793     nm = method->lookup_osr_nmethod_for(bci, CompLevel_none, false);
 794   }
 795   return nm;
 796 }
 797 
 798 IRT_ENTRY(nmethod*,
 799           InterpreterRuntime::frequency_counter_overflow_inner(JavaThread* thread, address branch_bcp))
 800   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
 801   // flag, in case this method triggers classloading which will call into Java.
 802   UnlockFlagSaver fs(thread);
 803 
 804   frame fr = thread->last_frame();
 805   assert(fr.is_interpreted_frame(), "must come from interpreter");
 806   methodHandle method(thread, fr.interpreter_frame_method());
 807   const int branch_bci = branch_bcp != NULL ? method->bci_from(branch_bcp) : InvocationEntryBci;
 808   const int bci = branch_bcp != NULL ? method->bci_from(fr.interpreter_frame_bcp()) : InvocationEntryBci;
 809 
 810   nmethod* osr_nm = CompilationPolicy::policy()->event(method, method, branch_bci, bci, CompLevel_none, thread);
 811 
 812   if (osr_nm != NULL) {
 813     // We may need to do on-stack replacement which requires that no
 814     // monitors in the activation are biased because their
 815     // BasicObjectLocks will need to migrate during OSR. Force
 816     // unbiasing of all monitors in the activation now (even though
 817     // the OSR nmethod might be invalidated) because we don't have a
 818     // safepoint opportunity later once the migration begins.
 819     if (UseBiasedLocking) {
 820       ResourceMark rm;
 821       GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();
 822       for( BasicObjectLock *kptr = fr.interpreter_frame_monitor_end();
 823            kptr < fr.interpreter_frame_monitor_begin();
 824            kptr = fr.next_monitor_in_interpreter_frame(kptr) ) {
 825         if( kptr->obj() != NULL ) {
 826           objects_to_revoke->append(Handle(THREAD, kptr->obj()));
 827         }
 828       }
 829       BiasedLocking::revoke(objects_to_revoke);
 830     }
 831   }
 832   return osr_nm;
 833 IRT_END
 834 
 835 IRT_LEAF(jint, InterpreterRuntime::bcp_to_di(methodOopDesc* method, address cur_bcp))
 836   assert(ProfileInterpreter, "must be profiling interpreter");
 837   int bci = method->bci_from(cur_bcp);
 838   methodDataOop mdo = method->method_data();
 839   if (mdo == NULL)  return 0;
 840   return mdo->bci_to_di(bci);
 841 IRT_END
 842 
 843 IRT_ENTRY(jint, InterpreterRuntime::profile_method(JavaThread* thread, address cur_bcp))
 844   // use UnlockFlagSaver to clear and restore the _do_not_unlock_if_synchronized
 845   // flag, in case this method triggers classloading which will call into Java.
 846   UnlockFlagSaver fs(thread);
 847 
 848   assert(ProfileInterpreter, "must be profiling interpreter");
 849   frame fr = thread->last_frame();
 850   assert(fr.is_interpreted_frame(), "must come from interpreter");
 851   methodHandle method(thread, fr.interpreter_frame_method());
 852   int bci = method->bci_from(cur_bcp);
 853   methodOopDesc::build_interpreter_method_data(method, THREAD);
 854   if (HAS_PENDING_EXCEPTION) {
 855     assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
 856     CLEAR_PENDING_EXCEPTION;
 857     // and fall through...
 858   }
 859   methodDataOop mdo = method->method_data();
 860   if (mdo == NULL)  return 0;
 861   return mdo->bci_to_di(bci);
 862 IRT_END
 863 
 864 
 865 #ifdef ASSERT
 866 IRT_LEAF(void, InterpreterRuntime::verify_mdp(methodOopDesc* method, address bcp, address mdp))
 867   assert(ProfileInterpreter, "must be profiling interpreter");
 868 
 869   methodDataOop mdo = method->method_data();
 870   assert(mdo != NULL, "must not be null");
 871 
 872   int bci = method->bci_from(bcp);
 873 
 874   address mdp2 = mdo->bci_to_dp(bci);
 875   if (mdp != mdp2) {
 876     ResourceMark rm;
 877     ResetNoHandleMark rnm; // In a LEAF entry.
 878     HandleMark hm;
 879     tty->print_cr("FAILED verify : actual mdp %p   expected mdp %p @ bci %d", mdp, mdp2, bci);
 880     int current_di = mdo->dp_to_di(mdp);
 881     int expected_di  = mdo->dp_to_di(mdp2);
 882     tty->print_cr("  actual di %d   expected di %d", current_di, expected_di);
 883     int expected_approx_bci = mdo->data_at(expected_di)->bci();
 884     int approx_bci = -1;
 885     if (current_di >= 0) {
 886       approx_bci = mdo->data_at(current_di)->bci();
 887     }
 888     tty->print_cr("  actual bci is %d  expected bci %d", approx_bci, expected_approx_bci);
 889     mdo->print_on(tty);
 890     method->print_codes();
 891   }
 892   assert(mdp == mdp2, "wrong mdp");
 893 IRT_END
 894 #endif // ASSERT
 895 
 896 IRT_ENTRY(void, InterpreterRuntime::update_mdp_for_ret(JavaThread* thread, int return_bci))
 897   assert(ProfileInterpreter, "must be profiling interpreter");
 898   ResourceMark rm(thread);
 899   HandleMark hm(thread);
 900   frame fr = thread->last_frame();
 901   assert(fr.is_interpreted_frame(), "must come from interpreter");
 902   methodDataHandle h_mdo(thread, fr.interpreter_frame_method()->method_data());
 903 
 904   // Grab a lock to ensure atomic access to setting the return bci and
 905   // the displacement.  This can block and GC, invalidating all naked oops.
 906   MutexLocker ml(RetData_lock);
 907 
 908   // ProfileData is essentially a wrapper around a derived oop, so we
 909   // need to take the lock before making any ProfileData structures.
 910   ProfileData* data = h_mdo->data_at(h_mdo->dp_to_di(fr.interpreter_frame_mdp()));
 911   RetData* rdata = data->as_RetData();
 912   address new_mdp = rdata->fixup_ret(return_bci, h_mdo);
 913   fr.interpreter_frame_set_mdp(new_mdp);
 914 IRT_END
 915 
 916 
 917 IRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* thread))
 918   // We used to need an explict preserve_arguments here for invoke bytecodes. However,
 919   // stack traversal automatically takes care of preserving arguments for invoke, so
 920   // this is no longer needed.
 921 
 922   // IRT_END does an implicit safepoint check, hence we are guaranteed to block
 923   // if this is called during a safepoint
 924 
 925   if (JvmtiExport::should_post_single_step()) {
 926     // We are called during regular safepoints and when the VM is
 927     // single stepping. If any thread is marked for single stepping,
 928     // then we may have JVMTI work to do.
 929     JvmtiExport::at_single_stepping_point(thread, method(thread), bcp(thread));
 930   }
 931 IRT_END
 932 
 933 IRT_ENTRY(void, InterpreterRuntime::post_field_access(JavaThread *thread, oopDesc* obj,
 934 ConstantPoolCacheEntry *cp_entry))
 935 
 936   // check the access_flags for the field in the klass
 937   instanceKlass* ik = instanceKlass::cast((klassOop)cp_entry->f1());
 938   typeArrayOop fields = ik->fields();
 939   int index = cp_entry->field_index();
 940   assert(index < fields->length(), "holders field index is out of range");
 941   // bail out if field accesses are not watched
 942   if ((fields->ushort_at(index) & JVM_ACC_FIELD_ACCESS_WATCHED) == 0) return;
 943 
 944   switch(cp_entry->flag_state()) {
 945     case btos:    // fall through
 946     case ctos:    // fall through
 947     case stos:    // fall through
 948     case itos:    // fall through
 949     case ftos:    // fall through
 950     case ltos:    // fall through
 951     case dtos:    // fall through
 952     case atos: break;
 953     default: ShouldNotReachHere(); return;
 954   }
 955   bool is_static = (obj == NULL);
 956   HandleMark hm(thread);
 957 
 958   Handle h_obj;
 959   if (!is_static) {
 960     // non-static field accessors have an object, but we need a handle
 961     h_obj = Handle(thread, obj);
 962   }
 963   instanceKlassHandle h_cp_entry_f1(thread, (klassOop)cp_entry->f1());
 964   jfieldID fid = jfieldIDWorkaround::to_jfieldID(h_cp_entry_f1, cp_entry->f2(), is_static);
 965   JvmtiExport::post_field_access(thread, method(thread), bcp(thread), h_cp_entry_f1, h_obj, fid);
 966 IRT_END
 967 
 968 IRT_ENTRY(void, InterpreterRuntime::post_field_modification(JavaThread *thread,
 969   oopDesc* obj, ConstantPoolCacheEntry *cp_entry, jvalue *value))
 970 
 971   klassOop k = (klassOop)cp_entry->f1();
 972 
 973   // check the access_flags for the field in the klass
 974   instanceKlass* ik = instanceKlass::cast(k);
 975   typeArrayOop fields = ik->fields();
 976   int index = cp_entry->field_index();
 977   assert(index < fields->length(), "holders field index is out of range");
 978   // bail out if field modifications are not watched
 979   if ((fields->ushort_at(index) & JVM_ACC_FIELD_MODIFICATION_WATCHED) == 0) return;
 980 
 981   char sig_type = '\0';
 982 
 983   switch(cp_entry->flag_state()) {
 984     case btos: sig_type = 'Z'; break;
 985     case ctos: sig_type = 'C'; break;
 986     case stos: sig_type = 'S'; break;
 987     case itos: sig_type = 'I'; break;
 988     case ftos: sig_type = 'F'; break;
 989     case atos: sig_type = 'L'; break;
 990     case ltos: sig_type = 'J'; break;
 991     case dtos: sig_type = 'D'; break;
 992     default:  ShouldNotReachHere(); return;
 993   }
 994   bool is_static = (obj == NULL);
 995 
 996   HandleMark hm(thread);
 997   instanceKlassHandle h_klass(thread, k);
 998   jfieldID fid = jfieldIDWorkaround::to_jfieldID(h_klass, cp_entry->f2(), is_static);
 999   jvalue fvalue;
1000 #ifdef _LP64
1001   fvalue = *value;
1002 #else
1003   // Long/double values are stored unaligned and also noncontiguously with
1004   // tagged stacks.  We can't just do a simple assignment even in the non-
1005   // J/D cases because a C++ compiler is allowed to assume that a jvalue is
1006   // 8-byte aligned, and interpreter stack slots are only 4-byte aligned.
1007   // We assume that the two halves of longs/doubles are stored in interpreter
1008   // stack slots in platform-endian order.
1009   jlong_accessor u;
1010   jint* newval = (jint*)value;
1011   u.words[0] = newval[0];
1012   u.words[1] = newval[Interpreter::stackElementWords]; // skip if tag
1013   fvalue.j = u.long_value;
1014 #endif // _LP64
1015 
1016   Handle h_obj;
1017   if (!is_static) {
1018     // non-static field accessors have an object, but we need a handle
1019     h_obj = Handle(thread, obj);
1020   }
1021 
1022   JvmtiExport::post_raw_field_modification(thread, method(thread), bcp(thread), h_klass, h_obj,
1023                                            fid, sig_type, &fvalue);
1024 IRT_END
1025 
1026 IRT_ENTRY(void, InterpreterRuntime::post_method_entry(JavaThread *thread))
1027   JvmtiExport::post_method_entry(thread, InterpreterRuntime::method(thread), InterpreterRuntime::last_frame(thread));
1028 IRT_END
1029 
1030 
1031 IRT_ENTRY(void, InterpreterRuntime::post_method_exit(JavaThread *thread))
1032   JvmtiExport::post_method_exit(thread, InterpreterRuntime::method(thread), InterpreterRuntime::last_frame(thread));
1033 IRT_END
1034 
1035 IRT_LEAF(int, InterpreterRuntime::interpreter_contains(address pc))
1036 {
1037   return (Interpreter::contains(pc) ? 1 : 0);
1038 }
1039 IRT_END
1040 
1041 
1042 // Implementation of SignatureHandlerLibrary
1043 
1044 address SignatureHandlerLibrary::set_handler_blob() {
1045   BufferBlob* handler_blob = BufferBlob::create("native signature handlers", blob_size);
1046   if (handler_blob == NULL) {
1047     return NULL;
1048   }
1049   address handler = handler_blob->code_begin();
1050   _handler_blob = handler_blob;
1051   _handler = handler;
1052   return handler;
1053 }
1054 
1055 void SignatureHandlerLibrary::initialize() {
1056   if (_fingerprints != NULL) {
1057     return;
1058   }
1059   if (set_handler_blob() == NULL) {
1060     vm_exit_out_of_memory(blob_size, "native signature handlers");
1061   }
1062 
1063   BufferBlob* bb = BufferBlob::create("Signature Handler Temp Buffer",
1064                                       SignatureHandlerLibrary::buffer_size);
1065   _buffer = bb->code_begin();
1066 
1067   _fingerprints = new(ResourceObj::C_HEAP)GrowableArray<uint64_t>(32, true);
1068   _handlers     = new(ResourceObj::C_HEAP)GrowableArray<address>(32, true);
1069 }
1070 
1071 address SignatureHandlerLibrary::set_handler(CodeBuffer* buffer) {
1072   address handler   = _handler;
1073   int     insts_size = buffer->pure_insts_size();
1074   if (handler + insts_size > _handler_blob->code_end()) {
1075     // get a new handler blob
1076     handler = set_handler_blob();
1077   }
1078   if (handler != NULL) {
1079     memcpy(handler, buffer->insts_begin(), insts_size);
1080     pd_set_handler(handler);
1081     ICache::invalidate_range(handler, insts_size);
1082     _handler = handler + insts_size;
1083   }
1084   return handler;
1085 }
1086 
1087 void SignatureHandlerLibrary::add(methodHandle method) {
1088   if (method->signature_handler() == NULL) {
1089     // use slow signature handler if we can't do better
1090     int handler_index = -1;
1091     // check if we can use customized (fast) signature handler
1092     if (UseFastSignatureHandlers && method->size_of_parameters() <= Fingerprinter::max_size_of_parameters) {
1093       // use customized signature handler
1094       MutexLocker mu(SignatureHandlerLibrary_lock);
1095       // make sure data structure is initialized
1096       initialize();
1097       // lookup method signature's fingerprint
1098       uint64_t fingerprint = Fingerprinter(method).fingerprint();
1099       handler_index = _fingerprints->find(fingerprint);
1100       // create handler if necessary
1101       if (handler_index < 0) {
1102         ResourceMark rm;
1103         ptrdiff_t align_offset = (address)
1104           round_to((intptr_t)_buffer, CodeEntryAlignment) - (address)_buffer;
1105         CodeBuffer buffer((address)(_buffer + align_offset),
1106                           SignatureHandlerLibrary::buffer_size - align_offset);
1107         InterpreterRuntime::SignatureHandlerGenerator(method, &buffer).generate(fingerprint);
1108         // copy into code heap
1109         address handler = set_handler(&buffer);
1110         if (handler == NULL) {
1111           // use slow signature handler
1112         } else {
1113           // debugging suppport
1114           if (PrintSignatureHandlers) {
1115             tty->cr();
1116             tty->print_cr("argument handler #%d for: %s %s (fingerprint = " UINT64_FORMAT ", %d bytes generated)",
1117                           _handlers->length(),
1118                           (method->is_static() ? "static" : "receiver"),
1119                           method->name_and_sig_as_C_string(),
1120                           fingerprint,
1121                           buffer.insts_size());
1122             Disassembler::decode(handler, handler + buffer.insts_size());
1123 #ifndef PRODUCT
1124             tty->print_cr(" --- associated result handler ---");
1125             address rh_begin = Interpreter::result_handler(method()->result_type());
1126             address rh_end = rh_begin;
1127             while (*(int*)rh_end != 0) {
1128               rh_end += sizeof(int);
1129             }
1130             Disassembler::decode(rh_begin, rh_end);
1131 #endif
1132           }
1133           // add handler to library
1134           _fingerprints->append(fingerprint);
1135           _handlers->append(handler);
1136           // set handler index
1137           assert(_fingerprints->length() == _handlers->length(), "sanity check");
1138           handler_index = _fingerprints->length() - 1;
1139         }
1140       }
1141     } else {
1142       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
1143     }
1144     if (handler_index < 0) {
1145       // use generic signature handler
1146       method->set_signature_handler(Interpreter::slow_signature_handler());
1147     } else {
1148       // set handler
1149       method->set_signature_handler(_handlers->at(handler_index));
1150     }
1151   }
1152   assert(method->signature_handler() == Interpreter::slow_signature_handler() ||
1153          _handlers->find(method->signature_handler()) == _fingerprints->find(Fingerprinter(method).fingerprint()),
1154          "sanity check");
1155 }
1156 
1157 
1158 BufferBlob*              SignatureHandlerLibrary::_handler_blob = NULL;
1159 address                  SignatureHandlerLibrary::_handler      = NULL;
1160 GrowableArray<uint64_t>* SignatureHandlerLibrary::_fingerprints = NULL;
1161 GrowableArray<address>*  SignatureHandlerLibrary::_handlers     = NULL;
1162 address                  SignatureHandlerLibrary::_buffer       = NULL;
1163 
1164 
1165 IRT_ENTRY(void, InterpreterRuntime::prepare_native_call(JavaThread* thread, methodOopDesc* method))
1166   methodHandle m(thread, method);
1167   assert(m->is_native(), "sanity check");
1168   // lookup native function entry point if it doesn't exist
1169   bool in_base_library;
1170   if (!m->has_native_function()) {
1171     NativeLookup::lookup(m, in_base_library, CHECK);
1172   }
1173   // make sure signature handler is installed
1174   SignatureHandlerLibrary::add(m);
1175   // The interpreter entry point checks the signature handler first,
1176   // before trying to fetch the native entry point and klass mirror.
1177   // We must set the signature handler last, so that multiple processors
1178   // preparing the same method will be sure to see non-null entry & mirror.
1179 IRT_END
1180 
1181 #if defined(IA32) || defined(AMD64)
1182 IRT_LEAF(void, InterpreterRuntime::popframe_move_outgoing_args(JavaThread* thread, void* src_address, void* dest_address))
1183   if (src_address == dest_address) {
1184     return;
1185   }
1186   ResetNoHandleMark rnm; // In a LEAF entry.
1187   HandleMark hm;
1188   ResourceMark rm;
1189   frame fr = thread->last_frame();
1190   assert(fr.is_interpreted_frame(), "");
1191   jint bci = fr.interpreter_frame_bci();
1192   methodHandle mh(thread, fr.interpreter_frame_method());
1193   Bytecode_invoke* invoke = Bytecode_invoke_at(mh, bci);
1194   ArgumentSizeComputer asc(invoke->signature());
1195   int size_of_arguments = (asc.size() + (invoke->has_receiver() ? 1 : 0)); // receiver
1196   Copy::conjoint_jbytes(src_address, dest_address,
1197                        size_of_arguments * Interpreter::stackElementSize);
1198 IRT_END
1199 #endif