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