1 /*
   2  * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "classfile/systemDictionary.hpp"
  27 #include "interpreter/interpreter.hpp"
  28 #include "jvmtifiles/jvmtiEnv.hpp"
  29 #include "memory/resourceArea.hpp"
  30 #include "oops/instanceKlass.hpp"
  31 #include "prims/jvmtiAgentThread.hpp"
  32 #include "prims/jvmtiEventController.inline.hpp"
  33 #include "prims/jvmtiImpl.hpp"
  34 #include "prims/jvmtiRedefineClasses.hpp"
  35 #include "runtime/atomic.hpp"
  36 #include "runtime/deoptimization.hpp"
  37 #include "runtime/handles.hpp"
  38 #include "runtime/handles.inline.hpp"
  39 #include "runtime/interfaceSupport.hpp"
  40 #include "runtime/javaCalls.hpp"
  41 #include "runtime/os.hpp"
  42 #include "runtime/serviceThread.hpp"
  43 #include "runtime/signature.hpp"
  44 #include "runtime/vframe.hpp"
  45 #include "runtime/vframe_hp.hpp"
  46 #include "runtime/vm_operations.hpp"
  47 #include "utilities/exceptions.hpp"
  48 #ifdef TARGET_OS_FAMILY_linux
  49 # include "thread_linux.inline.hpp"
  50 #endif
  51 #ifdef TARGET_OS_FAMILY_solaris
  52 # include "thread_solaris.inline.hpp"
  53 #endif
  54 #ifdef TARGET_OS_FAMILY_windows
  55 # include "thread_windows.inline.hpp"
  56 #endif
  57 #ifdef TARGET_OS_FAMILY_bsd
  58 # include "thread_bsd.inline.hpp"
  59 #endif
  60 
  61 //
  62 // class JvmtiAgentThread
  63 //
  64 // JavaThread used to wrap a thread started by an agent
  65 // using the JVMTI method RunAgentThread.
  66 //
  67 
  68 JvmtiAgentThread::JvmtiAgentThread(JvmtiEnv* env, jvmtiStartFunction start_fn, const void *start_arg)
  69     : JavaThread(start_function_wrapper) {
  70     _env = env;
  71     _start_fn = start_fn;
  72     _start_arg = start_arg;
  73 }
  74 
  75 void
  76 JvmtiAgentThread::start_function_wrapper(JavaThread *thread, TRAPS) {
  77     // It is expected that any Agent threads will be created as
  78     // Java Threads.  If this is the case, notification of the creation
  79     // of the thread is given in JavaThread::thread_main().
  80     assert(thread->is_Java_thread(), "debugger thread should be a Java Thread");
  81     assert(thread == JavaThread::current(), "sanity check");
  82 
  83     JvmtiAgentThread *dthread = (JvmtiAgentThread *)thread;
  84     dthread->call_start_function();
  85 }
  86 
  87 void
  88 JvmtiAgentThread::call_start_function() {
  89     ThreadToNativeFromVM transition(this);
  90     _start_fn(_env->jvmti_external(), jni_environment(), (void*)_start_arg);
  91 }
  92 
  93 
  94 //
  95 // class GrowableCache - private methods
  96 //
  97 
  98 void GrowableCache::recache() {
  99   int len = _elements->length();
 100 
 101   FREE_C_HEAP_ARRAY(address, _cache, mtInternal);
 102   _cache = NEW_C_HEAP_ARRAY(address,len+1, mtInternal);
 103 
 104   for (int i=0; i<len; i++) {
 105     _cache[i] = _elements->at(i)->getCacheValue();
 106     //
 107     // The cache entry has gone bad. Without a valid frame pointer
 108     // value, the entry is useless so we simply delete it in product
 109     // mode. The call to remove() will rebuild the cache again
 110     // without the bad entry.
 111     //
 112     if (_cache[i] == NULL) {
 113       assert(false, "cannot recache NULL elements");
 114       remove(i);
 115       return;
 116     }
 117   }
 118   _cache[len] = NULL;
 119 
 120   _listener_fun(_this_obj,_cache);
 121 }
 122 
 123 bool GrowableCache::equals(void* v, GrowableElement *e2) {
 124   GrowableElement *e1 = (GrowableElement *) v;
 125   assert(e1 != NULL, "e1 != NULL");
 126   assert(e2 != NULL, "e2 != NULL");
 127 
 128   return e1->equals(e2);
 129 }
 130 
 131 //
 132 // class GrowableCache - public methods
 133 //
 134 
 135 GrowableCache::GrowableCache() {
 136   _this_obj       = NULL;
 137   _listener_fun   = NULL;
 138   _elements       = NULL;
 139   _cache          = NULL;
 140 }
 141 
 142 GrowableCache::~GrowableCache() {
 143   clear();
 144   delete _elements;
 145   FREE_C_HEAP_ARRAY(address, _cache, mtInternal);
 146 }
 147 
 148 void GrowableCache::initialize(void *this_obj, void listener_fun(void *, address*) ) {
 149   _this_obj       = this_obj;
 150   _listener_fun   = listener_fun;
 151   _elements       = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<GrowableElement*>(5,true);
 152   recache();
 153 }
 154 
 155 // number of elements in the collection
 156 int GrowableCache::length() {
 157   return _elements->length();
 158 }
 159 
 160 // get the value of the index element in the collection
 161 GrowableElement* GrowableCache::at(int index) {
 162   GrowableElement *e = (GrowableElement *) _elements->at(index);
 163   assert(e != NULL, "e != NULL");
 164   return e;
 165 }
 166 
 167 int GrowableCache::find(GrowableElement* e) {
 168   return _elements->find(e, GrowableCache::equals);
 169 }
 170 
 171 // append a copy of the element to the end of the collection
 172 void GrowableCache::append(GrowableElement* e) {
 173   GrowableElement *new_e = e->clone();
 174   _elements->append(new_e);
 175   recache();
 176 }
 177 
 178 // insert a copy of the element using lessthan()
 179 void GrowableCache::insert(GrowableElement* e) {
 180   GrowableElement *new_e = e->clone();
 181   _elements->append(new_e);
 182 
 183   int n = length()-2;
 184   for (int i=n; i>=0; i--) {
 185     GrowableElement *e1 = _elements->at(i);
 186     GrowableElement *e2 = _elements->at(i+1);
 187     if (e2->lessThan(e1)) {
 188       _elements->at_put(i+1, e1);
 189       _elements->at_put(i,   e2);
 190     }
 191   }
 192 
 193   recache();
 194 }
 195 
 196 // remove the element at index
 197 void GrowableCache::remove (int index) {
 198   GrowableElement *e = _elements->at(index);
 199   assert(e != NULL, "e != NULL");
 200   _elements->remove(e);
 201   delete e;
 202   recache();
 203 }
 204 
 205 // clear out all elements, release all heap space and
 206 // let our listener know that things have changed.
 207 void GrowableCache::clear() {
 208   int len = _elements->length();
 209   for (int i=0; i<len; i++) {
 210     delete _elements->at(i);
 211   }
 212   _elements->clear();
 213   recache();
 214 }
 215 
 216 void GrowableCache::oops_do(OopClosure* f) {
 217   int len = _elements->length();
 218   for (int i=0; i<len; i++) {
 219     GrowableElement *e = _elements->at(i);
 220     e->oops_do(f);
 221   }
 222 }
 223 
 224 void GrowableCache::gc_epilogue() {
 225   int len = _elements->length();
 226   for (int i=0; i<len; i++) {
 227     _cache[i] = _elements->at(i)->getCacheValue();
 228   }
 229 }
 230 
 231 //
 232 // class JvmtiBreakpoint
 233 //
 234 
 235 JvmtiBreakpoint::JvmtiBreakpoint() {
 236   _method = NULL;
 237   _bci    = 0;
 238 #ifdef CHECK_UNHANDLED_OOPS
 239   // This one is always allocated with new, but check it just in case.
 240   Thread *thread = Thread::current();
 241   if (thread->is_in_stack((address)&_method)) {
 242     thread->allow_unhandled_oop((oop*)&_method);
 243   }
 244 #endif // CHECK_UNHANDLED_OOPS
 245 }
 246 
 247 JvmtiBreakpoint::JvmtiBreakpoint(methodOop m_method, jlocation location) {
 248   _method        = m_method;
 249   assert(_method != NULL, "_method != NULL");
 250   _bci           = (int) location;
 251 #ifdef CHECK_UNHANDLED_OOPS
 252   // Could be allocated with new and wouldn't be on the unhandled oop list.
 253   Thread *thread = Thread::current();
 254   if (thread->is_in_stack((address)&_method)) {
 255     thread->allow_unhandled_oop(&_method);
 256   }
 257 #endif // CHECK_UNHANDLED_OOPS
 258 
 259   assert(_bci >= 0, "_bci >= 0");
 260 }
 261 
 262 void JvmtiBreakpoint::copy(JvmtiBreakpoint& bp) {
 263   _method   = bp._method;
 264   _bci      = bp._bci;
 265 }
 266 
 267 bool JvmtiBreakpoint::lessThan(JvmtiBreakpoint& bp) {
 268   Unimplemented();
 269   return false;
 270 }
 271 
 272 bool JvmtiBreakpoint::equals(JvmtiBreakpoint& bp) {
 273   return _method   == bp._method
 274     &&   _bci      == bp._bci;
 275 }
 276 
 277 bool JvmtiBreakpoint::is_valid() {
 278   return _method != NULL &&
 279          _bci >= 0;
 280 }
 281 
 282 address JvmtiBreakpoint::getBcp() {
 283   return _method->bcp_from(_bci);
 284 }
 285 
 286 void JvmtiBreakpoint::each_method_version_do(method_action meth_act) {
 287   ((methodOopDesc*)_method->*meth_act)(_bci);
 288 
 289   // add/remove breakpoint to/from versions of the method that
 290   // are EMCP. Directly or transitively obsolete methods are
 291   // not saved in the PreviousVersionInfo.
 292   Thread *thread = Thread::current();
 293   instanceKlassHandle ikh = instanceKlassHandle(thread, _method->method_holder());
 294   Symbol* m_name = _method->name();
 295   Symbol* m_signature = _method->signature();
 296 
 297   {
 298     ResourceMark rm(thread);
 299     // PreviousVersionInfo objects returned via PreviousVersionWalker
 300     // contain a GrowableArray of handles. We have to clean up the
 301     // GrowableArray _after_ the PreviousVersionWalker destructor
 302     // has destroyed the handles.
 303     {
 304       // search previous versions if they exist
 305       PreviousVersionWalker pvw((instanceKlass *)ikh()->klass_part());
 306       for (PreviousVersionInfo * pv_info = pvw.next_previous_version();
 307            pv_info != NULL; pv_info = pvw.next_previous_version()) {
 308         GrowableArray<methodHandle>* methods =
 309           pv_info->prev_EMCP_method_handles();
 310 
 311         if (methods == NULL) {
 312           // We have run into a PreviousVersion generation where
 313           // all methods were made obsolete during that generation's
 314           // RedefineClasses() operation. At the time of that
 315           // operation, all EMCP methods were flushed so we don't
 316           // have to go back any further.
 317           //
 318           // A NULL methods array is different than an empty methods
 319           // array. We cannot infer any optimizations about older
 320           // generations from an empty methods array for the current
 321           // generation.
 322           break;
 323         }
 324 
 325         for (int i = methods->length() - 1; i >= 0; i--) {
 326           methodHandle method = methods->at(i);
 327           if (method->name() == m_name && method->signature() == m_signature) {
 328             RC_TRACE(0x00000800, ("%sing breakpoint in %s(%s)",
 329               meth_act == &methodOopDesc::set_breakpoint ? "sett" : "clear",
 330               method->name()->as_C_string(),
 331               method->signature()->as_C_string()));
 332             assert(!method->is_obsolete(), "only EMCP methods here");
 333 
 334             ((methodOopDesc*)method()->*meth_act)(_bci);
 335             break;
 336           }
 337         }
 338       }
 339     } // pvw is cleaned up
 340   } // rm is cleaned up
 341 }
 342 
 343 void JvmtiBreakpoint::set() {
 344   each_method_version_do(&methodOopDesc::set_breakpoint);
 345 }
 346 
 347 void JvmtiBreakpoint::clear() {
 348   each_method_version_do(&methodOopDesc::clear_breakpoint);
 349 }
 350 
 351 void JvmtiBreakpoint::print() {
 352 #ifndef PRODUCT
 353   const char *class_name  = (_method == NULL) ? "NULL" : _method->klass_name()->as_C_string();
 354   const char *method_name = (_method == NULL) ? "NULL" : _method->name()->as_C_string();
 355 
 356   tty->print("Breakpoint(%s,%s,%d,%p)",class_name, method_name, _bci, getBcp());
 357 #endif
 358 }
 359 
 360 
 361 //
 362 // class VM_ChangeBreakpoints
 363 //
 364 // Modify the Breakpoints data structure at a safepoint
 365 //
 366 
 367 void VM_ChangeBreakpoints::doit() {
 368   switch (_operation) {
 369   case SET_BREAKPOINT:
 370     _breakpoints->set_at_safepoint(*_bp);
 371     break;
 372   case CLEAR_BREAKPOINT:
 373     _breakpoints->clear_at_safepoint(*_bp);
 374     break;
 375   default:
 376     assert(false, "Unknown operation");
 377   }
 378 }
 379 
 380 void VM_ChangeBreakpoints::oops_do(OopClosure* f) {
 381   // The JvmtiBreakpoints in _breakpoints will be visited via
 382   // JvmtiExport::oops_do.
 383   if (_bp != NULL) {
 384     _bp->oops_do(f);
 385   }
 386 }
 387 
 388 //
 389 // class JvmtiBreakpoints
 390 //
 391 // a JVMTI internal collection of JvmtiBreakpoint
 392 //
 393 
 394 JvmtiBreakpoints::JvmtiBreakpoints(void listener_fun(void *,address *)) {
 395   _bps.initialize(this,listener_fun);
 396 }
 397 
 398 JvmtiBreakpoints:: ~JvmtiBreakpoints() {}
 399 
 400 void  JvmtiBreakpoints::oops_do(OopClosure* f) {
 401   _bps.oops_do(f);
 402 }
 403 
 404 void JvmtiBreakpoints::gc_epilogue() {
 405   _bps.gc_epilogue();
 406 }
 407 
 408 void  JvmtiBreakpoints::print() {
 409 #ifndef PRODUCT
 410   ResourceMark rm;
 411 
 412   int n = _bps.length();
 413   for (int i=0; i<n; i++) {
 414     JvmtiBreakpoint& bp = _bps.at(i);
 415     tty->print("%d: ", i);
 416     bp.print();
 417     tty->print_cr("");
 418   }
 419 #endif
 420 }
 421 
 422 
 423 void JvmtiBreakpoints::set_at_safepoint(JvmtiBreakpoint& bp) {
 424   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 425 
 426   int i = _bps.find(bp);
 427   if (i == -1) {
 428     _bps.append(bp);
 429     bp.set();
 430   }
 431 }
 432 
 433 void JvmtiBreakpoints::clear_at_safepoint(JvmtiBreakpoint& bp) {
 434   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
 435 
 436   int i = _bps.find(bp);
 437   if (i != -1) {
 438     _bps.remove(i);
 439     bp.clear();
 440   }
 441 }
 442 
 443 int JvmtiBreakpoints::length() { return _bps.length(); }
 444 
 445 int JvmtiBreakpoints::set(JvmtiBreakpoint& bp) {
 446   if ( _bps.find(bp) != -1) {
 447      return JVMTI_ERROR_DUPLICATE;
 448   }
 449   VM_ChangeBreakpoints set_breakpoint(VM_ChangeBreakpoints::SET_BREAKPOINT, &bp);
 450   VMThread::execute(&set_breakpoint);
 451   return JVMTI_ERROR_NONE;
 452 }
 453 
 454 int JvmtiBreakpoints::clear(JvmtiBreakpoint& bp) {
 455   if ( _bps.find(bp) == -1) {
 456      return JVMTI_ERROR_NOT_FOUND;
 457   }
 458 
 459   VM_ChangeBreakpoints clear_breakpoint(VM_ChangeBreakpoints::CLEAR_BREAKPOINT, &bp);
 460   VMThread::execute(&clear_breakpoint);
 461   return JVMTI_ERROR_NONE;
 462 }
 463 
 464 void JvmtiBreakpoints::clearall_in_class_at_safepoint(klassOop klass) {
 465   bool changed = true;
 466   // We are going to run thru the list of bkpts
 467   // and delete some.  This deletion probably alters
 468   // the list in some implementation defined way such
 469   // that when we delete entry i, the next entry might
 470   // no longer be at i+1.  To be safe, each time we delete
 471   // an entry, we'll just start again from the beginning.
 472   // We'll stop when we make a pass thru the whole list without
 473   // deleting anything.
 474   while (changed) {
 475     int len = _bps.length();
 476     changed = false;
 477     for (int i = 0; i < len; i++) {
 478       JvmtiBreakpoint& bp = _bps.at(i);
 479       if (bp.method()->method_holder() == klass) {
 480         bp.clear();
 481         _bps.remove(i);
 482         // This changed 'i' so we have to start over.
 483         changed = true;
 484         break;
 485       }
 486     }
 487   }
 488 }
 489 
 490 //
 491 // class JvmtiCurrentBreakpoints
 492 //
 493 
 494 JvmtiBreakpoints *JvmtiCurrentBreakpoints::_jvmti_breakpoints  = NULL;
 495 address *         JvmtiCurrentBreakpoints::_breakpoint_list    = NULL;
 496 
 497 
 498 JvmtiBreakpoints& JvmtiCurrentBreakpoints::get_jvmti_breakpoints() {
 499   if (_jvmti_breakpoints != NULL) return (*_jvmti_breakpoints);
 500   _jvmti_breakpoints = new JvmtiBreakpoints(listener_fun);
 501   assert(_jvmti_breakpoints != NULL, "_jvmti_breakpoints != NULL");
 502   return (*_jvmti_breakpoints);
 503 }
 504 
 505 void  JvmtiCurrentBreakpoints::listener_fun(void *this_obj, address *cache) {
 506   JvmtiBreakpoints *this_jvmti = (JvmtiBreakpoints *) this_obj;
 507   assert(this_jvmti != NULL, "this_jvmti != NULL");
 508 
 509   debug_only(int n = this_jvmti->length(););
 510   assert(cache[n] == NULL, "cache must be NULL terminated");
 511 
 512   set_breakpoint_list(cache);
 513 }
 514 
 515 
 516 void JvmtiCurrentBreakpoints::oops_do(OopClosure* f) {
 517   if (_jvmti_breakpoints != NULL) {
 518     _jvmti_breakpoints->oops_do(f);
 519   }
 520 }
 521 
 522 void JvmtiCurrentBreakpoints::gc_epilogue() {
 523   if (_jvmti_breakpoints != NULL) {
 524     _jvmti_breakpoints->gc_epilogue();
 525   }
 526 }
 527 
 528 ///////////////////////////////////////////////////////////////
 529 //
 530 // class VM_GetOrSetLocal
 531 //
 532 
 533 // Constructor for non-object getter
 534 VM_GetOrSetLocal::VM_GetOrSetLocal(JavaThread* thread, jint depth, int index, BasicType type)
 535   : _thread(thread)
 536   , _calling_thread(NULL)
 537   , _depth(depth)
 538   , _index(index)
 539   , _type(type)
 540   , _set(false)
 541   , _jvf(NULL)
 542   , _result(JVMTI_ERROR_NONE)
 543 {
 544 }
 545 
 546 // Constructor for object or non-object setter
 547 VM_GetOrSetLocal::VM_GetOrSetLocal(JavaThread* thread, jint depth, int index, BasicType type, jvalue value)
 548   : _thread(thread)
 549   , _calling_thread(NULL)
 550   , _depth(depth)
 551   , _index(index)
 552   , _type(type)
 553   , _value(value)
 554   , _set(true)
 555   , _jvf(NULL)
 556   , _result(JVMTI_ERROR_NONE)
 557 {
 558 }
 559 
 560 // Constructor for object getter
 561 VM_GetOrSetLocal::VM_GetOrSetLocal(JavaThread* thread, JavaThread* calling_thread, jint depth, int index)
 562   : _thread(thread)
 563   , _calling_thread(calling_thread)
 564   , _depth(depth)
 565   , _index(index)
 566   , _type(T_OBJECT)
 567   , _set(false)
 568   , _jvf(NULL)
 569   , _result(JVMTI_ERROR_NONE)
 570 {
 571 }
 572 
 573 vframe *VM_GetOrSetLocal::get_vframe() {
 574   if (!_thread->has_last_Java_frame()) {
 575     return NULL;
 576   }
 577   RegisterMap reg_map(_thread);
 578   vframe *vf = _thread->last_java_vframe(&reg_map);
 579   int d = 0;
 580   while ((vf != NULL) && (d < _depth)) {
 581     vf = vf->java_sender();
 582     d++;
 583   }
 584   return vf;
 585 }
 586 
 587 javaVFrame *VM_GetOrSetLocal::get_java_vframe() {
 588   vframe* vf = get_vframe();
 589   if (vf == NULL) {
 590     _result = JVMTI_ERROR_NO_MORE_FRAMES;
 591     return NULL;
 592   }
 593   javaVFrame *jvf = (javaVFrame*)vf;
 594 
 595   if (!vf->is_java_frame()) {
 596     _result = JVMTI_ERROR_OPAQUE_FRAME;
 597     return NULL;
 598   }
 599   return jvf;
 600 }
 601 
 602 // Check that the klass is assignable to a type with the given signature.
 603 // Another solution could be to use the function Klass::is_subtype_of(type).
 604 // But the type class can be forced to load/initialize eagerly in such a case.
 605 // This may cause unexpected consequences like CFLH or class-init JVMTI events.
 606 // It is better to avoid such a behavior.
 607 bool VM_GetOrSetLocal::is_assignable(const char* ty_sign, Klass* klass, Thread* thread) {
 608   assert(ty_sign != NULL, "type signature must not be NULL");
 609   assert(thread != NULL, "thread must not be NULL");
 610   assert(klass != NULL, "klass must not be NULL");
 611 
 612   int len = (int) strlen(ty_sign);
 613   if (ty_sign[0] == 'L' && ty_sign[len-1] == ';') { // Need pure class/interface name
 614     ty_sign++;
 615     len -= 2;
 616   }
 617   TempNewSymbol ty_sym = SymbolTable::new_symbol(ty_sign, len, thread);
 618   if (klass->name() == ty_sym) {
 619     return true;
 620   }
 621   // Compare primary supers
 622   int super_depth = klass->super_depth();
 623   int idx;
 624   for (idx = 0; idx < super_depth; idx++) {
 625     if (Klass::cast(klass->primary_super_of_depth(idx))->name() == ty_sym) {
 626       return true;
 627     }
 628   }
 629   // Compare secondary supers
 630   objArrayOop sec_supers = klass->secondary_supers();
 631   for (idx = 0; idx < sec_supers->length(); idx++) {
 632     if (Klass::cast((klassOop) sec_supers->obj_at(idx))->name() == ty_sym) {
 633       return true;
 634     }
 635   }
 636   return false;
 637 }
 638 
 639 // Checks error conditions:
 640 //   JVMTI_ERROR_INVALID_SLOT
 641 //   JVMTI_ERROR_TYPE_MISMATCH
 642 // Returns: 'true' - everything is Ok, 'false' - error code
 643 
 644 bool VM_GetOrSetLocal::check_slot_type(javaVFrame* jvf) {
 645   methodOop method_oop = jvf->method();
 646   if (!method_oop->has_localvariable_table()) {
 647     // Just to check index boundaries
 648     jint extra_slot = (_type == T_LONG || _type == T_DOUBLE) ? 1 : 0;
 649     if (_index < 0 || _index + extra_slot >= method_oop->max_locals()) {
 650       _result = JVMTI_ERROR_INVALID_SLOT;
 651       return false;
 652     }
 653     return true;
 654   }
 655 
 656   jint num_entries = method_oop->localvariable_table_length();
 657   if (num_entries == 0) {
 658     _result = JVMTI_ERROR_INVALID_SLOT;
 659     return false;       // There are no slots
 660   }
 661   int signature_idx = -1;
 662   int vf_bci = jvf->bci();
 663   LocalVariableTableElement* table = method_oop->localvariable_table_start();
 664   for (int i = 0; i < num_entries; i++) {
 665     int start_bci = table[i].start_bci;
 666     int end_bci = start_bci + table[i].length;
 667 
 668     // Here we assume that locations of LVT entries
 669     // with the same slot number cannot be overlapped
 670     if (_index == (jint) table[i].slot && start_bci <= vf_bci && vf_bci <= end_bci) {
 671       signature_idx = (int) table[i].descriptor_cp_index;
 672       break;
 673     }
 674   }
 675   if (signature_idx == -1) {
 676     _result = JVMTI_ERROR_INVALID_SLOT;
 677     return false;       // Incorrect slot index
 678   }
 679   Symbol*   sign_sym  = method_oop->constants()->symbol_at(signature_idx);
 680   const char* signature = (const char *) sign_sym->as_utf8();
 681   BasicType slot_type = char2type(signature[0]);
 682 
 683   switch (slot_type) {
 684   case T_BYTE:
 685   case T_SHORT:
 686   case T_CHAR:
 687   case T_BOOLEAN:
 688     slot_type = T_INT;
 689     break;
 690   case T_ARRAY:
 691     slot_type = T_OBJECT;
 692     break;
 693   };
 694   if (_type != slot_type) {
 695     _result = JVMTI_ERROR_TYPE_MISMATCH;
 696     return false;
 697   }
 698 
 699   jobject jobj = _value.l;
 700   if (_set && slot_type == T_OBJECT && jobj != NULL) { // NULL reference is allowed
 701     // Check that the jobject class matches the return type signature.
 702     JavaThread* cur_thread = JavaThread::current();
 703     HandleMark hm(cur_thread);
 704 
 705     Handle obj = Handle(cur_thread, JNIHandles::resolve_external_guard(jobj));
 706     NULL_CHECK(obj, (_result = JVMTI_ERROR_INVALID_OBJECT, false));
 707     KlassHandle ob_kh = KlassHandle(cur_thread, obj->klass());
 708     NULL_CHECK(ob_kh, (_result = JVMTI_ERROR_INVALID_OBJECT, false));
 709 
 710     if (!is_assignable(signature, Klass::cast(ob_kh()), cur_thread)) {
 711       _result = JVMTI_ERROR_TYPE_MISMATCH;
 712       return false;
 713     }
 714   }
 715   return true;
 716 }
 717 
 718 static bool can_be_deoptimized(vframe* vf) {
 719   return (vf->is_compiled_frame() && vf->fr().can_be_deoptimized());
 720 }
 721 
 722 bool VM_GetOrSetLocal::doit_prologue() {
 723   _jvf = get_java_vframe();
 724   NULL_CHECK(_jvf, false);
 725 
 726   if (_jvf->method()->is_native()) {
 727     if (getting_receiver() && !_jvf->method()->is_static()) {
 728       return true;
 729     } else {
 730       _result = JVMTI_ERROR_OPAQUE_FRAME;
 731       return false;
 732     }
 733   }
 734 
 735   if (!check_slot_type(_jvf)) {
 736     return false;
 737   }
 738   return true;
 739 }
 740 
 741 void VM_GetOrSetLocal::doit() {
 742   if (_set) {
 743     // Force deoptimization of frame if compiled because it's
 744     // possible the compiler emitted some locals as constant values,
 745     // meaning they are not mutable.
 746     if (can_be_deoptimized(_jvf)) {
 747 
 748       // Schedule deoptimization so that eventually the local
 749       // update will be written to an interpreter frame.
 750       Deoptimization::deoptimize_frame(_jvf->thread(), _jvf->fr().id());
 751 
 752       // Now store a new value for the local which will be applied
 753       // once deoptimization occurs. Note however that while this
 754       // write is deferred until deoptimization actually happens
 755       // can vframe created after this point will have its locals
 756       // reflecting this update so as far as anyone can see the
 757       // write has already taken place.
 758 
 759       // If we are updating an oop then get the oop from the handle
 760       // since the handle will be long gone by the time the deopt
 761       // happens. The oop stored in the deferred local will be
 762       // gc'd on its own.
 763       if (_type == T_OBJECT) {
 764         _value.l = (jobject) (JNIHandles::resolve_external_guard(_value.l));
 765       }
 766       // Re-read the vframe so we can see that it is deoptimized
 767       // [ Only need because of assert in update_local() ]
 768       _jvf = get_java_vframe();
 769       ((compiledVFrame*)_jvf)->update_local(_type, _index, _value);
 770       return;
 771     }
 772     StackValueCollection *locals = _jvf->locals();
 773     HandleMark hm;
 774 
 775     switch (_type) {
 776       case T_INT:    locals->set_int_at   (_index, _value.i); break;
 777       case T_LONG:   locals->set_long_at  (_index, _value.j); break;
 778       case T_FLOAT:  locals->set_float_at (_index, _value.f); break;
 779       case T_DOUBLE: locals->set_double_at(_index, _value.d); break;
 780       case T_OBJECT: {
 781         Handle ob_h(JNIHandles::resolve_external_guard(_value.l));
 782         locals->set_obj_at (_index, ob_h);
 783         break;
 784       }
 785       default: ShouldNotReachHere();
 786     }
 787     _jvf->set_locals(locals);
 788   } else {
 789     if (_jvf->method()->is_native() && _jvf->is_compiled_frame()) {
 790       assert(getting_receiver(), "Can only get here when getting receiver");
 791       oop receiver = _jvf->fr().get_native_receiver();
 792       _value.l = JNIHandles::make_local(_calling_thread, receiver);
 793     } else {
 794       StackValueCollection *locals = _jvf->locals();
 795 
 796       if (locals->at(_index)->type() == T_CONFLICT) {
 797         memset(&_value, 0, sizeof(_value));
 798         _value.l = NULL;
 799         return;
 800       }
 801 
 802       switch (_type) {
 803         case T_INT:    _value.i = locals->int_at   (_index);   break;
 804         case T_LONG:   _value.j = locals->long_at  (_index);   break;
 805         case T_FLOAT:  _value.f = locals->float_at (_index);   break;
 806         case T_DOUBLE: _value.d = locals->double_at(_index);   break;
 807         case T_OBJECT: {
 808           // Wrap the oop to be returned in a local JNI handle since
 809           // oops_do() no longer applies after doit() is finished.
 810           oop obj = locals->obj_at(_index)();
 811           _value.l = JNIHandles::make_local(_calling_thread, obj);
 812           break;
 813         }
 814         default: ShouldNotReachHere();
 815       }
 816     }
 817   }
 818 }
 819 
 820 
 821 bool VM_GetOrSetLocal::allow_nested_vm_operations() const {
 822   return true; // May need to deoptimize
 823 }
 824 
 825 
 826 VM_GetReceiver::VM_GetReceiver(
 827     JavaThread* thread, JavaThread* caller_thread, jint depth)
 828     : VM_GetOrSetLocal(thread, caller_thread, depth, 0) {}
 829 
 830 /////////////////////////////////////////////////////////////////////////////////////////
 831 
 832 //
 833 // class JvmtiSuspendControl - see comments in jvmtiImpl.hpp
 834 //
 835 
 836 bool JvmtiSuspendControl::suspend(JavaThread *java_thread) {
 837   // external suspend should have caught suspending a thread twice
 838 
 839   // Immediate suspension required for JPDA back-end so JVMTI agent threads do
 840   // not deadlock due to later suspension on transitions while holding
 841   // raw monitors.  Passing true causes the immediate suspension.
 842   // java_suspend() will catch threads in the process of exiting
 843   // and will ignore them.
 844   java_thread->java_suspend();
 845 
 846   // It would be nice to have the following assertion in all the time,
 847   // but it is possible for a racing resume request to have resumed
 848   // this thread right after we suspended it. Temporarily enable this
 849   // assertion if you are chasing a different kind of bug.
 850   //
 851   // assert(java_lang_Thread::thread(java_thread->threadObj()) == NULL ||
 852   //   java_thread->is_being_ext_suspended(), "thread is not suspended");
 853 
 854   if (java_lang_Thread::thread(java_thread->threadObj()) == NULL) {
 855     // check again because we can get delayed in java_suspend():
 856     // the thread is in process of exiting.
 857     return false;
 858   }
 859 
 860   return true;
 861 }
 862 
 863 bool JvmtiSuspendControl::resume(JavaThread *java_thread) {
 864   // external suspend should have caught resuming a thread twice
 865   assert(java_thread->is_being_ext_suspended(), "thread should be suspended");
 866 
 867   // resume thread
 868   {
 869     // must always grab Threads_lock, see JVM_SuspendThread
 870     MutexLocker ml(Threads_lock);
 871     java_thread->java_resume();
 872   }
 873 
 874   return true;
 875 }
 876 
 877 
 878 void JvmtiSuspendControl::print() {
 879 #ifndef PRODUCT
 880   MutexLocker mu(Threads_lock);
 881   ResourceMark rm;
 882 
 883   tty->print("Suspended Threads: [");
 884   for (JavaThread *thread = Threads::first(); thread != NULL; thread = thread->next()) {
 885 #if JVMTI_TRACE
 886     const char *name   = JvmtiTrace::safe_get_thread_name(thread);
 887 #else
 888     const char *name   = "";
 889 #endif /*JVMTI_TRACE */
 890     tty->print("%s(%c ", name, thread->is_being_ext_suspended() ? 'S' : '_');
 891     if (!thread->has_last_Java_frame()) {
 892       tty->print("no stack");
 893     }
 894     tty->print(") ");
 895   }
 896   tty->print_cr("]");
 897 #endif
 898 }
 899 
 900 JvmtiDeferredEvent JvmtiDeferredEvent::compiled_method_load_event(
 901     nmethod* nm) {
 902   JvmtiDeferredEvent event = JvmtiDeferredEvent(TYPE_COMPILED_METHOD_LOAD);
 903   event._event_data.compiled_method_load = nm;
 904   // Keep the nmethod alive until the ServiceThread can process
 905   // this deferred event.
 906   nmethodLocker::lock_nmethod(nm);
 907   return event;
 908 }
 909 
 910 JvmtiDeferredEvent JvmtiDeferredEvent::compiled_method_unload_event(
 911     nmethod* nm, jmethodID id, const void* code) {
 912   JvmtiDeferredEvent event = JvmtiDeferredEvent(TYPE_COMPILED_METHOD_UNLOAD);
 913   event._event_data.compiled_method_unload.nm = nm;
 914   event._event_data.compiled_method_unload.method_id = id;
 915   event._event_data.compiled_method_unload.code_begin = code;
 916   // Keep the nmethod alive until the ServiceThread can process
 917   // this deferred event. This will keep the memory for the
 918   // generated code from being reused too early. We pass
 919   // zombie_ok == true here so that our nmethod that was just
 920   // made into a zombie can be locked.
 921   nmethodLocker::lock_nmethod(nm, true /* zombie_ok */);
 922   return event;
 923 }
 924 
 925 JvmtiDeferredEvent JvmtiDeferredEvent::dynamic_code_generated_event(
 926       const char* name, const void* code_begin, const void* code_end) {
 927   JvmtiDeferredEvent event = JvmtiDeferredEvent(TYPE_DYNAMIC_CODE_GENERATED);
 928   // Need to make a copy of the name since we don't know how long
 929   // the event poster will keep it around after we enqueue the
 930   // deferred event and return. strdup() failure is handled in
 931   // the post() routine below.
 932   event._event_data.dynamic_code_generated.name = os::strdup(name);
 933   event._event_data.dynamic_code_generated.code_begin = code_begin;
 934   event._event_data.dynamic_code_generated.code_end = code_end;
 935   return event;
 936 }
 937 
 938 void JvmtiDeferredEvent::post() {
 939   assert(ServiceThread::is_service_thread(Thread::current()),
 940          "Service thread must post enqueued events");
 941   switch(_type) {
 942     case TYPE_COMPILED_METHOD_LOAD: {
 943       nmethod* nm = _event_data.compiled_method_load;
 944       JvmtiExport::post_compiled_method_load(nm);
 945       // done with the deferred event so unlock the nmethod
 946       nmethodLocker::unlock_nmethod(nm);
 947       break;
 948     }
 949     case TYPE_COMPILED_METHOD_UNLOAD: {
 950       nmethod* nm = _event_data.compiled_method_unload.nm;
 951       JvmtiExport::post_compiled_method_unload(
 952         _event_data.compiled_method_unload.method_id,
 953         _event_data.compiled_method_unload.code_begin);
 954       // done with the deferred event so unlock the nmethod
 955       nmethodLocker::unlock_nmethod(nm);
 956       break;
 957     }
 958     case TYPE_DYNAMIC_CODE_GENERATED: {
 959       JvmtiExport::post_dynamic_code_generated_internal(
 960         // if strdup failed give the event a default name
 961         (_event_data.dynamic_code_generated.name == NULL)
 962           ? "unknown_code" : _event_data.dynamic_code_generated.name,
 963         _event_data.dynamic_code_generated.code_begin,
 964         _event_data.dynamic_code_generated.code_end);
 965       if (_event_data.dynamic_code_generated.name != NULL) {
 966         // release our copy
 967         os::free((void *)_event_data.dynamic_code_generated.name);
 968       }
 969       break;
 970     }
 971     default:
 972       ShouldNotReachHere();
 973   }
 974 }
 975 
 976 JvmtiDeferredEventQueue::QueueNode* JvmtiDeferredEventQueue::_queue_tail = NULL;
 977 JvmtiDeferredEventQueue::QueueNode* JvmtiDeferredEventQueue::_queue_head = NULL;
 978 
 979 volatile JvmtiDeferredEventQueue::QueueNode*
 980     JvmtiDeferredEventQueue::_pending_list = NULL;
 981 
 982 bool JvmtiDeferredEventQueue::has_events() {
 983   assert(Service_lock->owned_by_self(), "Must own Service_lock");
 984   return _queue_head != NULL || _pending_list != NULL;
 985 }
 986 
 987 void JvmtiDeferredEventQueue::enqueue(const JvmtiDeferredEvent& event) {
 988   assert(Service_lock->owned_by_self(), "Must own Service_lock");
 989 
 990   process_pending_events();
 991 
 992   // Events get added to the end of the queue (and are pulled off the front).
 993   QueueNode* node = new QueueNode(event);
 994   if (_queue_tail == NULL) {
 995     _queue_tail = _queue_head = node;
 996   } else {
 997     assert(_queue_tail->next() == NULL, "Must be the last element in the list");
 998     _queue_tail->set_next(node);
 999     _queue_tail = node;
1000   }
1001 
1002   Service_lock->notify_all();
1003   assert((_queue_head == NULL) == (_queue_tail == NULL),
1004          "Inconsistent queue markers");
1005 }
1006 
1007 JvmtiDeferredEvent JvmtiDeferredEventQueue::dequeue() {
1008   assert(Service_lock->owned_by_self(), "Must own Service_lock");
1009 
1010   process_pending_events();
1011 
1012   assert(_queue_head != NULL, "Nothing to dequeue");
1013 
1014   if (_queue_head == NULL) {
1015     // Just in case this happens in product; it shouldn't but let's not crash
1016     return JvmtiDeferredEvent();
1017   }
1018 
1019   QueueNode* node = _queue_head;
1020   _queue_head = _queue_head->next();
1021   if (_queue_head == NULL) {
1022     _queue_tail = NULL;
1023   }
1024 
1025   assert((_queue_head == NULL) == (_queue_tail == NULL),
1026          "Inconsistent queue markers");
1027 
1028   JvmtiDeferredEvent event = node->event();
1029   delete node;
1030   return event;
1031 }
1032 
1033 void JvmtiDeferredEventQueue::add_pending_event(
1034     const JvmtiDeferredEvent& event) {
1035 
1036   QueueNode* node = new QueueNode(event);
1037 
1038   bool success = false;
1039   QueueNode* prev_value = (QueueNode*)_pending_list;
1040   do {
1041     node->set_next(prev_value);
1042     prev_value = (QueueNode*)Atomic::cmpxchg_ptr(
1043         (void*)node, (volatile void*)&_pending_list, (void*)node->next());
1044   } while (prev_value != node->next());
1045 }
1046 
1047 // This method transfers any events that were added by someone NOT holding
1048 // the lock into the mainline queue.
1049 void JvmtiDeferredEventQueue::process_pending_events() {
1050   assert(Service_lock->owned_by_self(), "Must own Service_lock");
1051 
1052   if (_pending_list != NULL) {
1053     QueueNode* head =
1054         (QueueNode*)Atomic::xchg_ptr(NULL, (volatile void*)&_pending_list);
1055 
1056     assert((_queue_head == NULL) == (_queue_tail == NULL),
1057            "Inconsistent queue markers");
1058 
1059     if (head != NULL) {
1060       // Since we've treated the pending list as a stack (with newer
1061       // events at the beginning), we need to join the bottom of the stack
1062       // with the 'tail' of the queue in order to get the events in the
1063       // right order.  We do this by reversing the pending list and appending
1064       // it to the queue.
1065 
1066       QueueNode* new_tail = head;
1067       QueueNode* new_head = NULL;
1068 
1069       // This reverses the list
1070       QueueNode* prev = new_tail;
1071       QueueNode* node = new_tail->next();
1072       new_tail->set_next(NULL);
1073       while (node != NULL) {
1074         QueueNode* next = node->next();
1075         node->set_next(prev);
1076         prev = node;
1077         node = next;
1078       }
1079       new_head = prev;
1080 
1081       // Now append the new list to the queue
1082       if (_queue_tail != NULL) {
1083         _queue_tail->set_next(new_head);
1084       } else { // _queue_head == NULL
1085         _queue_head = new_head;
1086       }
1087       _queue_tail = new_tail;
1088     }
1089   }
1090 }