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