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