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