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