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