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