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