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