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/classLoaderDataGraph.hpp"
  27 #include "classfile/moduleEntry.hpp"
  28 #include "classfile/systemDictionary.hpp"
  29 #include "jvmtifiles/jvmtiEnv.hpp"
  30 #include "memory/resourceArea.hpp"
  31 #include "oops/objArrayKlass.hpp"
  32 #include "oops/objArrayOop.hpp"
  33 #include "oops/oop.inline.hpp"
  34 #include "oops/oopHandle.inline.hpp"
  35 #include "prims/jvmtiEnvBase.hpp"
  36 #include "prims/jvmtiEventController.inline.hpp"
  37 #include "prims/jvmtiExtensions.hpp"
  38 #include "prims/jvmtiImpl.hpp"
  39 #include "prims/jvmtiManageCapabilities.hpp"
  40 #include "prims/jvmtiTagMap.hpp"
  41 #include "prims/jvmtiThreadState.inline.hpp"
  42 #include "runtime/biasedLocking.hpp"
  43 #include "runtime/deoptimization.hpp"
  44 #include "runtime/frame.inline.hpp"
  45 #include "runtime/handles.inline.hpp"
  46 #include "runtime/interfaceSupport.inline.hpp"
  47 #include "runtime/jfieldIDWorkaround.hpp"
  48 #include "runtime/jniHandles.inline.hpp"
  49 #include "runtime/objectMonitor.hpp"
  50 #include "runtime/objectMonitor.inline.hpp"
  51 #include "runtime/signature.hpp"
  52 #include "runtime/thread.inline.hpp"
  53 #include "runtime/threadSMR.hpp"
  54 #include "runtime/vframe.hpp"
  55 #include "runtime/vframe_hp.hpp"
  56 #include "runtime/vmThread.hpp"
  57 #include "runtime/vmOperations.hpp"
  58 
  59 ///////////////////////////////////////////////////////////////
  60 //
  61 // JvmtiEnvBase
  62 //
  63 
  64 JvmtiEnvBase* JvmtiEnvBase::_head_environment = NULL;
  65 
  66 bool JvmtiEnvBase::_globally_initialized = false;
  67 volatile bool JvmtiEnvBase::_needs_clean_up = false;
  68 
  69 jvmtiPhase JvmtiEnvBase::_phase = JVMTI_PHASE_PRIMORDIAL;
  70 
  71 volatile int JvmtiEnvBase::_dying_thread_env_iteration_count = 0;
  72 
  73 extern jvmtiInterface_1_ jvmti_Interface;
  74 extern jvmtiInterface_1_ jvmtiTrace_Interface;
  75 
  76 
  77 // perform initializations that must occur before any JVMTI environments
  78 // are released but which should only be initialized once (no matter
  79 // how many environments are created).
  80 void
  81 JvmtiEnvBase::globally_initialize() {
  82   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
  83   assert(_globally_initialized == false, "bad call");
  84 
  85   JvmtiManageCapabilities::initialize();
  86 
  87   // register extension functions and events
  88   JvmtiExtensions::register_extensions();
  89 
  90 #ifdef JVMTI_TRACE
  91   JvmtiTrace::initialize();
  92 #endif
  93 
  94   _globally_initialized = true;
  95 }
  96 
  97 
  98 void
  99 JvmtiEnvBase::initialize() {
 100   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
 101 
 102   // Add this environment to the end of the environment list (order is important)
 103   {
 104     // This block of code must not contain any safepoints, as list deallocation
 105     // (which occurs at a safepoint) cannot occur simultaneously with this list
 106     // addition.  Note: NoSafepointVerifier cannot, currently, be used before
 107     // threads exist.
 108     JvmtiEnvIterator it;
 109     JvmtiEnvBase *previous_env = NULL;
 110     for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
 111       previous_env = env;
 112     }
 113     if (previous_env == NULL) {
 114       _head_environment = this;
 115     } else {
 116       previous_env->set_next_environment(this);
 117     }
 118   }
 119 
 120   if (_globally_initialized == false) {
 121     globally_initialize();
 122   }
 123 }
 124 
 125 jvmtiPhase
 126 JvmtiEnvBase::phase() {
 127   // For the JVMTI environments possessed the can_generate_early_vmstart:
 128   //   replace JVMTI_PHASE_PRIMORDIAL with JVMTI_PHASE_START
 129   if (_phase == JVMTI_PHASE_PRIMORDIAL &&
 130       JvmtiExport::early_vmstart_recorded() &&
 131       early_vmstart_env()) {
 132     return JVMTI_PHASE_START;
 133   }
 134   return _phase; // Normal case
 135 }
 136 
 137 bool
 138 JvmtiEnvBase::is_valid() {
 139   jint value = 0;
 140 
 141   // This object might not be a JvmtiEnvBase so we can't assume
 142   // the _magic field is properly aligned. Get the value in a safe
 143   // way and then check against JVMTI_MAGIC.
 144 
 145   switch (sizeof(_magic)) {
 146   case 2:
 147     value = Bytes::get_native_u2((address)&_magic);
 148     break;
 149 
 150   case 4:
 151     value = Bytes::get_native_u4((address)&_magic);
 152     break;
 153 
 154   case 8:
 155     value = Bytes::get_native_u8((address)&_magic);
 156     break;
 157 
 158   default:
 159     guarantee(false, "_magic field is an unexpected size");
 160   }
 161 
 162   return value == JVMTI_MAGIC;
 163 }
 164 
 165 
 166 bool
 167 JvmtiEnvBase::use_version_1_0_semantics() {
 168   int major, minor, micro;
 169 
 170   JvmtiExport::decode_version_values(_version, &major, &minor, &micro);
 171   return major == 1 && minor == 0;  // micro version doesn't matter here
 172 }
 173 
 174 
 175 bool
 176 JvmtiEnvBase::use_version_1_1_semantics() {
 177   int major, minor, micro;
 178 
 179   JvmtiExport::decode_version_values(_version, &major, &minor, &micro);
 180   return major == 1 && minor == 1;  // micro version doesn't matter here
 181 }
 182 
 183 bool
 184 JvmtiEnvBase::use_version_1_2_semantics() {
 185   int major, minor, micro;
 186 
 187   JvmtiExport::decode_version_values(_version, &major, &minor, &micro);
 188   return major == 1 && minor == 2;  // micro version doesn't matter here
 189 }
 190 
 191 
 192 JvmtiEnvBase::JvmtiEnvBase(jint version) : _env_event_enable() {
 193   _version = version;
 194   _env_local_storage = NULL;
 195   _tag_map = NULL;
 196   _native_method_prefix_count = 0;
 197   _native_method_prefixes = NULL;
 198   _next = NULL;
 199   _class_file_load_hook_ever_enabled = false;
 200 
 201   // Moot since ClassFileLoadHook not yet enabled.
 202   // But "true" will give a more predictable ClassFileLoadHook behavior
 203   // for environment creation during ClassFileLoadHook.
 204   _is_retransformable = true;
 205 
 206   // all callbacks initially NULL
 207   memset(&_event_callbacks,0,sizeof(jvmtiEventCallbacks));
 208 
 209   // all capabilities initially off
 210   memset(&_current_capabilities, 0, sizeof(_current_capabilities));
 211 
 212   // all prohibited capabilities initially off
 213   memset(&_prohibited_capabilities, 0, sizeof(_prohibited_capabilities));
 214 
 215   _magic = JVMTI_MAGIC;
 216 
 217   JvmtiEventController::env_initialize((JvmtiEnv*)this);
 218 
 219 #ifdef JVMTI_TRACE
 220   _jvmti_external.functions = TraceJVMTI != NULL ? &jvmtiTrace_Interface : &jvmti_Interface;
 221 #else
 222   _jvmti_external.functions = &jvmti_Interface;
 223 #endif
 224 }
 225 
 226 
 227 void
 228 JvmtiEnvBase::dispose() {
 229 
 230 #ifdef JVMTI_TRACE
 231   JvmtiTrace::shutdown();
 232 #endif
 233 
 234   // Dispose of event info and let the event controller call us back
 235   // in a locked state (env_dispose, below)
 236   JvmtiEventController::env_dispose(this);
 237 }
 238 
 239 void
 240 JvmtiEnvBase::env_dispose() {
 241   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
 242 
 243   // We have been entered with all events disabled on this environment.
 244   // A race to re-enable events (by setting callbacks) is prevented by
 245   // checking for a valid environment when setting callbacks (while
 246   // holding the JvmtiThreadState_lock).
 247 
 248   // Mark as invalid.
 249   _magic = DISPOSED_MAGIC;
 250 
 251   // Relinquish all capabilities.
 252   jvmtiCapabilities *caps = get_capabilities();
 253   JvmtiManageCapabilities::relinquish_capabilities(caps, caps, caps);
 254 
 255   // Same situation as with events (see above)
 256   set_native_method_prefixes(0, NULL);
 257 
 258   JvmtiTagMap* tag_map_to_deallocate = _tag_map;
 259   set_tag_map(NULL);
 260   // A tag map can be big, deallocate it now
 261   if (tag_map_to_deallocate != NULL) {
 262     delete tag_map_to_deallocate;
 263   }
 264 
 265   _needs_clean_up = true;
 266 }
 267 
 268 
 269 JvmtiEnvBase::~JvmtiEnvBase() {
 270   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
 271 
 272   // There is a small window of time during which the tag map of a
 273   // disposed environment could have been reallocated.
 274   // Make sure it is gone.
 275   JvmtiTagMap* tag_map_to_deallocate = _tag_map;
 276   set_tag_map(NULL);
 277   // A tag map can be big, deallocate it now
 278   if (tag_map_to_deallocate != NULL) {
 279     delete tag_map_to_deallocate;
 280   }
 281 
 282   _magic = BAD_MAGIC;
 283 }
 284 
 285 
 286 void
 287 JvmtiEnvBase::periodic_clean_up() {
 288   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
 289 
 290   // JvmtiEnvBase reference is saved in JvmtiEnvThreadState. So
 291   // clean up JvmtiThreadState before deleting JvmtiEnv pointer.
 292   JvmtiThreadState::periodic_clean_up();
 293 
 294   // Unlink all invalid environments from the list of environments
 295   // and deallocate them
 296   JvmtiEnvIterator it;
 297   JvmtiEnvBase* previous_env = NULL;
 298   JvmtiEnvBase* env = it.first();
 299   while (env != NULL) {
 300     if (env->is_valid()) {
 301       previous_env = env;
 302       env = it.next(env);
 303     } else {
 304       // This one isn't valid, remove it from the list and deallocate it
 305       JvmtiEnvBase* defunct_env = env;
 306       env = it.next(env);
 307       if (previous_env == NULL) {
 308         _head_environment = env;
 309       } else {
 310         previous_env->set_next_environment(env);
 311       }
 312       delete defunct_env;
 313     }
 314   }
 315 
 316 }
 317 
 318 
 319 void
 320 JvmtiEnvBase::check_for_periodic_clean_up() {
 321   assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
 322 
 323   class ThreadInsideIterationClosure: public ThreadClosure {
 324    private:
 325     bool _inside;
 326    public:
 327     ThreadInsideIterationClosure() : _inside(false) {};
 328 
 329     void do_thread(Thread* thread) {
 330       _inside |= thread->is_inside_jvmti_env_iteration();
 331     }
 332 
 333     bool is_inside_jvmti_env_iteration() {
 334       return _inside;
 335     }
 336   };
 337 
 338   if (_needs_clean_up) {
 339     // Check if we are currently iterating environment,
 340     // deallocation should not occur if we are
 341     ThreadInsideIterationClosure tiic;
 342     Threads::threads_do(&tiic);
 343     if (!tiic.is_inside_jvmti_env_iteration() &&
 344              !is_inside_dying_thread_env_iteration()) {
 345       _needs_clean_up = false;
 346       JvmtiEnvBase::periodic_clean_up();
 347     }
 348   }
 349 }
 350 
 351 
 352 void
 353 JvmtiEnvBase::record_first_time_class_file_load_hook_enabled() {
 354   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),
 355          "sanity check");
 356 
 357   if (!_class_file_load_hook_ever_enabled) {
 358     _class_file_load_hook_ever_enabled = true;
 359 
 360     if (get_capabilities()->can_retransform_classes) {
 361       _is_retransformable = true;
 362     } else {
 363       _is_retransformable = false;
 364 
 365       // cannot add retransform capability after ClassFileLoadHook has been enabled
 366       get_prohibited_capabilities()->can_retransform_classes = 1;
 367     }
 368   }
 369 }
 370 
 371 
 372 void
 373 JvmtiEnvBase::record_class_file_load_hook_enabled() {
 374   if (!_class_file_load_hook_ever_enabled) {
 375     if (Threads::number_of_threads() == 0) {
 376       record_first_time_class_file_load_hook_enabled();
 377     } else {
 378       MutexLocker mu(JvmtiThreadState_lock);
 379       record_first_time_class_file_load_hook_enabled();
 380     }
 381   }
 382 }
 383 
 384 
 385 jvmtiError
 386 JvmtiEnvBase::set_native_method_prefixes(jint prefix_count, char** prefixes) {
 387   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(),
 388          "sanity check");
 389 
 390   int old_prefix_count = get_native_method_prefix_count();
 391   char **old_prefixes = get_native_method_prefixes();
 392 
 393   // allocate and install the new prefixex
 394   if (prefix_count == 0 || !is_valid()) {
 395     _native_method_prefix_count = 0;
 396     _native_method_prefixes = NULL;
 397   } else {
 398     // there are prefixes, allocate an array to hold them, and fill it
 399     char** new_prefixes = (char**)os::malloc((prefix_count) * sizeof(char*), mtInternal);
 400     if (new_prefixes == NULL) {
 401       return JVMTI_ERROR_OUT_OF_MEMORY;
 402     }
 403     for (int i = 0; i < prefix_count; i++) {
 404       char* prefix = prefixes[i];
 405       if (prefix == NULL) {
 406         for (int j = 0; j < (i-1); j++) {
 407           os::free(new_prefixes[j]);
 408         }
 409         os::free(new_prefixes);
 410         return JVMTI_ERROR_NULL_POINTER;
 411       }
 412       prefix = os::strdup(prefixes[i]);
 413       if (prefix == NULL) {
 414         for (int j = 0; j < (i-1); j++) {
 415           os::free(new_prefixes[j]);
 416         }
 417         os::free(new_prefixes);
 418         return JVMTI_ERROR_OUT_OF_MEMORY;
 419       }
 420       new_prefixes[i] = prefix;
 421     }
 422     _native_method_prefix_count = prefix_count;
 423     _native_method_prefixes = new_prefixes;
 424   }
 425 
 426   // now that we know the new prefixes have been successfully installed we can
 427   // safely remove the old ones
 428   if (old_prefix_count != 0) {
 429     for (int i = 0; i < old_prefix_count; i++) {
 430       os::free(old_prefixes[i]);
 431     }
 432     os::free(old_prefixes);
 433   }
 434 
 435   return JVMTI_ERROR_NONE;
 436 }
 437 
 438 
 439 // Collect all the prefixes which have been set in any JVM TI environments
 440 // by the SetNativeMethodPrefix(es) functions.  Be sure to maintain the
 441 // order of environments and the order of prefixes within each environment.
 442 // Return in a resource allocated array.
 443 char**
 444 JvmtiEnvBase::get_all_native_method_prefixes(int* count_ptr) {
 445   assert(Threads::number_of_threads() == 0 ||
 446          SafepointSynchronize::is_at_safepoint() ||
 447          JvmtiThreadState_lock->is_locked(),
 448          "sanity check");
 449 
 450   int total_count = 0;
 451   GrowableArray<char*>* prefix_array =new GrowableArray<char*>(5);
 452 
 453   JvmtiEnvIterator it;
 454   for (JvmtiEnvBase* env = it.first(); env != NULL; env = it.next(env)) {
 455     int prefix_count = env->get_native_method_prefix_count();
 456     char** prefixes = env->get_native_method_prefixes();
 457     for (int j = 0; j < prefix_count; j++) {
 458       // retrieve a prefix and so that it is safe against asynchronous changes
 459       // copy it into the resource area
 460       char* prefix = prefixes[j];
 461       char* prefix_copy = NEW_RESOURCE_ARRAY(char, strlen(prefix)+1);
 462       strcpy(prefix_copy, prefix);
 463       prefix_array->at_put_grow(total_count++, prefix_copy);
 464     }
 465   }
 466 
 467   char** all_prefixes = NEW_RESOURCE_ARRAY(char*, total_count);
 468   char** p = all_prefixes;
 469   for (int i = 0; i < total_count; ++i) {
 470     *p++ = prefix_array->at(i);
 471   }
 472   *count_ptr = total_count;
 473   return all_prefixes;
 474 }
 475 
 476 void
 477 JvmtiEnvBase::set_event_callbacks(const jvmtiEventCallbacks* callbacks,
 478                                                jint size_of_callbacks) {
 479   assert(Threads::number_of_threads() == 0 || JvmtiThreadState_lock->is_locked(), "sanity check");
 480 
 481   size_t byte_cnt = sizeof(jvmtiEventCallbacks);
 482 
 483   // clear in either case to be sure we got any gap between sizes
 484   memset(&_event_callbacks, 0, byte_cnt);
 485 
 486   // Now that JvmtiThreadState_lock is held, prevent a possible race condition where events
 487   // are re-enabled by a call to set event callbacks where the DisposeEnvironment
 488   // occurs after the boiler-plate environment check and before the lock is acquired.
 489   if (callbacks != NULL && is_valid()) {
 490     if (size_of_callbacks < (jint)byte_cnt) {
 491       byte_cnt = size_of_callbacks;
 492     }
 493     memcpy(&_event_callbacks, callbacks, byte_cnt);
 494   }
 495 }
 496 
 497 
 498 // In the fullness of time, all users of the method should instead
 499 // directly use allocate, besides being cleaner and faster, this will
 500 // mean much better out of memory handling
 501 unsigned char *
 502 JvmtiEnvBase::jvmtiMalloc(jlong size) {
 503   unsigned char* mem = NULL;
 504   jvmtiError result = allocate(size, &mem);
 505   assert(result == JVMTI_ERROR_NONE, "Allocate failed");
 506   return mem;
 507 }
 508 
 509 
 510 // Handle management
 511 
 512 jobject JvmtiEnvBase::jni_reference(Handle hndl) {
 513   return JNIHandles::make_local(hndl());
 514 }
 515 
 516 jobject JvmtiEnvBase::jni_reference(JavaThread *thread, Handle hndl) {
 517   return JNIHandles::make_local(thread, hndl());
 518 }
 519 
 520 void JvmtiEnvBase::destroy_jni_reference(jobject jobj) {
 521   JNIHandles::destroy_local(jobj);
 522 }
 523 
 524 void JvmtiEnvBase::destroy_jni_reference(JavaThread *thread, jobject jobj) {
 525   JNIHandles::destroy_local(jobj); // thread is unused.
 526 }
 527 
 528 //
 529 // Threads
 530 //
 531 
 532 jobject *
 533 JvmtiEnvBase::new_jobjectArray(int length, Handle *handles) {
 534   if (length == 0) {
 535     return NULL;
 536   }
 537 
 538   jobject *objArray = (jobject *) jvmtiMalloc(sizeof(jobject) * length);
 539   NULL_CHECK(objArray, NULL);
 540 
 541   for (int i=0; i<length; i++) {
 542     objArray[i] = jni_reference(handles[i]);
 543   }
 544   return objArray;
 545 }
 546 
 547 jthread *
 548 JvmtiEnvBase::new_jthreadArray(int length, Handle *handles) {
 549   return (jthread *) new_jobjectArray(length,handles);
 550 }
 551 
 552 jthreadGroup *
 553 JvmtiEnvBase::new_jthreadGroupArray(int length, Handle *handles) {
 554   return (jthreadGroup *) new_jobjectArray(length,handles);
 555 }
 556 
 557 // return the vframe on the specified thread and depth, NULL if no such frame
 558 vframe*
 559 JvmtiEnvBase::vframeFor(JavaThread* java_thread, jint depth) {
 560   if (!java_thread->has_last_Java_frame()) {
 561     return NULL;
 562   }
 563   RegisterMap reg_map(java_thread, true, true);
 564   vframe *vf = java_thread->last_java_vframe(&reg_map);
 565   int d = 0;
 566   while ((vf != NULL) && (d < depth)) {
 567     vf = vf->java_sender();
 568     d++;
 569   }
 570   return vf;
 571 }
 572 
 573 
 574 //
 575 // utilities: JNI objects
 576 //
 577 
 578 
 579 jclass
 580 JvmtiEnvBase::get_jni_class_non_null(Klass* k) {
 581   assert(k != NULL, "k != NULL");
 582   Thread *thread = Thread::current();
 583   return (jclass)jni_reference(Handle(thread, k->java_mirror()));
 584 }
 585 
 586 //
 587 // Field Information
 588 //
 589 
 590 bool
 591 JvmtiEnvBase::get_field_descriptor(Klass* k, jfieldID field, fieldDescriptor* fd) {
 592   if (!jfieldIDWorkaround::is_valid_jfieldID(k, field)) {
 593     return false;
 594   }
 595   bool found = false;
 596   if (jfieldIDWorkaround::is_static_jfieldID(field)) {
 597     JNIid* id = jfieldIDWorkaround::from_static_jfieldID(field);
 598     found = id->find_local_field(fd);
 599   } else {
 600     // Non-static field. The fieldID is really the offset of the field within the object.
 601     int offset = jfieldIDWorkaround::from_instance_jfieldID(k, field);
 602     found = InstanceKlass::cast(k)->find_field_from_offset(offset, false, fd);
 603   }
 604   return found;
 605 }
 606 
 607 //
 608 // Object Monitor Information
 609 //
 610 
 611 //
 612 // Count the number of objects for a lightweight monitor. The hobj
 613 // parameter is object that owns the monitor so this routine will
 614 // count the number of times the same object was locked by frames
 615 // in java_thread.
 616 //
 617 jint
 618 JvmtiEnvBase::count_locked_objects(JavaThread *java_thread, Handle hobj) {
 619   jint ret = 0;
 620   if (!java_thread->has_last_Java_frame()) {
 621     return ret;  // no Java frames so no monitors
 622   }
 623 
 624   ResourceMark rm;
 625   HandleMark   hm;
 626   RegisterMap  reg_map(java_thread, true, true);
 627 
 628   for(javaVFrame *jvf=java_thread->last_java_vframe(&reg_map); jvf != NULL;
 629                                                  jvf = jvf->java_sender()) {
 630     GrowableArray<MonitorInfo*>* mons = jvf->monitors();
 631     if (!mons->is_empty()) {
 632       for (int i = 0; i < mons->length(); i++) {
 633         MonitorInfo *mi = mons->at(i);
 634         if (mi->owner_is_scalar_replaced()) continue;
 635 
 636         // see if owner of the monitor is our object
 637         if (mi->owner() != NULL && mi->owner() == hobj()) {
 638           ret++;
 639         }
 640       }
 641     }
 642   }
 643   return ret;
 644 }
 645 
 646 
 647 
 648 jvmtiError
 649 JvmtiEnvBase::get_current_contended_monitor(JavaThread *calling_thread, JavaThread *java_thread, jobject *monitor_ptr) {
 650 #ifdef ASSERT
 651   uint32_t debug_bits = 0;
 652 #endif
 653   assert((SafepointSynchronize::is_at_safepoint() ||
 654           java_thread->is_thread_fully_suspended(false, &debug_bits)),
 655          "at safepoint or target thread is suspended");
 656   oop obj = NULL;
 657   ObjectMonitor *mon = java_thread->current_waiting_monitor();
 658   if (mon == NULL) {
 659     // thread is not doing an Object.wait() call
 660     mon = java_thread->current_pending_monitor();
 661     if (mon != NULL) {
 662       // The thread is trying to enter() or raw_enter() an ObjectMonitor.
 663       obj = (oop)mon->object();
 664       // If obj == NULL, then ObjectMonitor is raw which doesn't count
 665       // as contended for this API
 666     }
 667     // implied else: no contended ObjectMonitor
 668   } else {
 669     // thread is doing an Object.wait() call
 670     obj = (oop)mon->object();
 671     assert(obj != NULL, "Object.wait() should have an object");
 672   }
 673 
 674   if (obj == NULL) {
 675     *monitor_ptr = NULL;
 676   } else {
 677     HandleMark hm;
 678     Handle     hobj(Thread::current(), obj);
 679     *monitor_ptr = jni_reference(calling_thread, hobj);
 680   }
 681   return JVMTI_ERROR_NONE;
 682 }
 683 
 684 
 685 jvmtiError
 686 JvmtiEnvBase::get_owned_monitors(JavaThread *calling_thread, JavaThread* java_thread,
 687                                  GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list) {
 688   jvmtiError err = JVMTI_ERROR_NONE;
 689 #ifdef ASSERT
 690   uint32_t debug_bits = 0;
 691 #endif
 692   assert((SafepointSynchronize::is_at_safepoint() ||
 693           java_thread->is_thread_fully_suspended(false, &debug_bits)),
 694          "at safepoint or target thread is suspended");
 695 
 696   if (java_thread->has_last_Java_frame()) {
 697     ResourceMark rm;
 698     HandleMark   hm;
 699     RegisterMap  reg_map(java_thread, true, true);
 700 
 701     int depth = 0;
 702     for (javaVFrame *jvf = java_thread->last_java_vframe(&reg_map); jvf != NULL;
 703          jvf = jvf->java_sender()) {
 704       if (MaxJavaStackTraceDepth == 0 || depth++ < MaxJavaStackTraceDepth) {  // check for stack too deep
 705         // add locked objects for this frame into list
 706         err = get_locked_objects_in_frame(calling_thread, java_thread, jvf, owned_monitors_list, depth-1);
 707         if (err != JVMTI_ERROR_NONE) {
 708           return err;
 709         }
 710       }
 711     }
 712   }
 713 
 714   // Get off stack monitors. (e.g. acquired via jni MonitorEnter).
 715   JvmtiMonitorClosure jmc(java_thread, calling_thread, owned_monitors_list, this);
 716   ObjectSynchronizer::monitors_iterate(&jmc);
 717   err = jmc.error();
 718 
 719   return err;
 720 }
 721 
 722 // Save JNI local handles for any objects that this frame owns.
 723 jvmtiError
 724 JvmtiEnvBase::get_locked_objects_in_frame(JavaThread* calling_thread, JavaThread* java_thread,
 725                                  javaVFrame *jvf, GrowableArray<jvmtiMonitorStackDepthInfo*>* owned_monitors_list, jint stack_depth) {
 726   jvmtiError err = JVMTI_ERROR_NONE;
 727   ResourceMark rm;
 728 
 729   GrowableArray<MonitorInfo*>* mons = jvf->monitors();
 730   if (mons->is_empty()) {
 731     return err;  // this javaVFrame holds no monitors
 732   }
 733 
 734   HandleMark hm;
 735   oop wait_obj = NULL;
 736   {
 737     // save object of current wait() call (if any) for later comparison
 738     ObjectMonitor *mon = java_thread->current_waiting_monitor();
 739     if (mon != NULL) {
 740       wait_obj = (oop)mon->object();
 741     }
 742   }
 743   oop pending_obj = NULL;
 744   {
 745     // save object of current enter() call (if any) for later comparison
 746     ObjectMonitor *mon = java_thread->current_pending_monitor();
 747     if (mon != NULL) {
 748       pending_obj = (oop)mon->object();
 749     }
 750   }
 751 
 752   for (int i = 0; i < mons->length(); i++) {
 753     MonitorInfo *mi = mons->at(i);
 754 
 755     if (mi->owner_is_scalar_replaced()) continue;
 756 
 757     oop obj = mi->owner();
 758     if (obj == NULL) {
 759       // this monitor doesn't have an owning object so skip it
 760       continue;
 761     }
 762 
 763     if (wait_obj == obj) {
 764       // the thread is waiting on this monitor so it isn't really owned
 765       continue;
 766     }
 767 
 768     if (pending_obj == obj) {
 769       // the thread is pending on this monitor so it isn't really owned
 770       continue;
 771     }
 772 
 773     if (owned_monitors_list->length() > 0) {
 774       // Our list has at least one object on it so we have to check
 775       // for recursive object locking
 776       bool found = false;
 777       for (int j = 0; j < owned_monitors_list->length(); j++) {
 778         jobject jobj = ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(j))->monitor;
 779         oop check = JNIHandles::resolve(jobj);
 780         if (check == obj) {
 781           found = true;  // we found the object
 782           break;
 783         }
 784       }
 785 
 786       if (found) {
 787         // already have this object so don't include it
 788         continue;
 789       }
 790     }
 791 
 792     // add the owning object to our list
 793     jvmtiMonitorStackDepthInfo *jmsdi;
 794     err = allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
 795     if (err != JVMTI_ERROR_NONE) {
 796         return err;
 797     }
 798     Handle hobj(Thread::current(), obj);
 799     jmsdi->monitor = jni_reference(calling_thread, hobj);
 800     jmsdi->stack_depth = stack_depth;
 801     owned_monitors_list->append(jmsdi);
 802   }
 803 
 804   return err;
 805 }
 806 
 807 jvmtiError
 808 JvmtiEnvBase::get_stack_trace(javaVFrame *jvf,
 809                               jint start_depth, jint max_count,
 810                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
 811   Thread* current_thread = Thread::current();
 812   ResourceMark rm(current_thread);
 813   HandleMark hm(current_thread);
 814   int count = 0;
 815 
 816   if (start_depth != 0) {
 817     if (start_depth > 0) {
 818       for (int j = 0; j < start_depth && jvf != NULL; j++) {
 819         jvf = jvf->java_sender();
 820       }
 821       if (jvf == NULL) {
 822         // start_depth is deeper than the stack depth
 823         return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 824       }
 825     } else { // start_depth < 0
 826       // we are referencing the starting depth based on the oldest
 827       // part of the stack.
 828       // optimize to limit the number of times that java_sender() is called
 829       javaVFrame *jvf_cursor = jvf;
 830       javaVFrame *jvf_prev = NULL;
 831       javaVFrame *jvf_prev_prev = NULL;
 832       int j = 0;
 833       while (jvf_cursor != NULL) {
 834         jvf_prev_prev = jvf_prev;
 835         jvf_prev = jvf_cursor;
 836         for (j = 0; j > start_depth && jvf_cursor != NULL; j--) {
 837           jvf_cursor = jvf_cursor->java_sender();
 838         }
 839       }
 840       if (j == start_depth) {
 841         // previous pointer is exactly where we want to start
 842         jvf = jvf_prev;
 843       } else {
 844         // we need to back up further to get to the right place
 845         if (jvf_prev_prev == NULL) {
 846           // the -start_depth is greater than the stack depth
 847           return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 848         }
 849         // j now is the number of frames on the stack starting with
 850         // jvf_prev, we start from jvf_prev_prev and move older on
 851         // the stack that many, the result is -start_depth frames
 852         // remaining.
 853         jvf = jvf_prev_prev;
 854         for (; j < 0; j++) {
 855           jvf = jvf->java_sender();
 856         }
 857       }
 858     }
 859   }
 860   for (; count < max_count && jvf != NULL; count++) {
 861     frame_buffer[count].method = jvf->method()->jmethod_id();
 862     frame_buffer[count].location = (jvf->method()->is_native() ? -1 : jvf->bci());
 863     jvf = jvf->java_sender();
 864   }
 865   *count_ptr = count;
 866   return JVMTI_ERROR_NONE;
 867 }
 868 
 869 jvmtiError
 870 JvmtiEnvBase::get_stack_trace(JavaThread *java_thread,
 871                               jint start_depth, jint max_count,
 872                               jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
 873 #ifdef ASSERT
 874   uint32_t debug_bits = 0;
 875 #endif
 876   assert((SafepointSynchronize::is_at_safepoint() ||
 877           java_thread->is_thread_fully_suspended(false, &debug_bits)),
 878          "at safepoint or target thread is suspended");
 879   int count = 0;
 880   jvmtiError err = JVMTI_ERROR_NONE;
 881 
 882   if (java_thread->has_last_Java_frame()) {
 883     RegisterMap reg_map(java_thread, true, true);
 884     Thread* current_thread = Thread::current();
 885     ResourceMark rm(current_thread);
 886     javaVFrame *jvf = java_thread->last_java_vframe(&reg_map);
 887 
 888     err = get_stack_trace(jvf, start_depth, max_count, frame_buffer, count_ptr);
 889   } else {
 890     *count_ptr = 0;
 891     if (start_depth != 0) {
 892       // no frames and there is a starting depth
 893       err = JVMTI_ERROR_ILLEGAL_ARGUMENT;
 894     }
 895   }
 896   return err;
 897 }
 898 
 899 jvmtiError
 900 JvmtiEnvBase::get_frame_count(JvmtiThreadState *state, jint *count_ptr) {
 901   assert((state != NULL),
 902          "JavaThread should create JvmtiThreadState before calling this method");
 903   *count_ptr = state->count_frames();
 904   return JVMTI_ERROR_NONE;
 905 }
 906 
 907 jvmtiError
 908 JvmtiEnvBase::get_frame_location(JavaThread *java_thread, jint depth,
 909                                  jmethodID* method_ptr, jlocation* location_ptr) {
 910 #ifdef ASSERT
 911   uint32_t debug_bits = 0;
 912 #endif
 913   assert((SafepointSynchronize::is_at_safepoint() ||
 914           java_thread->is_thread_fully_suspended(false, &debug_bits)),
 915          "at safepoint or target thread is suspended");
 916   Thread* current_thread = Thread::current();
 917   ResourceMark rm(current_thread);
 918 
 919   vframe *vf = vframeFor(java_thread, depth);
 920   if (vf == NULL) {
 921     return JVMTI_ERROR_NO_MORE_FRAMES;
 922   }
 923 
 924   // vframeFor should return a java frame. If it doesn't
 925   // it means we've got an internal error and we return the
 926   // error in product mode. In debug mode we will instead
 927   // attempt to cast the vframe to a javaVFrame and will
 928   // cause an assertion/crash to allow further diagnosis.
 929 #ifdef PRODUCT
 930   if (!vf->is_java_frame()) {
 931     return JVMTI_ERROR_INTERNAL;
 932   }
 933 #endif
 934 
 935   HandleMark hm(current_thread);
 936   javaVFrame *jvf = javaVFrame::cast(vf);
 937   Method* method = jvf->method();
 938   if (method->is_native()) {
 939     *location_ptr = -1;
 940   } else {
 941     *location_ptr = jvf->bci();
 942   }
 943   *method_ptr = method->jmethod_id();
 944 
 945   return JVMTI_ERROR_NONE;
 946 }
 947 
 948 
 949 jvmtiError
 950 JvmtiEnvBase::get_object_monitor_usage(JavaThread* calling_thread, jobject object, jvmtiMonitorUsage* info_ptr) {
 951   HandleMark hm;
 952   Handle hobj;
 953 
 954   Thread* current_thread = Thread::current();
 955   bool at_safepoint = SafepointSynchronize::is_at_safepoint();
 956 
 957   // Check arguments
 958   {
 959     oop mirror = JNIHandles::resolve_external_guard(object);
 960     NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
 961     NULL_CHECK(info_ptr, JVMTI_ERROR_NULL_POINTER);
 962 
 963     hobj = Handle(current_thread, mirror);
 964   }
 965 
 966   JavaThread *owning_thread = NULL;
 967   ObjectMonitor *mon = NULL;
 968   jvmtiMonitorUsage ret = {
 969       NULL, 0, 0, NULL, 0, NULL
 970   };
 971 
 972   uint32_t debug_bits = 0;
 973   // first derive the object's owner and entry_count (if any)
 974   {
 975     // Revoke any biases before querying the mark word
 976     if (at_safepoint) {
 977       BiasedLocking::revoke_at_safepoint(hobj);
 978     } else {
 979       BiasedLocking::revoke_and_rebias(hobj, false, calling_thread);
 980     }
 981 
 982     address owner = NULL;
 983     {
 984       markOop mark = hobj()->mark();
 985 
 986       if (!mark->has_monitor()) {
 987         // this object has a lightweight monitor
 988 
 989         if (mark->has_locker()) {
 990           owner = (address)mark->locker(); // save the address of the Lock word
 991         }
 992         // implied else: no owner
 993       } else {
 994         // this object has a heavyweight monitor
 995         mon = mark->monitor();
 996 
 997         // The owner field of a heavyweight monitor may be NULL for no
 998         // owner, a JavaThread * or it may still be the address of the
 999         // Lock word in a JavaThread's stack. A monitor can be inflated
1000         // by a non-owning JavaThread, but only the owning JavaThread
1001         // can change the owner field from the Lock word to the
1002         // JavaThread * and it may not have done that yet.
1003         owner = (address)mon->owner();
1004       }
1005     }
1006 
1007     if (owner != NULL) {
1008       // Use current thread since function can be called from a
1009       // JavaThread or the VMThread.
1010       ThreadsListHandle tlh;
1011       // This monitor is owned so we have to find the owning JavaThread.
1012       owning_thread = Threads::owning_thread_from_monitor_owner(tlh.list(), owner);
1013       // Cannot assume (owning_thread != NULL) here because this function
1014       // may not have been called at a safepoint and the owning_thread
1015       // might not be suspended.
1016       if (owning_thread != NULL) {
1017         // The monitor's owner either has to be the current thread, at safepoint
1018         // or it has to be suspended. Any of these conditions will prevent both
1019         // contending and waiting threads from modifying the state of
1020         // the monitor.
1021         if (!at_safepoint && !owning_thread->is_thread_fully_suspended(true, &debug_bits)) {
1022           // Don't worry! This return of JVMTI_ERROR_THREAD_NOT_SUSPENDED
1023           // will not make it back to the JVM/TI agent. The error code will
1024           // get intercepted in JvmtiEnv::GetObjectMonitorUsage() which
1025           // will retry the call via a VM_GetObjectMonitorUsage VM op.
1026           return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1027         }
1028         HandleMark hm;
1029         Handle     th(current_thread, owning_thread->threadObj());
1030         ret.owner = (jthread)jni_reference(calling_thread, th);
1031       }
1032       // implied else: no owner
1033     } // ThreadsListHandle is destroyed here.
1034 
1035     if (owning_thread != NULL) {  // monitor is owned
1036       // The recursions field of a monitor does not reflect recursions
1037       // as lightweight locks before inflating the monitor are not included.
1038       // We have to count the number of recursive monitor entries the hard way.
1039       // We pass a handle to survive any GCs along the way.
1040       ResourceMark rm;
1041       ret.entry_count = count_locked_objects(owning_thread, hobj);
1042     }
1043     // implied else: entry_count == 0
1044   }
1045 
1046   jint nWant = 0, nWait = 0;
1047   if (mon != NULL) {
1048     // this object has a heavyweight monitor
1049     nWant = mon->contentions(); // # of threads contending for monitor
1050     nWait = mon->waiters();     // # of threads in Object.wait()
1051     ret.waiter_count = nWant + nWait;
1052     ret.notify_waiter_count = nWait;
1053   } else {
1054     // this object has a lightweight monitor
1055     ret.waiter_count = 0;
1056     ret.notify_waiter_count = 0;
1057   }
1058 
1059   // Allocate memory for heavyweight and lightweight monitor.
1060   jvmtiError err;
1061   err = allocate(ret.waiter_count * sizeof(jthread *), (unsigned char**)&ret.waiters);
1062   if (err != JVMTI_ERROR_NONE) {
1063     return err;
1064   }
1065   err = allocate(ret.notify_waiter_count * sizeof(jthread *),
1066                  (unsigned char**)&ret.notify_waiters);
1067   if (err != JVMTI_ERROR_NONE) {
1068     deallocate((unsigned char*)ret.waiters);
1069     return err;
1070   }
1071 
1072   // now derive the rest of the fields
1073   if (mon != NULL) {
1074     // this object has a heavyweight monitor
1075 
1076     // Number of waiters may actually be less than the waiter count.
1077     // So NULL out memory so that unused memory will be NULL.
1078     memset(ret.waiters, 0, ret.waiter_count * sizeof(jthread *));
1079     memset(ret.notify_waiters, 0, ret.notify_waiter_count * sizeof(jthread *));
1080 
1081     if (ret.waiter_count > 0) {
1082       // we have contending and/or waiting threads
1083       HandleMark hm;
1084       // Use current thread since function can be called from a
1085       // JavaThread or the VMThread.
1086       ThreadsListHandle tlh;
1087       if (nWant > 0) {
1088         // we have contending threads
1089         ResourceMark rm;
1090         // get_pending_threads returns only java thread so we do not need to
1091         // check for non java threads.
1092         GrowableArray<JavaThread*>* wantList = Threads::get_pending_threads(tlh.list(), nWant, (address)mon);
1093         if (wantList->length() < nWant) {
1094           // robustness: the pending list has gotten smaller
1095           nWant = wantList->length();
1096         }
1097         for (int i = 0; i < nWant; i++) {
1098           JavaThread *pending_thread = wantList->at(i);
1099           // If the monitor has no owner, then a non-suspended contending
1100           // thread could potentially change the state of the monitor by
1101           // entering it. The JVM/TI spec doesn't allow this.
1102           if (owning_thread == NULL && !at_safepoint &&
1103               !pending_thread->is_thread_fully_suspended(true, &debug_bits)) {
1104             if (ret.owner != NULL) {
1105               destroy_jni_reference(calling_thread, ret.owner);
1106             }
1107             for (int j = 0; j < i; j++) {
1108               destroy_jni_reference(calling_thread, ret.waiters[j]);
1109             }
1110             deallocate((unsigned char*)ret.waiters);
1111             deallocate((unsigned char*)ret.notify_waiters);
1112             return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1113           }
1114           Handle th(current_thread, pending_thread->threadObj());
1115           ret.waiters[i] = (jthread)jni_reference(calling_thread, th);
1116         }
1117       }
1118       if (nWait > 0) {
1119         // we have threads in Object.wait()
1120         int offset = nWant;  // add after any contending threads
1121         ObjectWaiter *waiter = mon->first_waiter();
1122         for (int i = 0, j = 0; i < nWait; i++) {
1123           if (waiter == NULL) {
1124             // robustness: the waiting list has gotten smaller
1125             nWait = j;
1126             break;
1127           }
1128           Thread *t = mon->thread_of_waiter(waiter);
1129           if (t != NULL && t->is_Java_thread()) {
1130             JavaThread *wjava_thread = (JavaThread *)t;
1131             // If the thread was found on the ObjectWaiter list, then
1132             // it has not been notified. This thread can't change the
1133             // state of the monitor so it doesn't need to be suspended.
1134             Handle th(current_thread, wjava_thread->threadObj());
1135             ret.waiters[offset + j] = (jthread)jni_reference(calling_thread, th);
1136             ret.notify_waiters[j++] = (jthread)jni_reference(calling_thread, th);
1137           }
1138           waiter = mon->next_waiter(waiter);
1139         }
1140       }
1141     } // ThreadsListHandle is destroyed here.
1142 
1143     // Adjust count. nWant and nWait count values may be less than original.
1144     ret.waiter_count = nWant + nWait;
1145     ret.notify_waiter_count = nWait;
1146   } else {
1147     // this object has a lightweight monitor and we have nothing more
1148     // to do here because the defaults are just fine.
1149   }
1150 
1151   // we don't update return parameter unless everything worked
1152   *info_ptr = ret;
1153 
1154   return JVMTI_ERROR_NONE;
1155 }
1156 
1157 ResourceTracker::ResourceTracker(JvmtiEnv* env) {
1158   _env = env;
1159   _allocations = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<unsigned char*>(20, true);
1160   _failed = false;
1161 }
1162 ResourceTracker::~ResourceTracker() {
1163   if (_failed) {
1164     for (int i=0; i<_allocations->length(); i++) {
1165       _env->deallocate(_allocations->at(i));
1166     }
1167   }
1168   delete _allocations;
1169 }
1170 
1171 jvmtiError ResourceTracker::allocate(jlong size, unsigned char** mem_ptr) {
1172   unsigned char *ptr;
1173   jvmtiError err = _env->allocate(size, &ptr);
1174   if (err == JVMTI_ERROR_NONE) {
1175     _allocations->append(ptr);
1176     *mem_ptr = ptr;
1177   } else {
1178     *mem_ptr = NULL;
1179     _failed = true;
1180   }
1181   return err;
1182  }
1183 
1184 unsigned char* ResourceTracker::allocate(jlong size) {
1185   unsigned char* ptr;
1186   allocate(size, &ptr);
1187   return ptr;
1188 }
1189 
1190 char* ResourceTracker::strdup(const char* str) {
1191   char *dup_str = (char*)allocate(strlen(str)+1);
1192   if (dup_str != NULL) {
1193     strcpy(dup_str, str);
1194   }
1195   return dup_str;
1196 }
1197 
1198 struct StackInfoNode {
1199   struct StackInfoNode *next;
1200   jvmtiStackInfo info;
1201 };
1202 
1203 // Create a jvmtiStackInfo inside a linked list node and create a
1204 // buffer for the frame information, both allocated as resource objects.
1205 // Fill in both the jvmtiStackInfo and the jvmtiFrameInfo.
1206 // Note that either or both of thr and thread_oop
1207 // may be null if the thread is new or has exited.
1208 void
1209 VM_GetMultipleStackTraces::fill_frames(jthread jt, JavaThread *thr, oop thread_oop) {
1210   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1211 
1212   jint state = 0;
1213   struct StackInfoNode *node = NEW_RESOURCE_OBJ(struct StackInfoNode);
1214   jvmtiStackInfo *infop = &(node->info);
1215   node->next = head();
1216   set_head(node);
1217   infop->frame_count = 0;
1218   infop->thread = jt;
1219 
1220   if (thread_oop != NULL) {
1221     // get most state bits
1222     state = (jint)java_lang_Thread::get_thread_status(thread_oop);
1223   }
1224 
1225   if (thr != NULL) {    // add more state bits if there is a JavaThead to query
1226     // same as is_being_ext_suspended() but without locking
1227     if (thr->is_ext_suspended() || thr->is_external_suspend()) {
1228       state |= JVMTI_THREAD_STATE_SUSPENDED;
1229     }
1230     JavaThreadState jts = thr->thread_state();
1231     if (jts == _thread_in_native) {
1232       state |= JVMTI_THREAD_STATE_IN_NATIVE;
1233     }
1234     OSThread* osThread = thr->osthread();
1235     if (osThread != NULL && osThread->interrupted()) {
1236       state |= JVMTI_THREAD_STATE_INTERRUPTED;
1237     }
1238   }
1239   infop->state = state;
1240 
1241   if (thr != NULL && (state & JVMTI_THREAD_STATE_ALIVE) != 0) {
1242     infop->frame_buffer = NEW_RESOURCE_ARRAY(jvmtiFrameInfo, max_frame_count());
1243     env()->get_stack_trace(thr, 0, max_frame_count(),
1244                            infop->frame_buffer, &(infop->frame_count));
1245   } else {
1246     infop->frame_buffer = NULL;
1247     infop->frame_count = 0;
1248   }
1249   _frame_count_total += infop->frame_count;
1250 }
1251 
1252 // Based on the stack information in the linked list, allocate memory
1253 // block to return and fill it from the info in the linked list.
1254 void
1255 VM_GetMultipleStackTraces::allocate_and_fill_stacks(jint thread_count) {
1256   // do I need to worry about alignment issues?
1257   jlong alloc_size =  thread_count       * sizeof(jvmtiStackInfo)
1258                     + _frame_count_total * sizeof(jvmtiFrameInfo);
1259   env()->allocate(alloc_size, (unsigned char **)&_stack_info);
1260 
1261   // pointers to move through the newly allocated space as it is filled in
1262   jvmtiStackInfo *si = _stack_info + thread_count;      // bottom of stack info
1263   jvmtiFrameInfo *fi = (jvmtiFrameInfo *)si;            // is the top of frame info
1264 
1265   // copy information in resource area into allocated buffer
1266   // insert stack info backwards since linked list is backwards
1267   // insert frame info forwards
1268   // walk the StackInfoNodes
1269   for (struct StackInfoNode *sin = head(); sin != NULL; sin = sin->next) {
1270     jint frame_count = sin->info.frame_count;
1271     size_t frames_size = frame_count * sizeof(jvmtiFrameInfo);
1272     --si;
1273     memcpy(si, &(sin->info), sizeof(jvmtiStackInfo));
1274     if (frames_size == 0) {
1275       si->frame_buffer = NULL;
1276     } else {
1277       memcpy(fi, sin->info.frame_buffer, frames_size);
1278       si->frame_buffer = fi;  // point to the new allocated copy of the frames
1279       fi += frame_count;
1280     }
1281   }
1282   assert(si == _stack_info, "the last copied stack info must be the first record");
1283   assert((unsigned char *)fi == ((unsigned char *)_stack_info) + alloc_size,
1284          "the last copied frame info must be the last record");
1285 }
1286 
1287 
1288 void
1289 VM_GetThreadListStackTraces::doit() {
1290   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1291 
1292   ResourceMark rm;
1293   ThreadsListHandle tlh;
1294   for (int i = 0; i < _thread_count; ++i) {
1295     jthread jt = _thread_list[i];
1296     JavaThread* java_thread = NULL;
1297     oop thread_oop = NULL;
1298     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), jt, &java_thread, &thread_oop);
1299     if (err != JVMTI_ERROR_NONE) {
1300       // We got an error code so we don't have a JavaThread *, but
1301       // only return an error from here if we didn't get a valid
1302       // thread_oop.
1303       if (thread_oop == NULL) {
1304         set_result(err);
1305         return;
1306       }
1307       // We have a valid thread_oop.
1308     }
1309     fill_frames(jt, java_thread, thread_oop);
1310   }
1311   allocate_and_fill_stacks(_thread_count);
1312 }
1313 
1314 void
1315 VM_GetAllStackTraces::doit() {
1316   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1317 
1318   ResourceMark rm;
1319   _final_thread_count = 0;
1320   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) {
1321     oop thread_oop = jt->threadObj();
1322     if (thread_oop != NULL &&
1323         !jt->is_exiting() &&
1324         java_lang_Thread::is_alive(thread_oop) &&
1325         !jt->is_hidden_from_external_view()) {
1326       ++_final_thread_count;
1327       // Handle block of the calling thread is used to create local refs.
1328       fill_frames((jthread)JNIHandles::make_local(_calling_thread, thread_oop),
1329                   jt, thread_oop);
1330     }
1331   }
1332   allocate_and_fill_stacks(_final_thread_count);
1333 }
1334 
1335 // Verifies that the top frame is a java frame in an expected state.
1336 // Deoptimizes frame if needed.
1337 // Checks that the frame method signature matches the return type (tos).
1338 // HandleMark must be defined in the caller only.
1339 // It is to keep a ret_ob_h handle alive after return to the caller.
1340 jvmtiError
1341 JvmtiEnvBase::check_top_frame(JavaThread* current_thread, JavaThread* java_thread,
1342                               jvalue value, TosState tos, Handle* ret_ob_h) {
1343   ResourceMark rm(current_thread);
1344 
1345   vframe *vf = vframeFor(java_thread, 0);
1346   NULL_CHECK(vf, JVMTI_ERROR_NO_MORE_FRAMES);
1347 
1348   javaVFrame *jvf = (javaVFrame*) vf;
1349   if (!vf->is_java_frame() || jvf->method()->is_native()) {
1350     return JVMTI_ERROR_OPAQUE_FRAME;
1351   }
1352 
1353   // If the frame is a compiled one, need to deoptimize it.
1354   if (vf->is_compiled_frame()) {
1355     if (!vf->fr().can_be_deoptimized()) {
1356       return JVMTI_ERROR_OPAQUE_FRAME;
1357     }
1358     Deoptimization::deoptimize_frame(java_thread, jvf->fr().id());
1359   }
1360 
1361   // Get information about method return type
1362   Symbol* signature = jvf->method()->signature();
1363 
1364   ResultTypeFinder rtf(signature);
1365   TosState fr_tos = as_TosState(rtf.type());
1366   if (fr_tos != tos) {
1367     if (tos != itos || (fr_tos != btos && fr_tos != ztos && fr_tos != ctos && fr_tos != stos)) {
1368       return JVMTI_ERROR_TYPE_MISMATCH;
1369     }
1370   }
1371 
1372   // Check that the jobject class matches the return type signature.
1373   jobject jobj = value.l;
1374   if (tos == atos && jobj != NULL) { // NULL reference is allowed
1375     Handle ob_h(current_thread, JNIHandles::resolve_external_guard(jobj));
1376     NULL_CHECK(ob_h, JVMTI_ERROR_INVALID_OBJECT);
1377     Klass* ob_k = ob_h()->klass();
1378     NULL_CHECK(ob_k, JVMTI_ERROR_INVALID_OBJECT);
1379 
1380     // Method return type signature.
1381     char* ty_sign = 1 + strchr(signature->as_C_string(), ')');
1382 
1383     if (!VM_GetOrSetLocal::is_assignable(ty_sign, ob_k, current_thread)) {
1384       return JVMTI_ERROR_TYPE_MISMATCH;
1385     }
1386     *ret_ob_h = ob_h;
1387   }
1388   return JVMTI_ERROR_NONE;
1389 } /* end check_top_frame */
1390 
1391 
1392 // ForceEarlyReturn<type> follows the PopFrame approach in many aspects.
1393 // Main difference is on the last stage in the interpreter.
1394 // The PopFrame stops method execution to continue execution
1395 // from the same method call instruction.
1396 // The ForceEarlyReturn forces return from method so the execution
1397 // continues at the bytecode following the method call.
1398 
1399 // Threads_lock NOT held, java_thread not protected by lock
1400 // java_thread - pre-checked
1401 
1402 jvmtiError
1403 JvmtiEnvBase::force_early_return(JavaThread* java_thread, jvalue value, TosState tos) {
1404   JavaThread* current_thread = JavaThread::current();
1405   HandleMark   hm(current_thread);
1406   uint32_t debug_bits = 0;
1407 
1408   // retrieve or create the state
1409   JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
1410   if (state == NULL) {
1411     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1412   }
1413 
1414   // Check if java_thread is fully suspended
1415   if (!java_thread->is_thread_fully_suspended(true /* wait for suspend completion */, &debug_bits)) {
1416     return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1417   }
1418 
1419   // Check to see if a ForceEarlyReturn was already in progress
1420   if (state->is_earlyret_pending()) {
1421     // Probably possible for JVMTI clients to trigger this, but the
1422     // JPDA backend shouldn't allow this to happen
1423     return JVMTI_ERROR_INTERNAL;
1424   }
1425   {
1426     // The same as for PopFrame. Workaround bug:
1427     //  4812902: popFrame hangs if the method is waiting at a synchronize
1428     // Catch this condition and return an error to avoid hanging.
1429     // Now JVMTI spec allows an implementation to bail out with an opaque
1430     // frame error.
1431     OSThread* osThread = java_thread->osthread();
1432     if (osThread->get_state() == MONITOR_WAIT) {
1433       return JVMTI_ERROR_OPAQUE_FRAME;
1434     }
1435   }
1436   Handle ret_ob_h;
1437   jvmtiError err = check_top_frame(current_thread, java_thread, value, tos, &ret_ob_h);
1438   if (err != JVMTI_ERROR_NONE) {
1439     return err;
1440   }
1441   assert(tos != atos || value.l == NULL || ret_ob_h() != NULL,
1442          "return object oop must not be NULL if jobject is not NULL");
1443 
1444   // Update the thread state to reflect that the top frame must be
1445   // forced to return.
1446   // The current frame will be returned later when the suspended
1447   // thread is resumed and right before returning from VM to Java.
1448   // (see call_VM_base() in assembler_<cpu>.cpp).
1449 
1450   state->set_earlyret_pending();
1451   state->set_earlyret_oop(ret_ob_h());
1452   state->set_earlyret_value(value, tos);
1453 
1454   // Set pending step flag for this early return.
1455   // It is cleared when next step event is posted.
1456   state->set_pending_step_for_earlyret();
1457 
1458   return JVMTI_ERROR_NONE;
1459 } /* end force_early_return */
1460 
1461 void
1462 JvmtiMonitorClosure::do_monitor(ObjectMonitor* mon) {
1463   if ( _error != JVMTI_ERROR_NONE) {
1464     // Error occurred in previous iteration so no need to add
1465     // to the list.
1466     return;
1467   }
1468   if (mon->owner() == _java_thread ) {
1469     // Filter out on stack monitors collected during stack walk.
1470     oop obj = (oop)mon->object();
1471     bool found = false;
1472     for (int j = 0; j < _owned_monitors_list->length(); j++) {
1473       jobject jobj = ((jvmtiMonitorStackDepthInfo*)_owned_monitors_list->at(j))->monitor;
1474       oop check = JNIHandles::resolve(jobj);
1475       if (check == obj) {
1476         // On stack monitor already collected during the stack walk.
1477         found = true;
1478         break;
1479       }
1480     }
1481     if (found == false) {
1482       // This is off stack monitor (e.g. acquired via jni MonitorEnter).
1483       jvmtiError err;
1484       jvmtiMonitorStackDepthInfo *jmsdi;
1485       err = _env->allocate(sizeof(jvmtiMonitorStackDepthInfo), (unsigned char **)&jmsdi);
1486       if (err != JVMTI_ERROR_NONE) {
1487         _error = err;
1488         return;
1489       }
1490       Handle hobj(Thread::current(), obj);
1491       jmsdi->monitor = _env->jni_reference(_calling_thread, hobj);
1492       // stack depth is unknown for this monitor.
1493       jmsdi->stack_depth = -1;
1494       _owned_monitors_list->append(jmsdi);
1495     }
1496   }
1497 }
1498 
1499 GrowableArray<OopHandle>* JvmtiModuleClosure::_tbl = NULL;
1500 
1501 void JvmtiModuleClosure::do_module(ModuleEntry* entry) {
1502   assert_locked_or_safepoint(Module_lock);
1503   OopHandle module = entry->module_handle();
1504   guarantee(module.resolve() != NULL, "module object is NULL");
1505   _tbl->push(module);
1506 }
1507 
1508 jvmtiError
1509 JvmtiModuleClosure::get_all_modules(JvmtiEnv* env, jint* module_count_ptr, jobject** modules_ptr) {
1510   ResourceMark rm;
1511   MutexLocker mcld(ClassLoaderDataGraph_lock);
1512   MutexLocker ml(Module_lock);
1513 
1514   _tbl = new GrowableArray<OopHandle>(77);
1515   if (_tbl == NULL) {
1516     return JVMTI_ERROR_OUT_OF_MEMORY;
1517   }
1518 
1519   // Iterate over all the modules loaded to the system.
1520   ClassLoaderDataGraph::modules_do(&do_module);
1521 
1522   jint len = _tbl->length();
1523   guarantee(len > 0, "at least one module must be present");
1524 
1525   jobject* array = (jobject*)env->jvmtiMalloc((jlong)(len * sizeof(jobject)));
1526   if (array == NULL) {
1527     return JVMTI_ERROR_OUT_OF_MEMORY;
1528   }
1529   for (jint idx = 0; idx < len; idx++) {
1530     array[idx] = JNIHandles::make_local(Thread::current(), _tbl->at(idx).resolve());
1531   }
1532   _tbl = NULL;
1533   *modules_ptr = array;
1534   *module_count_ptr = len;
1535   return JVMTI_ERROR_NONE;
1536 }
1537 
1538 void
1539 VM_UpdateForPopTopFrame::doit() {
1540   JavaThread* jt = _state->get_thread();
1541   ThreadsListHandle tlh;
1542   if (jt != NULL && tlh.includes(jt) && !jt->is_exiting() && jt->threadObj() != NULL) {
1543     _state->update_for_pop_top_frame();
1544   } else {
1545     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
1546   }
1547 }
1548 
1549 void
1550 VM_SetFramePop::doit() {
1551   JavaThread* jt = _state->get_thread();
1552   ThreadsListHandle tlh;
1553   if (jt != NULL && tlh.includes(jt) && !jt->is_exiting() && jt->threadObj() != NULL) {
1554     int frame_number = _state->count_frames() - _depth;
1555     _state->env_thread_state((JvmtiEnvBase*)_env)->set_frame_pop(frame_number);
1556   } else {
1557     _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
1558   }
1559 }
1560 
1561 void
1562 VM_GetOwnedMonitorInfo::doit() {
1563   _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
1564   ThreadsListHandle tlh;
1565   if (_java_thread != NULL && tlh.includes(_java_thread)
1566       && !_java_thread->is_exiting() && _java_thread->threadObj() != NULL) {
1567     _result = ((JvmtiEnvBase *)_env)->get_owned_monitors(_calling_thread, _java_thread,
1568                                                           _owned_monitors_list);
1569   }
1570 }
1571 
1572 void
1573 VM_GetCurrentContendedMonitor::doit() {
1574   _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
1575   ThreadsListHandle tlh;
1576   if (_java_thread != NULL && tlh.includes(_java_thread)
1577       && !_java_thread->is_exiting() && _java_thread->threadObj() != NULL) {
1578     _result = ((JvmtiEnvBase *)_env)->get_current_contended_monitor(_calling_thread,_java_thread,_owned_monitor_ptr);
1579   }
1580 }
1581 
1582 void
1583 VM_GetStackTrace::doit() {
1584   _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
1585   ThreadsListHandle tlh;
1586   if (_java_thread != NULL && tlh.includes(_java_thread)
1587       && !_java_thread->is_exiting() && _java_thread->threadObj() != NULL) {
1588     _result = ((JvmtiEnvBase *)_env)->get_stack_trace(_java_thread,
1589                                                       _start_depth, _max_count,
1590                                                       _frame_buffer, _count_ptr);
1591   }
1592 }
1593 
1594 void
1595 VM_GetFrameCount::doit() {
1596   _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
1597   JavaThread* jt = _state->get_thread();
1598   ThreadsListHandle tlh;
1599   if (jt != NULL && tlh.includes(jt) && !jt->is_exiting() && jt->threadObj() != NULL) {
1600     _result = ((JvmtiEnvBase*)_env)->get_frame_count(_state, _count_ptr);
1601   }
1602 }
1603 
1604 void
1605 VM_GetFrameLocation::doit() {
1606   _result = JVMTI_ERROR_THREAD_NOT_ALIVE;
1607   ThreadsListHandle tlh;
1608   if (_java_thread != NULL && tlh.includes(_java_thread)
1609       && !_java_thread->is_exiting() && _java_thread->threadObj() != NULL) {
1610     _result = ((JvmtiEnvBase*)_env)->get_frame_location(_java_thread, _depth,
1611                                                         _method_ptr, _location_ptr);
1612   }
1613 }
1614 
1615 void
1616 VM_GetFiberThread::doit() {
1617   oop carrier_thread = java_lang_Fiber::carrier_thread(_fiber_h());
1618   *_carrier_thread_ptr = (jthread)JNIHandles::make_local(_current_thread, carrier_thread);
1619 }
1620 
1621 static
1622 javaVFrame* get_fiber_jvf(Thread* cur_thread, oop fiber) {
1623   oop cont = java_lang_Fiber::continuation(fiber);
1624   javaVFrame* jvf = NULL;
1625 
1626   if (cont != NULL && java_lang_Continuation::is_mounted(cont)) {
1627     oop carrier_thread = java_lang_Fiber::carrier_thread(fiber);
1628     JavaThread* java_thread = java_lang_Thread::thread(carrier_thread);
1629     vframeStream vfs(java_thread, Handle(cur_thread, Continuation::continuation_scope(cont)));
1630     
1631     if (!vfs.at_end()) {
1632       jvf = vfs.asJavaVFrame();
1633     }
1634   } else {
1635     Handle cont_h(cur_thread, cont);
1636     vframeStream vfs(cont_h);
1637 
1638     if (!vfs.at_end()) {
1639       jvf = vfs.asJavaVFrame();
1640     }
1641   }
1642   return jvf;
1643 }
1644 
1645 void
1646 VM_GetFiberStackTrace::doit() {
1647   Thread* cur_thread = Thread::current();
1648   ResourceMark rm(cur_thread);
1649   HandleMark hm(cur_thread);
1650   javaVFrame *jvf = get_fiber_jvf(cur_thread, _fiber_h());
1651   _result = ((JvmtiEnvBase *)_env)->get_stack_trace(jvf,
1652                                                     _start_depth, _max_count,
1653                                                     _frame_buffer, _count_ptr);
1654 }
1655 
1656 void
1657 VM_GetFiberFrameCount::doit() {
1658   Thread* cur_thread = Thread::current();
1659   ResourceMark rm(cur_thread);
1660   HandleMark hm(cur_thread);
1661   javaVFrame *jvf = get_fiber_jvf(cur_thread, _fiber_h());
1662   int count = 0;
1663 
1664   while (jvf != NULL) {
1665     Method* method = jvf->method();
1666     jvf = jvf->java_sender();
1667     count++;
1668   }
1669   *_count_ptr = count;
1670 }
1671 
1672 void
1673 VM_GetFiberFrameLocation::doit() {
1674   Thread* cur_thread = Thread::current();
1675   ResourceMark rm(cur_thread);
1676   HandleMark hm(cur_thread);
1677   javaVFrame *jvf = get_fiber_jvf(cur_thread, _fiber_h());
1678   int  depth = -1;
1679 
1680   while (jvf != NULL && depth < _depth) {
1681     Method* method = jvf->method();
1682     jvf = jvf->java_sender();
1683     depth++;
1684   }
1685 
1686   if (depth < _depth) {
1687     _result = JVMTI_ERROR_NO_MORE_FRAMES;
1688     return;
1689   }
1690 
1691   Method* method = jvf->method();
1692   if (method->is_native()) {
1693     *_location_ptr = -1;
1694   } else {
1695     *_location_ptr = jvf->bci();
1696   }
1697   *_method_ptr = method->jmethod_id();
1698 }