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/classLoaderExt.hpp"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/modules.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "classfile/vmSymbols.hpp"
  32 #include "interpreter/bytecodeStream.hpp"
  33 #include "interpreter/interpreter.hpp"
  34 #include "jvmtifiles/jvmtiEnv.hpp"
  35 #include "logging/log.hpp"
  36 #include "logging/logConfiguration.hpp"
  37 #include "memory/resourceArea.hpp"
  38 #include "memory/universe.hpp"
  39 #include "oops/instanceKlass.hpp"
  40 #include "oops/objArrayOop.inline.hpp"
  41 #include "oops/oop.inline.hpp"
  42 #include "prims/jniCheck.hpp"
  43 #include "prims/jvm_misc.hpp"
  44 #include "prims/jvmtiAgentThread.hpp"
  45 #include "prims/jvmtiClassFileReconstituter.hpp"
  46 #include "prims/jvmtiCodeBlobEvents.hpp"
  47 #include "prims/jvmtiExtensions.hpp"
  48 #include "prims/jvmtiGetLoadedClasses.hpp"
  49 #include "prims/jvmtiImpl.hpp"
  50 #include "prims/jvmtiManageCapabilities.hpp"
  51 #include "prims/jvmtiRawMonitor.hpp"
  52 #include "prims/jvmtiRedefineClasses.hpp"
  53 #include "prims/jvmtiTagMap.hpp"
  54 #include "prims/jvmtiThreadState.inline.hpp"
  55 #include "prims/jvmtiUtil.hpp"
  56 #include "runtime/arguments.hpp"
  57 #include "runtime/deoptimization.hpp"
  58 #include "runtime/fieldDescriptor.inline.hpp"
  59 #include "runtime/interfaceSupport.inline.hpp"
  60 #include "runtime/javaCalls.hpp"
  61 #include "runtime/jfieldIDWorkaround.hpp"
  62 #include "runtime/jniHandles.inline.hpp"
  63 #include "runtime/objectMonitor.inline.hpp"
  64 #include "runtime/osThread.hpp"
  65 #include "runtime/reflectionUtils.hpp"
  66 #include "runtime/signature.hpp"
  67 #include "runtime/thread.inline.hpp"
  68 #include "runtime/threadHeapSampler.hpp"
  69 #include "runtime/threadSMR.hpp"
  70 #include "runtime/timerTrace.hpp"
  71 #include "runtime/vframe.inline.hpp"
  72 #include "runtime/vmThread.hpp"
  73 #include "services/threadService.hpp"
  74 #include "utilities/exceptions.hpp"
  75 #include "utilities/preserveException.hpp"
  76 
  77 
  78 #define FIXLATER 0 // REMOVE this when completed.
  79 
  80  // FIXLATER: hook into JvmtiTrace
  81 #define TraceJVMTICalls false
  82 
  83 JvmtiEnv::JvmtiEnv(jint version) : JvmtiEnvBase(version) {
  84 }
  85 
  86 JvmtiEnv::~JvmtiEnv() {
  87 }
  88 
  89 JvmtiEnv*
  90 JvmtiEnv::create_a_jvmti(jint version) {
  91   return new JvmtiEnv(version);
  92 }
  93 
  94 // VM operation class to copy jni function table at safepoint.
  95 // More than one java threads or jvmti agents may be reading/
  96 // modifying jni function tables. To reduce the risk of bad
  97 // interaction b/w these threads it is copied at safepoint.
  98 class VM_JNIFunctionTableCopier : public VM_Operation {
  99  private:
 100   const struct JNINativeInterface_ *_function_table;
 101  public:
 102   VM_JNIFunctionTableCopier(const struct JNINativeInterface_ *func_tbl) {
 103     _function_table = func_tbl;
 104   };
 105 
 106   VMOp_Type type() const { return VMOp_JNIFunctionTableCopier; }
 107   void doit() {
 108     copy_jni_function_table(_function_table);
 109   };
 110 };
 111 
 112 //
 113 // Do not change the "prefix" marker below, everything above it is copied
 114 // unchanged into the filled stub, everything below is controlled by the
 115 // stub filler (only method bodies are carried forward, and then only for
 116 // functionality still in the spec).
 117 //
 118 // end file prefix
 119 
 120   //
 121   // Memory Management functions
 122   //
 123 
 124 // mem_ptr - pre-checked for NULL
 125 jvmtiError
 126 JvmtiEnv::Allocate(jlong size, unsigned char** mem_ptr) {
 127   return allocate(size, mem_ptr);
 128 } /* end Allocate */
 129 
 130 
 131 // mem - NULL is a valid value, must be checked
 132 jvmtiError
 133 JvmtiEnv::Deallocate(unsigned char* mem) {
 134   return deallocate(mem);
 135 } /* end Deallocate */
 136 
 137 // Threads_lock NOT held, java_thread not protected by lock
 138 // java_thread - pre-checked
 139 // data - NULL is a valid value, must be checked
 140 jvmtiError
 141 JvmtiEnv::SetThreadLocalStorage(JavaThread* java_thread, const void* data) {
 142   JvmtiThreadState* state = java_thread->jvmti_thread_state();
 143   if (state == NULL) {
 144     if (data == NULL) {
 145       // leaving state unset same as data set to NULL
 146       return JVMTI_ERROR_NONE;
 147     }
 148     // otherwise, create the state
 149     state = JvmtiThreadState::state_for(java_thread);
 150     if (state == NULL) {
 151       return JVMTI_ERROR_THREAD_NOT_ALIVE;
 152     }
 153   }
 154   state->env_thread_state(this)->set_agent_thread_local_storage_data((void*)data);
 155   return JVMTI_ERROR_NONE;
 156 } /* end SetThreadLocalStorage */
 157 
 158 
 159 // Threads_lock NOT held
 160 // thread - NOT pre-checked
 161 // data_ptr - pre-checked for NULL
 162 jvmtiError
 163 JvmtiEnv::GetThreadLocalStorage(jthread thread, void** data_ptr) {
 164   JavaThread* current_thread = JavaThread::current();
 165   if (thread == NULL) {
 166     JvmtiThreadState* state = current_thread->jvmti_thread_state();
 167     *data_ptr = (state == NULL) ? NULL :
 168       state->env_thread_state(this)->get_agent_thread_local_storage_data();
 169   } else {
 170     // jvmti_GetThreadLocalStorage is "in native" and doesn't transition
 171     // the thread to _thread_in_vm. However, when the TLS for a thread
 172     // other than the current thread is required we need to transition
 173     // from native so as to resolve the jthread.
 174 
 175     ThreadInVMfromNative __tiv(current_thread);
 176     VM_ENTRY_BASE(jvmtiError, JvmtiEnv::GetThreadLocalStorage , current_thread)
 177     debug_only(VMNativeEntryWrapper __vew;)
 178 
 179     JavaThread* java_thread = NULL;
 180     ThreadsListHandle tlh(current_thread);
 181     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), thread, &java_thread, NULL);
 182     if (err != JVMTI_ERROR_NONE) {
 183       return err;
 184     }
 185 
 186     JvmtiThreadState* state = java_thread->jvmti_thread_state();
 187     *data_ptr = (state == NULL) ? NULL :
 188       state->env_thread_state(this)->get_agent_thread_local_storage_data();
 189   }
 190   return JVMTI_ERROR_NONE;
 191 } /* end GetThreadLocalStorage */
 192 
 193   //
 194   // Module functions
 195   //
 196 
 197 // module_count_ptr - pre-checked for NULL
 198 // modules_ptr - pre-checked for NULL
 199 jvmtiError
 200 JvmtiEnv::GetAllModules(jint* module_count_ptr, jobject** modules_ptr) {
 201     JvmtiModuleClosure jmc;
 202 
 203     return jmc.get_all_modules(this, module_count_ptr, modules_ptr);
 204 } /* end GetAllModules */
 205 
 206 
 207 // class_loader - NULL is a valid value, must be pre-checked
 208 // package_name - pre-checked for NULL
 209 // module_ptr - pre-checked for NULL
 210 jvmtiError
 211 JvmtiEnv::GetNamedModule(jobject class_loader, const char* package_name, jobject* module_ptr) {
 212   JavaThread* THREAD = JavaThread::current(); // pass to macros
 213   ResourceMark rm(THREAD);
 214 
 215   Handle h_loader (THREAD, JNIHandles::resolve(class_loader));
 216   // Check that loader is a subclass of java.lang.ClassLoader.
 217   if (h_loader.not_null() && !java_lang_ClassLoader::is_subclass(h_loader->klass())) {
 218     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 219   }
 220   jobject module = Modules::get_named_module(h_loader, package_name, THREAD);
 221   if (HAS_PENDING_EXCEPTION) {
 222     CLEAR_PENDING_EXCEPTION;
 223     return JVMTI_ERROR_INTERNAL; // unexpected exception
 224   }
 225   *module_ptr = module;
 226   return JVMTI_ERROR_NONE;
 227 } /* end GetNamedModule */
 228 
 229 
 230 // module - pre-checked for NULL
 231 // to_module - pre-checked for NULL
 232 jvmtiError
 233 JvmtiEnv::AddModuleReads(jobject module, jobject to_module) {
 234   JavaThread* THREAD = JavaThread::current();
 235 
 236   // check module
 237   Handle h_module(THREAD, JNIHandles::resolve(module));
 238   if (!java_lang_Module::is_instance(h_module())) {
 239     return JVMTI_ERROR_INVALID_MODULE;
 240   }
 241   // check to_module
 242   Handle h_to_module(THREAD, JNIHandles::resolve(to_module));
 243   if (!java_lang_Module::is_instance(h_to_module())) {
 244     return JVMTI_ERROR_INVALID_MODULE;
 245   }
 246   return JvmtiExport::add_module_reads(h_module, h_to_module, THREAD);
 247 } /* end AddModuleReads */
 248 
 249 
 250 // module - pre-checked for NULL
 251 // pkg_name - pre-checked for NULL
 252 // to_module - pre-checked for NULL
 253 jvmtiError
 254 JvmtiEnv::AddModuleExports(jobject module, const char* pkg_name, jobject to_module) {
 255   JavaThread* THREAD = JavaThread::current();
 256   Handle h_pkg = java_lang_String::create_from_str(pkg_name, THREAD);
 257 
 258   // check module
 259   Handle h_module(THREAD, JNIHandles::resolve(module));
 260   if (!java_lang_Module::is_instance(h_module())) {
 261     return JVMTI_ERROR_INVALID_MODULE;
 262   }
 263   // check to_module
 264   Handle h_to_module(THREAD, JNIHandles::resolve(to_module));
 265   if (!java_lang_Module::is_instance(h_to_module())) {
 266     return JVMTI_ERROR_INVALID_MODULE;
 267   }
 268   return JvmtiExport::add_module_exports(h_module, h_pkg, h_to_module, THREAD);
 269 } /* end AddModuleExports */
 270 
 271 
 272 // module - pre-checked for NULL
 273 // pkg_name - pre-checked for NULL
 274 // to_module - pre-checked for NULL
 275 jvmtiError
 276 JvmtiEnv::AddModuleOpens(jobject module, const char* pkg_name, jobject to_module) {
 277   JavaThread* THREAD = JavaThread::current();
 278   Handle h_pkg = java_lang_String::create_from_str(pkg_name, THREAD);
 279 
 280   // check module
 281   Handle h_module(THREAD, JNIHandles::resolve(module));
 282   if (!java_lang_Module::is_instance(h_module())) {
 283     return JVMTI_ERROR_INVALID_MODULE;
 284   }
 285   // check to_module
 286   Handle h_to_module(THREAD, JNIHandles::resolve(to_module));
 287   if (!java_lang_Module::is_instance(h_to_module())) {
 288     return JVMTI_ERROR_INVALID_MODULE;
 289   }
 290   return JvmtiExport::add_module_opens(h_module, h_pkg, h_to_module, THREAD);
 291 } /* end AddModuleOpens */
 292 
 293 
 294 // module - pre-checked for NULL
 295 // service - pre-checked for NULL
 296 jvmtiError
 297 JvmtiEnv::AddModuleUses(jobject module, jclass service) {
 298   JavaThread* THREAD = JavaThread::current();
 299 
 300   // check module
 301   Handle h_module(THREAD, JNIHandles::resolve(module));
 302   if (!java_lang_Module::is_instance(h_module())) {
 303     return JVMTI_ERROR_INVALID_MODULE;
 304   }
 305   // check service
 306   Handle h_service(THREAD, JNIHandles::resolve_external_guard(service));
 307   if (!java_lang_Class::is_instance(h_service()) ||
 308       java_lang_Class::is_primitive(h_service())) {
 309     return JVMTI_ERROR_INVALID_CLASS;
 310   }
 311   return JvmtiExport::add_module_uses(h_module, h_service, THREAD);
 312 } /* end AddModuleUses */
 313 
 314 
 315 // module - pre-checked for NULL
 316 // service - pre-checked for NULL
 317 // impl_class - pre-checked for NULL
 318 jvmtiError
 319 JvmtiEnv::AddModuleProvides(jobject module, jclass service, jclass impl_class) {
 320   JavaThread* THREAD = JavaThread::current();
 321 
 322   // check module
 323   Handle h_module(THREAD, JNIHandles::resolve(module));
 324   if (!java_lang_Module::is_instance(h_module())) {
 325     return JVMTI_ERROR_INVALID_MODULE;
 326   }
 327   // check service
 328   Handle h_service(THREAD, JNIHandles::resolve_external_guard(service));
 329   if (!java_lang_Class::is_instance(h_service()) ||
 330       java_lang_Class::is_primitive(h_service())) {
 331     return JVMTI_ERROR_INVALID_CLASS;
 332   }
 333   // check impl_class
 334   Handle h_impl_class(THREAD, JNIHandles::resolve_external_guard(impl_class));
 335   if (!java_lang_Class::is_instance(h_impl_class()) ||
 336       java_lang_Class::is_primitive(h_impl_class())) {
 337     return JVMTI_ERROR_INVALID_CLASS;
 338   }
 339   return JvmtiExport::add_module_provides(h_module, h_service, h_impl_class, THREAD);
 340 } /* end AddModuleProvides */
 341 
 342 // module - pre-checked for NULL
 343 // is_modifiable_class_ptr - pre-checked for NULL
 344 jvmtiError
 345 JvmtiEnv::IsModifiableModule(jobject module, jboolean* is_modifiable_module_ptr) {
 346   JavaThread* THREAD = JavaThread::current();
 347 
 348   // check module
 349   Handle h_module(THREAD, JNIHandles::resolve(module));
 350   if (!java_lang_Module::is_instance(h_module())) {
 351     return JVMTI_ERROR_INVALID_MODULE;
 352   }
 353 
 354   *is_modifiable_module_ptr = JNI_TRUE;
 355   return JVMTI_ERROR_NONE;
 356 } /* end IsModifiableModule */
 357 
 358 
 359   //
 360   // Class functions
 361   //
 362 
 363 // class_count_ptr - pre-checked for NULL
 364 // classes_ptr - pre-checked for NULL
 365 jvmtiError
 366 JvmtiEnv::GetLoadedClasses(jint* class_count_ptr, jclass** classes_ptr) {
 367   return JvmtiGetLoadedClasses::getLoadedClasses(this, class_count_ptr, classes_ptr);
 368 } /* end GetLoadedClasses */
 369 
 370 
 371 // initiating_loader - NULL is a valid value, must be checked
 372 // class_count_ptr - pre-checked for NULL
 373 // classes_ptr - pre-checked for NULL
 374 jvmtiError
 375 JvmtiEnv::GetClassLoaderClasses(jobject initiating_loader, jint* class_count_ptr, jclass** classes_ptr) {
 376   return JvmtiGetLoadedClasses::getClassLoaderClasses(this, initiating_loader,
 377                                                   class_count_ptr, classes_ptr);
 378 } /* end GetClassLoaderClasses */
 379 
 380 // k_mirror - may be primitive, this must be checked
 381 // is_modifiable_class_ptr - pre-checked for NULL
 382 jvmtiError
 383 JvmtiEnv::IsModifiableClass(oop k_mirror, jboolean* is_modifiable_class_ptr) {
 384   *is_modifiable_class_ptr = VM_RedefineClasses::is_modifiable_class(k_mirror)?
 385                                                        JNI_TRUE : JNI_FALSE;
 386   return JVMTI_ERROR_NONE;
 387 } /* end IsModifiableClass */
 388 
 389 // class_count - pre-checked to be greater than or equal to 0
 390 // classes - pre-checked for NULL
 391 jvmtiError
 392 JvmtiEnv::RetransformClasses(jint class_count, const jclass* classes) {
 393 //TODO: add locking
 394 
 395   int index;
 396   JavaThread* current_thread = JavaThread::current();
 397   ResourceMark rm(current_thread);
 398 
 399   jvmtiClassDefinition* class_definitions =
 400                             NEW_RESOURCE_ARRAY(jvmtiClassDefinition, class_count);
 401   NULL_CHECK(class_definitions, JVMTI_ERROR_OUT_OF_MEMORY);
 402 
 403   for (index = 0; index < class_count; index++) {
 404     HandleMark hm(current_thread);
 405 
 406     jclass jcls = classes[index];
 407     oop k_mirror = JNIHandles::resolve_external_guard(jcls);
 408     if (k_mirror == NULL) {
 409       return JVMTI_ERROR_INVALID_CLASS;
 410     }
 411     if (!k_mirror->is_a(SystemDictionary::Class_klass())) {
 412       return JVMTI_ERROR_INVALID_CLASS;
 413     }
 414 
 415     if (!VM_RedefineClasses::is_modifiable_class(k_mirror)) {
 416       return JVMTI_ERROR_UNMODIFIABLE_CLASS;
 417     }
 418 
 419     Klass* klass = java_lang_Class::as_Klass(k_mirror);
 420 
 421     jint status = klass->jvmti_class_status();
 422     if (status & (JVMTI_CLASS_STATUS_ERROR)) {
 423       return JVMTI_ERROR_INVALID_CLASS;
 424     }
 425 
 426     InstanceKlass* ik = InstanceKlass::cast(klass);
 427     if (ik->get_cached_class_file_bytes() == NULL) {
 428       // Not cached, we need to reconstitute the class file from the
 429       // VM representation. We don't attach the reconstituted class
 430       // bytes to the InstanceKlass here because they have not been
 431       // validated and we're not at a safepoint.
 432       JvmtiClassFileReconstituter reconstituter(ik);
 433       if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
 434         return reconstituter.get_error();
 435       }
 436 
 437       class_definitions[index].class_byte_count = (jint)reconstituter.class_file_size();
 438       class_definitions[index].class_bytes      = (unsigned char*)
 439                                                        reconstituter.class_file_bytes();
 440     } else {
 441       // it is cached, get it from the cache
 442       class_definitions[index].class_byte_count = ik->get_cached_class_file_len();
 443       class_definitions[index].class_bytes      = ik->get_cached_class_file_bytes();
 444     }
 445     class_definitions[index].klass              = jcls;
 446   }
 447   VM_RedefineClasses op(class_count, class_definitions, jvmti_class_load_kind_retransform);
 448   VMThread::execute(&op);
 449   return (op.check_error());
 450 } /* end RetransformClasses */
 451 
 452 
 453 // class_count - pre-checked to be greater than or equal to 0
 454 // class_definitions - pre-checked for NULL
 455 jvmtiError
 456 JvmtiEnv::RedefineClasses(jint class_count, const jvmtiClassDefinition* class_definitions) {
 457 //TODO: add locking
 458   VM_RedefineClasses op(class_count, class_definitions, jvmti_class_load_kind_redefine);
 459   VMThread::execute(&op);
 460   return (op.check_error());
 461 } /* end RedefineClasses */
 462 
 463 
 464   //
 465   // Object functions
 466   //
 467 
 468 // size_ptr - pre-checked for NULL
 469 jvmtiError
 470 JvmtiEnv::GetObjectSize(jobject object, jlong* size_ptr) {
 471   oop mirror = JNIHandles::resolve_external_guard(object);
 472   NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
 473   size_t obj_size = mirror->size();
 474   *size_ptr = (jlong)Universe::heap()->cell_size(obj_size) * wordSize;
 475   return JVMTI_ERROR_NONE;
 476 } /* end GetObjectSize */
 477 
 478   //
 479   // Method functions
 480   //
 481 
 482 // prefix - NULL is a valid value, must be checked
 483 jvmtiError
 484 JvmtiEnv::SetNativeMethodPrefix(const char* prefix) {
 485   return prefix == NULL?
 486               SetNativeMethodPrefixes(0, NULL) :
 487               SetNativeMethodPrefixes(1, (char**)&prefix);
 488 } /* end SetNativeMethodPrefix */
 489 
 490 
 491 // prefix_count - pre-checked to be greater than or equal to 0
 492 // prefixes - pre-checked for NULL
 493 jvmtiError
 494 JvmtiEnv::SetNativeMethodPrefixes(jint prefix_count, char** prefixes) {
 495   // Have to grab JVMTI thread state lock to be sure that some thread
 496   // isn't accessing the prefixes at the same time we are setting them.
 497   // No locks during VM bring-up.
 498   if (Threads::number_of_threads() == 0) {
 499     return set_native_method_prefixes(prefix_count, prefixes);
 500   } else {
 501     MutexLocker mu(JvmtiThreadState_lock);
 502     return set_native_method_prefixes(prefix_count, prefixes);
 503   }
 504 } /* end SetNativeMethodPrefixes */
 505 
 506   //
 507   // Event Management functions
 508   //
 509 
 510 // callbacks - NULL is a valid value, must be checked
 511 // size_of_callbacks - pre-checked to be greater than or equal to 0
 512 jvmtiError
 513 JvmtiEnv::SetEventCallbacks(const jvmtiEventCallbacks* callbacks, jint size_of_callbacks) {
 514   JvmtiEventController::set_event_callbacks(this, callbacks, size_of_callbacks);
 515   return JVMTI_ERROR_NONE;
 516 } /* end SetEventCallbacks */
 517 
 518 
 519 // event_thread - NULL is a valid value, must be checked
 520 jvmtiError
 521 JvmtiEnv::SetEventNotificationMode(jvmtiEventMode mode, jvmtiEvent event_type, jthread event_thread,   ...) {
 522   if (event_thread == NULL) {
 523     // Can be called at Agent_OnLoad() time with event_thread == NULL
 524     // when Thread::current() does not work yet so we cannot create a
 525     // ThreadsListHandle that is common to both thread-specific and
 526     // global code paths.
 527 
 528     // event_type must be valid
 529     if (!JvmtiEventController::is_valid_event_type(event_type)) {
 530       return JVMTI_ERROR_INVALID_EVENT_TYPE;
 531     }
 532 
 533     bool enabled = (mode == JVMTI_ENABLE);
 534 
 535     // assure that needed capabilities are present
 536     if (enabled && !JvmtiUtil::has_event_capability(event_type, get_capabilities())) {
 537       return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
 538     }
 539 
 540     if (event_type == JVMTI_EVENT_CLASS_FILE_LOAD_HOOK && enabled) {
 541       record_class_file_load_hook_enabled();
 542     }
 543 
 544     if (event_type == JVMTI_EVENT_SAMPLED_OBJECT_ALLOC) {
 545       if (enabled) {
 546         ThreadHeapSampler::enable();
 547       } else {
 548         ThreadHeapSampler::disable();
 549       }
 550     }
 551     JvmtiEventController::set_user_enabled(this, (JavaThread*) NULL, event_type, enabled);
 552   } else {
 553     // We have a specified event_thread.
 554     JavaThread* java_thread = NULL;
 555     ThreadsListHandle tlh;
 556     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), event_thread, &java_thread, NULL);
 557     if (err != JVMTI_ERROR_NONE) {
 558       return err;
 559     }
 560 
 561     // event_type must be valid
 562     if (!JvmtiEventController::is_valid_event_type(event_type)) {
 563       return JVMTI_ERROR_INVALID_EVENT_TYPE;
 564     }
 565 
 566     // global events cannot be controlled at thread level.
 567     if (JvmtiEventController::is_global_event(event_type)) {
 568       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 569     }
 570 
 571     bool enabled = (mode == JVMTI_ENABLE);
 572 
 573     // assure that needed capabilities are present
 574     if (enabled && !JvmtiUtil::has_event_capability(event_type, get_capabilities())) {
 575       return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
 576     }
 577 
 578     if (event_type == JVMTI_EVENT_CLASS_FILE_LOAD_HOOK && enabled) {
 579       record_class_file_load_hook_enabled();
 580     }
 581     JvmtiEventController::set_user_enabled(this, java_thread, event_type, enabled);
 582   }
 583 
 584   return JVMTI_ERROR_NONE;
 585 } /* end SetEventNotificationMode */
 586 
 587   //
 588   // Capability functions
 589   //
 590 
 591 // capabilities_ptr - pre-checked for NULL
 592 jvmtiError
 593 JvmtiEnv::GetPotentialCapabilities(jvmtiCapabilities* capabilities_ptr) {
 594   JvmtiManageCapabilities::get_potential_capabilities(get_capabilities(),
 595                                                       get_prohibited_capabilities(),
 596                                                       capabilities_ptr);
 597   return JVMTI_ERROR_NONE;
 598 } /* end GetPotentialCapabilities */
 599 
 600 
 601 // capabilities_ptr - pre-checked for NULL
 602 jvmtiError
 603 JvmtiEnv::AddCapabilities(const jvmtiCapabilities* capabilities_ptr) {
 604   return JvmtiManageCapabilities::add_capabilities(get_capabilities(),
 605                                                    get_prohibited_capabilities(),
 606                                                    capabilities_ptr,
 607                                                    get_capabilities());
 608 } /* end AddCapabilities */
 609 
 610 
 611 // capabilities_ptr - pre-checked for NULL
 612 jvmtiError
 613 JvmtiEnv::RelinquishCapabilities(const jvmtiCapabilities* capabilities_ptr) {
 614   JvmtiManageCapabilities::relinquish_capabilities(get_capabilities(), capabilities_ptr, get_capabilities());
 615   return JVMTI_ERROR_NONE;
 616 } /* end RelinquishCapabilities */
 617 
 618 
 619 // capabilities_ptr - pre-checked for NULL
 620 jvmtiError
 621 JvmtiEnv::GetCapabilities(jvmtiCapabilities* capabilities_ptr) {
 622   JvmtiManageCapabilities::copy_capabilities(get_capabilities(), capabilities_ptr);
 623   return JVMTI_ERROR_NONE;
 624 } /* end GetCapabilities */
 625 
 626   //
 627   // Class Loader Search functions
 628   //
 629 
 630 // segment - pre-checked for NULL
 631 jvmtiError
 632 JvmtiEnv::AddToBootstrapClassLoaderSearch(const char* segment) {
 633   jvmtiPhase phase = get_phase();
 634   if (phase == JVMTI_PHASE_ONLOAD) {
 635     Arguments::append_sysclasspath(segment);
 636     return JVMTI_ERROR_NONE;
 637   } else if (use_version_1_0_semantics()) {
 638     // This JvmtiEnv requested version 1.0 semantics and this function
 639     // is only allowed in the ONLOAD phase in version 1.0 so we need to
 640     // return an error here.
 641     return JVMTI_ERROR_WRONG_PHASE;
 642   } else if (phase == JVMTI_PHASE_LIVE) {
 643     // The phase is checked by the wrapper that called this function,
 644     // but this thread could be racing with the thread that is
 645     // terminating the VM so we check one more time.
 646 
 647     // create the zip entry
 648     ClassPathZipEntry* zip_entry = ClassLoader::create_class_path_zip_entry(segment, true);
 649     if (zip_entry == NULL) {
 650       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 651     }
 652 
 653     // lock the loader
 654     Thread* thread = Thread::current();
 655     HandleMark hm;
 656     Handle loader_lock = Handle(thread, SystemDictionary::system_loader_lock());
 657 
 658     ObjectLocker ol(loader_lock, thread);
 659 
 660     // add the jar file to the bootclasspath
 661     log_info(class, load)("opened: %s", zip_entry->name());
 662 #if INCLUDE_CDS
 663     ClassLoaderExt::append_boot_classpath(zip_entry);
 664 #else
 665     ClassLoader::add_to_boot_append_entries(zip_entry);
 666 #endif
 667     return JVMTI_ERROR_NONE;
 668   } else {
 669     return JVMTI_ERROR_WRONG_PHASE;
 670   }
 671 
 672 } /* end AddToBootstrapClassLoaderSearch */
 673 
 674 
 675 // segment - pre-checked for NULL
 676 jvmtiError
 677 JvmtiEnv::AddToSystemClassLoaderSearch(const char* segment) {
 678   jvmtiPhase phase = get_phase();
 679 
 680   if (phase == JVMTI_PHASE_ONLOAD) {
 681     for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
 682       if (strcmp("java.class.path", p->key()) == 0) {
 683         p->append_value(segment);
 684         break;
 685       }
 686     }
 687     return JVMTI_ERROR_NONE;
 688   } else if (phase == JVMTI_PHASE_LIVE) {
 689     // The phase is checked by the wrapper that called this function,
 690     // but this thread could be racing with the thread that is
 691     // terminating the VM so we check one more time.
 692     HandleMark hm;
 693 
 694     // create the zip entry (which will open the zip file and hence
 695     // check that the segment is indeed a zip file).
 696     ClassPathZipEntry* zip_entry = ClassLoader::create_class_path_zip_entry(segment, false);
 697     if (zip_entry == NULL) {
 698       return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 699     }
 700     delete zip_entry;   // no longer needed
 701 
 702     // lock the loader
 703     Thread* THREAD = Thread::current();
 704     Handle loader = Handle(THREAD, SystemDictionary::java_system_loader());
 705 
 706     ObjectLocker ol(loader, THREAD);
 707 
 708     // need the path as java.lang.String
 709     Handle path = java_lang_String::create_from_platform_dependent_str(segment, THREAD);
 710     if (HAS_PENDING_EXCEPTION) {
 711       CLEAR_PENDING_EXCEPTION;
 712       return JVMTI_ERROR_INTERNAL;
 713     }
 714 
 715     // Invoke the appendToClassPathForInstrumentation method - if the method
 716     // is not found it means the loader doesn't support adding to the class path
 717     // in the live phase.
 718     {
 719       JavaValue res(T_VOID);
 720       JavaCalls::call_special(&res,
 721                               loader,
 722                               loader->klass(),
 723                               vmSymbols::appendToClassPathForInstrumentation_name(),
 724                               vmSymbols::appendToClassPathForInstrumentation_signature(),
 725                               path,
 726                               THREAD);
 727       if (HAS_PENDING_EXCEPTION) {
 728         Symbol* ex_name = PENDING_EXCEPTION->klass()->name();
 729         CLEAR_PENDING_EXCEPTION;
 730 
 731         if (ex_name == vmSymbols::java_lang_NoSuchMethodError()) {
 732           return JVMTI_ERROR_CLASS_LOADER_UNSUPPORTED;
 733         } else {
 734           return JVMTI_ERROR_INTERNAL;
 735         }
 736       }
 737     }
 738 
 739     return JVMTI_ERROR_NONE;
 740   } else {
 741     return JVMTI_ERROR_WRONG_PHASE;
 742   }
 743 } /* end AddToSystemClassLoaderSearch */
 744 
 745   //
 746   // General functions
 747   //
 748 
 749 // phase_ptr - pre-checked for NULL
 750 jvmtiError
 751 JvmtiEnv::GetPhase(jvmtiPhase* phase_ptr) {
 752   *phase_ptr = phase();
 753   return JVMTI_ERROR_NONE;
 754 } /* end GetPhase */
 755 
 756 
 757 jvmtiError
 758 JvmtiEnv::DisposeEnvironment() {
 759   dispose();
 760   return JVMTI_ERROR_NONE;
 761 } /* end DisposeEnvironment */
 762 
 763 
 764 // data - NULL is a valid value, must be checked
 765 jvmtiError
 766 JvmtiEnv::SetEnvironmentLocalStorage(const void* data) {
 767   set_env_local_storage(data);
 768   return JVMTI_ERROR_NONE;
 769 } /* end SetEnvironmentLocalStorage */
 770 
 771 
 772 // data_ptr - pre-checked for NULL
 773 jvmtiError
 774 JvmtiEnv::GetEnvironmentLocalStorage(void** data_ptr) {
 775   *data_ptr = (void*)get_env_local_storage();
 776   return JVMTI_ERROR_NONE;
 777 } /* end GetEnvironmentLocalStorage */
 778 
 779 // version_ptr - pre-checked for NULL
 780 jvmtiError
 781 JvmtiEnv::GetVersionNumber(jint* version_ptr) {
 782   *version_ptr = JVMTI_VERSION;
 783   return JVMTI_ERROR_NONE;
 784 } /* end GetVersionNumber */
 785 
 786 
 787 // name_ptr - pre-checked for NULL
 788 jvmtiError
 789 JvmtiEnv::GetErrorName(jvmtiError error, char** name_ptr) {
 790   if (error < JVMTI_ERROR_NONE || error > JVMTI_ERROR_MAX) {
 791     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 792   }
 793   const char *name = JvmtiUtil::error_name(error);
 794   if (name == NULL) {
 795     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 796   }
 797   size_t len = strlen(name) + 1;
 798   jvmtiError err = allocate(len, (unsigned char**)name_ptr);
 799   if (err == JVMTI_ERROR_NONE) {
 800     memcpy(*name_ptr, name, len);
 801   }
 802   return err;
 803 } /* end GetErrorName */
 804 
 805 
 806 jvmtiError
 807 JvmtiEnv::SetVerboseFlag(jvmtiVerboseFlag flag, jboolean value) {
 808   LogLevelType level = value == 0 ? LogLevel::Off : LogLevel::Info;
 809   switch (flag) {
 810   case JVMTI_VERBOSE_OTHER:
 811     // ignore
 812     break;
 813   case JVMTI_VERBOSE_CLASS:
 814     LogConfiguration::configure_stdout(level, false, LOG_TAGS(class, unload));
 815     LogConfiguration::configure_stdout(level, false, LOG_TAGS(class, load));
 816     break;
 817   case JVMTI_VERBOSE_GC:
 818     if (value == 0) {
 819       LogConfiguration::configure_stdout(LogLevel::Off, true, LOG_TAGS(gc));
 820     } else {
 821       LogConfiguration::configure_stdout(LogLevel::Info, true, LOG_TAGS(gc));
 822     }
 823     break;
 824   case JVMTI_VERBOSE_JNI:
 825     PrintJNIResolving = value != 0;
 826     break;
 827   default:
 828     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
 829   };
 830   return JVMTI_ERROR_NONE;
 831 } /* end SetVerboseFlag */
 832 
 833 
 834 // format_ptr - pre-checked for NULL
 835 jvmtiError
 836 JvmtiEnv::GetJLocationFormat(jvmtiJlocationFormat* format_ptr) {
 837   *format_ptr = JVMTI_JLOCATION_JVMBCI;
 838   return JVMTI_ERROR_NONE;
 839 } /* end GetJLocationFormat */
 840 
 841   //
 842   // Thread functions
 843   //
 844 
 845 // Threads_lock NOT held
 846 // thread - NOT pre-checked
 847 // thread_state_ptr - pre-checked for NULL
 848 jvmtiError
 849 JvmtiEnv::GetThreadState(jthread thread, jint* thread_state_ptr) {
 850   JavaThread* current_thread = JavaThread::current();
 851   JavaThread* java_thread = NULL;
 852   oop thread_oop = NULL;
 853   ThreadsListHandle tlh(current_thread);
 854 
 855   if (thread == NULL) {
 856     java_thread = current_thread;
 857     thread_oop = java_thread->threadObj();
 858 
 859     if (thread_oop == NULL || !thread_oop->is_a(SystemDictionary::Thread_klass())) {
 860       return JVMTI_ERROR_INVALID_THREAD;
 861     }
 862   } else {
 863     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
 864     if (err != JVMTI_ERROR_NONE) {
 865       // We got an error code so we don't have a JavaThread *, but
 866       // only return an error from here if we didn't get a valid
 867       // thread_oop.
 868       if (thread_oop == NULL) {
 869         return err;
 870       }
 871       // We have a valid thread_oop so we can return some thread state.
 872     }
 873   }
 874 
 875   // get most state bits
 876   jint state = (jint)java_lang_Thread::get_thread_status(thread_oop);
 877 
 878   if (java_thread != NULL) {
 879     // We have a JavaThread* so add more state bits.
 880     JavaThreadState jts = java_thread->thread_state();
 881 
 882     if (java_thread->is_being_ext_suspended()) {
 883       state |= JVMTI_THREAD_STATE_SUSPENDED;
 884     }
 885     if (jts == _thread_in_native) {
 886       state |= JVMTI_THREAD_STATE_IN_NATIVE;
 887     }
 888     OSThread* osThread = java_thread->osthread();
 889     if (osThread != NULL && osThread->interrupted()) {
 890       state |= JVMTI_THREAD_STATE_INTERRUPTED;
 891     }
 892   }
 893 
 894   *thread_state_ptr = state;
 895   return JVMTI_ERROR_NONE;
 896 } /* end GetThreadState */
 897 
 898 
 899 // thread_ptr - pre-checked for NULL
 900 jvmtiError
 901 JvmtiEnv::GetCurrentThread(jthread* thread_ptr) {
 902   JavaThread* current_thread  = JavaThread::current();
 903   *thread_ptr = (jthread)JNIHandles::make_local(current_thread, current_thread->threadObj());
 904   return JVMTI_ERROR_NONE;
 905 } /* end GetCurrentThread */
 906 
 907 
 908 // threads_count_ptr - pre-checked for NULL
 909 // threads_ptr - pre-checked for NULL
 910 jvmtiError
 911 JvmtiEnv::GetAllThreads(jint* threads_count_ptr, jthread** threads_ptr) {
 912   int nthreads        = 0;
 913   Handle *thread_objs = NULL;
 914   ResourceMark rm;
 915   HandleMark hm;
 916 
 917   // enumerate threads (including agent threads)
 918   ThreadsListEnumerator tle(Thread::current(), true);
 919   nthreads = tle.num_threads();
 920   *threads_count_ptr = nthreads;
 921 
 922   if (nthreads == 0) {
 923     *threads_ptr = NULL;
 924     return JVMTI_ERROR_NONE;
 925   }
 926 
 927   thread_objs = NEW_RESOURCE_ARRAY(Handle, nthreads);
 928   NULL_CHECK(thread_objs, JVMTI_ERROR_OUT_OF_MEMORY);
 929 
 930   for (int i=0; i < nthreads; i++) {
 931     thread_objs[i] = Handle(tle.get_threadObj(i));
 932   }
 933 
 934   jthread *jthreads  = new_jthreadArray(nthreads, thread_objs);
 935   NULL_CHECK(jthreads, JVMTI_ERROR_OUT_OF_MEMORY);
 936 
 937   *threads_ptr = jthreads;
 938   return JVMTI_ERROR_NONE;
 939 } /* end GetAllThreads */
 940 
 941 
 942 // Threads_lock NOT held, java_thread not protected by lock
 943 // java_thread - pre-checked
 944 jvmtiError
 945 JvmtiEnv::SuspendThread(JavaThread* java_thread) {
 946   // don't allow hidden thread suspend request.
 947   if (java_thread->is_hidden_from_external_view()) {
 948     return (JVMTI_ERROR_NONE);
 949   }
 950 
 951   {
 952     MutexLockerEx ml(java_thread->SR_lock(), Mutex::_no_safepoint_check_flag);
 953     if (java_thread->is_external_suspend()) {
 954       // don't allow nested external suspend requests.
 955       return (JVMTI_ERROR_THREAD_SUSPENDED);
 956     }
 957     if (java_thread->is_exiting()) { // thread is in the process of exiting
 958       return (JVMTI_ERROR_THREAD_NOT_ALIVE);
 959     }
 960     java_thread->set_external_suspend();
 961   }
 962 
 963   if (!JvmtiSuspendControl::suspend(java_thread)) {
 964     // the thread was in the process of exiting
 965     return (JVMTI_ERROR_THREAD_NOT_ALIVE);
 966   }
 967   return JVMTI_ERROR_NONE;
 968 } /* end SuspendThread */
 969 
 970 
 971 // request_count - pre-checked to be greater than or equal to 0
 972 // request_list - pre-checked for NULL
 973 // results - pre-checked for NULL
 974 jvmtiError
 975 JvmtiEnv::SuspendThreadList(jint request_count, const jthread* request_list, jvmtiError* results) {
 976   int needSafepoint = 0;  // > 0 if we need a safepoint
 977   ThreadsListHandle tlh;
 978   for (int i = 0; i < request_count; i++) {
 979     JavaThread *java_thread = NULL;
 980     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), request_list[i], &java_thread, NULL);
 981     if (err != JVMTI_ERROR_NONE) {
 982       results[i] = err;
 983       continue;
 984     }
 985     // don't allow hidden thread suspend request.
 986     if (java_thread->is_hidden_from_external_view()) {
 987       results[i] = JVMTI_ERROR_NONE;  // indicate successful suspend
 988       continue;
 989     }
 990 
 991     {
 992       MutexLockerEx ml(java_thread->SR_lock(), Mutex::_no_safepoint_check_flag);
 993       if (java_thread->is_external_suspend()) {
 994         // don't allow nested external suspend requests.
 995         results[i] = JVMTI_ERROR_THREAD_SUSPENDED;
 996         continue;
 997       }
 998       if (java_thread->is_exiting()) { // thread is in the process of exiting
 999         results[i] = JVMTI_ERROR_THREAD_NOT_ALIVE;
1000         continue;
1001       }
1002       java_thread->set_external_suspend();
1003     }
1004     if (java_thread->thread_state() == _thread_in_native) {
1005       // We need to try and suspend native threads here. Threads in
1006       // other states will self-suspend on their next transition.
1007       if (!JvmtiSuspendControl::suspend(java_thread)) {
1008         // The thread was in the process of exiting. Force another
1009         // safepoint to make sure that this thread transitions.
1010         needSafepoint++;
1011         results[i] = JVMTI_ERROR_THREAD_NOT_ALIVE;
1012         continue;
1013       }
1014     } else {
1015       needSafepoint++;
1016     }
1017     results[i] = JVMTI_ERROR_NONE;  // indicate successful suspend
1018   }
1019   if (needSafepoint > 0) {
1020     VM_ThreadsSuspendJVMTI tsj;
1021     VMThread::execute(&tsj);
1022   }
1023   // per-thread suspend results returned via results parameter
1024   return JVMTI_ERROR_NONE;
1025 } /* end SuspendThreadList */
1026 
1027 
1028 // Threads_lock NOT held, java_thread not protected by lock
1029 // java_thread - pre-checked
1030 jvmtiError
1031 JvmtiEnv::ResumeThread(JavaThread* java_thread) {
1032   // don't allow hidden thread resume request.
1033   if (java_thread->is_hidden_from_external_view()) {
1034     return JVMTI_ERROR_NONE;
1035   }
1036 
1037   if (!java_thread->is_being_ext_suspended()) {
1038     return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1039   }
1040 
1041   if (!JvmtiSuspendControl::resume(java_thread)) {
1042     return JVMTI_ERROR_INTERNAL;
1043   }
1044   return JVMTI_ERROR_NONE;
1045 } /* end ResumeThread */
1046 
1047 
1048 // request_count - pre-checked to be greater than or equal to 0
1049 // request_list - pre-checked for NULL
1050 // results - pre-checked for NULL
1051 jvmtiError
1052 JvmtiEnv::ResumeThreadList(jint request_count, const jthread* request_list, jvmtiError* results) {
1053   ThreadsListHandle tlh;
1054   for (int i = 0; i < request_count; i++) {
1055     JavaThread* java_thread = NULL;
1056     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), request_list[i], &java_thread, NULL);
1057     if (err != JVMTI_ERROR_NONE) {
1058       results[i] = err;
1059       continue;
1060     }
1061     // don't allow hidden thread resume request.
1062     if (java_thread->is_hidden_from_external_view()) {
1063       results[i] = JVMTI_ERROR_NONE;  // indicate successful resume
1064       continue;
1065     }
1066     if (!java_thread->is_being_ext_suspended()) {
1067       results[i] = JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1068       continue;
1069     }
1070 
1071     if (!JvmtiSuspendControl::resume(java_thread)) {
1072       results[i] = JVMTI_ERROR_INTERNAL;
1073       continue;
1074     }
1075 
1076     results[i] = JVMTI_ERROR_NONE;  // indicate successful resume
1077   }
1078   // per-thread resume results returned via results parameter
1079   return JVMTI_ERROR_NONE;
1080 } /* end ResumeThreadList */
1081 
1082 
1083 // Threads_lock NOT held, java_thread not protected by lock
1084 // java_thread - pre-checked
1085 jvmtiError
1086 JvmtiEnv::StopThread(JavaThread* java_thread, jobject exception) {
1087   oop e = JNIHandles::resolve_external_guard(exception);
1088   NULL_CHECK(e, JVMTI_ERROR_NULL_POINTER);
1089 
1090   JavaThread::send_async_exception(java_thread->threadObj(), e);
1091 
1092   return JVMTI_ERROR_NONE;
1093 
1094 } /* end StopThread */
1095 
1096 
1097 // Threads_lock NOT held
1098 // thread - NOT pre-checked
1099 jvmtiError
1100 JvmtiEnv::InterruptThread(jthread thread) {
1101   // TODO: this is very similar to JVM_Interrupt(); share code in future
1102   JavaThread* current_thread  = JavaThread::current();
1103   JavaThread* java_thread = NULL;
1104   ThreadsListHandle tlh(current_thread);
1105   jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), thread, &java_thread, NULL);
1106   if (err != JVMTI_ERROR_NONE) {
1107     return err;
1108   }
1109 
1110   Thread::interrupt(java_thread);
1111 
1112   return JVMTI_ERROR_NONE;
1113 } /* end InterruptThread */
1114 
1115 
1116 // Threads_lock NOT held
1117 // thread - NOT pre-checked
1118 // info_ptr - pre-checked for NULL
1119 jvmtiError
1120 JvmtiEnv::GetThreadInfo(jthread thread, jvmtiThreadInfo* info_ptr) {
1121   ResourceMark rm;
1122   HandleMark hm;
1123 
1124   JavaThread* current_thread = JavaThread::current();
1125   ThreadsListHandle tlh(current_thread);
1126 
1127   // if thread is NULL the current thread is used
1128   oop thread_oop = NULL;
1129   if (thread == NULL) {
1130     thread_oop = current_thread->threadObj();
1131     if (thread_oop == NULL || !thread_oop->is_a(SystemDictionary::Thread_klass())) {
1132       return JVMTI_ERROR_INVALID_THREAD;
1133     }
1134   } else {
1135     JavaThread* java_thread = NULL;
1136     jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
1137     if (err != JVMTI_ERROR_NONE) {
1138       // We got an error code so we don't have a JavaThread *, but
1139       // only return an error from here if we didn't get a valid
1140       // thread_oop.
1141       if (thread_oop == NULL) {
1142         return err;
1143       }
1144       // We have a valid thread_oop so we can return some thread info.
1145     }
1146   }
1147 
1148   Handle thread_obj(current_thread, thread_oop);
1149   Handle name;
1150   ThreadPriority priority;
1151   Handle     thread_group;
1152   Handle context_class_loader;
1153   bool          is_daemon;
1154 
1155   { MutexLocker mu(Threads_lock);
1156 
1157     name = Handle(current_thread, java_lang_Thread::name(thread_obj()));
1158     priority = java_lang_Thread::priority(thread_obj());
1159     thread_group = Handle(current_thread, java_lang_Thread::threadGroup(thread_obj()));
1160     is_daemon = java_lang_Thread::is_daemon(thread_obj());
1161 
1162     oop loader = java_lang_Thread::context_class_loader(thread_obj());
1163     context_class_loader = Handle(current_thread, loader);
1164   }
1165   { const char *n;
1166 
1167     if (name() != NULL) {
1168       n = java_lang_String::as_utf8_string(name());
1169     } else {
1170       int utf8_length = 0;
1171       n = UNICODE::as_utf8((jchar*) NULL, utf8_length);
1172     }
1173 
1174     info_ptr->name = (char *) jvmtiMalloc(strlen(n)+1);
1175     if (info_ptr->name == NULL)
1176       return JVMTI_ERROR_OUT_OF_MEMORY;
1177 
1178     strcpy(info_ptr->name, n);
1179   }
1180   info_ptr->is_daemon = is_daemon;
1181   info_ptr->priority  = priority;
1182 
1183   info_ptr->context_class_loader = (context_class_loader.is_null()) ? NULL :
1184                                      jni_reference(context_class_loader);
1185   info_ptr->thread_group = jni_reference(thread_group);
1186 
1187   return JVMTI_ERROR_NONE;
1188 } /* end GetThreadInfo */
1189 
1190 
1191 // Threads_lock NOT held, java_thread not protected by lock
1192 // java_thread - pre-checked
1193 // owned_monitor_count_ptr - pre-checked for NULL
1194 // owned_monitors_ptr - pre-checked for NULL
1195 jvmtiError
1196 JvmtiEnv::GetOwnedMonitorInfo(JavaThread* java_thread, jint* owned_monitor_count_ptr, jobject** owned_monitors_ptr) {
1197   jvmtiError err = JVMTI_ERROR_NONE;
1198   JavaThread* calling_thread = JavaThread::current();
1199 
1200   // growable array of jvmti monitors info on the C-heap
1201   GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list =
1202       new (ResourceObj::C_HEAP, mtInternal) GrowableArray<jvmtiMonitorStackDepthInfo*>(1, true);
1203 
1204   // It is only safe to perform the direct operation on the current
1205   // thread. All other usage needs to use a vm-safepoint-op for safety.
1206   if (java_thread == calling_thread) {
1207     err = get_owned_monitors(calling_thread, java_thread, owned_monitors_list);
1208   } else {
1209     // JVMTI get monitors info at safepoint. Do not require target thread to
1210     // be suspended.
1211     VM_GetOwnedMonitorInfo op(this, calling_thread, java_thread, owned_monitors_list);
1212     VMThread::execute(&op);
1213     err = op.result();
1214   }
1215   jint owned_monitor_count = owned_monitors_list->length();
1216   if (err == JVMTI_ERROR_NONE) {
1217     if ((err = allocate(owned_monitor_count * sizeof(jobject *),
1218                       (unsigned char**)owned_monitors_ptr)) == JVMTI_ERROR_NONE) {
1219       // copy into the returned array
1220       for (int i = 0; i < owned_monitor_count; i++) {
1221         (*owned_monitors_ptr)[i] =
1222           ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(i))->monitor;
1223       }
1224       *owned_monitor_count_ptr = owned_monitor_count;
1225     }
1226   }
1227   // clean up.
1228   for (int i = 0; i < owned_monitor_count; i++) {
1229     deallocate((unsigned char*)owned_monitors_list->at(i));
1230   }
1231   delete owned_monitors_list;
1232 
1233   return err;
1234 } /* end GetOwnedMonitorInfo */
1235 
1236 
1237 // Threads_lock NOT held, java_thread not protected by lock
1238 // java_thread - pre-checked
1239 // monitor_info_count_ptr - pre-checked for NULL
1240 // monitor_info_ptr - pre-checked for NULL
1241 jvmtiError
1242 JvmtiEnv::GetOwnedMonitorStackDepthInfo(JavaThread* java_thread, jint* monitor_info_count_ptr, jvmtiMonitorStackDepthInfo** monitor_info_ptr) {
1243   jvmtiError err = JVMTI_ERROR_NONE;
1244   JavaThread* calling_thread  = JavaThread::current();
1245 
1246   // growable array of jvmti monitors info on the C-heap
1247   GrowableArray<jvmtiMonitorStackDepthInfo*> *owned_monitors_list =
1248          new (ResourceObj::C_HEAP, mtInternal) GrowableArray<jvmtiMonitorStackDepthInfo*>(1, true);
1249 
1250   // It is only safe to perform the direct operation on the current
1251   // thread. All other usage needs to use a vm-safepoint-op for safety.
1252   if (java_thread == calling_thread) {
1253     err = get_owned_monitors(calling_thread, java_thread, owned_monitors_list);
1254   } else {
1255     // JVMTI get owned monitors info at safepoint. Do not require target thread to
1256     // be suspended.
1257     VM_GetOwnedMonitorInfo op(this, calling_thread, java_thread, owned_monitors_list);
1258     VMThread::execute(&op);
1259     err = op.result();
1260   }
1261 
1262   jint owned_monitor_count = owned_monitors_list->length();
1263   if (err == JVMTI_ERROR_NONE) {
1264     if ((err = allocate(owned_monitor_count * sizeof(jvmtiMonitorStackDepthInfo),
1265                       (unsigned char**)monitor_info_ptr)) == JVMTI_ERROR_NONE) {
1266       // copy to output array.
1267       for (int i = 0; i < owned_monitor_count; i++) {
1268         (*monitor_info_ptr)[i].monitor =
1269           ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(i))->monitor;
1270         (*monitor_info_ptr)[i].stack_depth =
1271           ((jvmtiMonitorStackDepthInfo*)owned_monitors_list->at(i))->stack_depth;
1272       }
1273     }
1274     *monitor_info_count_ptr = owned_monitor_count;
1275   }
1276 
1277   // clean up.
1278   for (int i = 0; i < owned_monitor_count; i++) {
1279     deallocate((unsigned char*)owned_monitors_list->at(i));
1280   }
1281   delete owned_monitors_list;
1282 
1283   return err;
1284 } /* end GetOwnedMonitorStackDepthInfo */
1285 
1286 
1287 // Threads_lock NOT held, java_thread not protected by lock
1288 // java_thread - pre-checked
1289 // monitor_ptr - pre-checked for NULL
1290 jvmtiError
1291 JvmtiEnv::GetCurrentContendedMonitor(JavaThread* java_thread, jobject* monitor_ptr) {
1292   jvmtiError err = JVMTI_ERROR_NONE;
1293   JavaThread* calling_thread  = JavaThread::current();
1294 
1295   // It is only safe to perform the direct operation on the current
1296   // thread. All other usage needs to use a vm-safepoint-op for safety.
1297   if (java_thread == calling_thread) {
1298     err = get_current_contended_monitor(calling_thread, java_thread, monitor_ptr);
1299   } else {
1300     // get contended monitor information at safepoint.
1301     VM_GetCurrentContendedMonitor op(this, calling_thread, java_thread, monitor_ptr);
1302     VMThread::execute(&op);
1303     err = op.result();
1304   }
1305   return err;
1306 } /* end GetCurrentContendedMonitor */
1307 
1308 
1309 // Threads_lock NOT held
1310 // thread - NOT pre-checked
1311 // proc - pre-checked for NULL
1312 // arg - NULL is a valid value, must be checked
1313 jvmtiError
1314 JvmtiEnv::RunAgentThread(jthread thread, jvmtiStartFunction proc, const void* arg, jint priority) {
1315   JavaThread* current_thread = JavaThread::current();
1316 
1317   JavaThread* java_thread = NULL;
1318   oop thread_oop = NULL;
1319   ThreadsListHandle tlh(current_thread);
1320   jvmtiError err = JvmtiExport::cv_external_thread_to_JavaThread(tlh.list(), thread, &java_thread, &thread_oop);
1321   if (err != JVMTI_ERROR_NONE) {
1322     // We got an error code so we don't have a JavaThread *, but
1323     // only return an error from here if we didn't get a valid
1324     // thread_oop.
1325     if (thread_oop == NULL) {
1326       return err;
1327     }
1328     // We have a valid thread_oop.
1329   }
1330 
1331   if (java_thread != NULL) {
1332     // 'thread' refers to an existing JavaThread.
1333     return JVMTI_ERROR_INVALID_THREAD;
1334   }
1335 
1336   if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) {
1337     return JVMTI_ERROR_INVALID_PRIORITY;
1338   }
1339 
1340   Handle thread_hndl(current_thread, thread_oop);
1341   {
1342     MutexLocker mu(Threads_lock); // grab Threads_lock
1343 
1344     JvmtiAgentThread *new_thread = new JvmtiAgentThread(this, proc, arg);
1345 
1346     // At this point it may be possible that no osthread was created for the
1347     // JavaThread due to lack of memory.
1348     if (new_thread == NULL || new_thread->osthread() == NULL) {
1349       if (new_thread != NULL) {
1350         new_thread->smr_delete();
1351       }
1352       return JVMTI_ERROR_OUT_OF_MEMORY;
1353     }
1354 
1355     java_lang_Thread::set_thread(thread_hndl(), new_thread);
1356     java_lang_Thread::set_priority(thread_hndl(), (ThreadPriority)priority);
1357     java_lang_Thread::set_daemon(thread_hndl());
1358 
1359     new_thread->set_threadObj(thread_hndl());
1360     Threads::add(new_thread);
1361     Thread::start(new_thread);
1362   } // unlock Threads_lock
1363 
1364   return JVMTI_ERROR_NONE;
1365 } /* end RunAgentThread */
1366 
1367   //
1368   // Thread Group functions
1369   //
1370 
1371 // group_count_ptr - pre-checked for NULL
1372 // groups_ptr - pre-checked for NULL
1373 jvmtiError
1374 JvmtiEnv::GetTopThreadGroups(jint* group_count_ptr, jthreadGroup** groups_ptr) {
1375   JavaThread* current_thread = JavaThread::current();
1376 
1377   // Only one top level thread group now.
1378   *group_count_ptr = 1;
1379 
1380   // Allocate memory to store global-refs to the thread groups.
1381   // Assume this area is freed by caller.
1382   *groups_ptr = (jthreadGroup *) jvmtiMalloc((sizeof(jthreadGroup)) * (*group_count_ptr));
1383 
1384   NULL_CHECK(*groups_ptr, JVMTI_ERROR_OUT_OF_MEMORY);
1385 
1386   // Convert oop to Handle, then convert Handle to global-ref.
1387   {
1388     HandleMark hm(current_thread);
1389     Handle system_thread_group(current_thread, Universe::system_thread_group());
1390     *groups_ptr[0] = jni_reference(system_thread_group);
1391   }
1392 
1393   return JVMTI_ERROR_NONE;
1394 } /* end GetTopThreadGroups */
1395 
1396 
1397 // info_ptr - pre-checked for NULL
1398 jvmtiError
1399 JvmtiEnv::GetThreadGroupInfo(jthreadGroup group, jvmtiThreadGroupInfo* info_ptr) {
1400   ResourceMark rm;
1401   HandleMark hm;
1402 
1403   JavaThread* current_thread = JavaThread::current();
1404 
1405   Handle group_obj (current_thread, JNIHandles::resolve_external_guard(group));
1406   NULL_CHECK(group_obj(), JVMTI_ERROR_INVALID_THREAD_GROUP);
1407 
1408   const char* name;
1409   Handle parent_group;
1410   bool is_daemon;
1411   ThreadPriority max_priority;
1412 
1413   { MutexLocker mu(Threads_lock);
1414 
1415     name         = java_lang_ThreadGroup::name(group_obj());
1416     parent_group = Handle(current_thread, java_lang_ThreadGroup::parent(group_obj()));
1417     is_daemon    = java_lang_ThreadGroup::is_daemon(group_obj());
1418     max_priority = java_lang_ThreadGroup::maxPriority(group_obj());
1419   }
1420 
1421   info_ptr->is_daemon    = is_daemon;
1422   info_ptr->max_priority = max_priority;
1423   info_ptr->parent       = jni_reference(parent_group);
1424 
1425   if (name != NULL) {
1426     info_ptr->name = (char*)jvmtiMalloc(strlen(name)+1);
1427     NULL_CHECK(info_ptr->name, JVMTI_ERROR_OUT_OF_MEMORY);
1428     strcpy(info_ptr->name, name);
1429   } else {
1430     info_ptr->name = NULL;
1431   }
1432 
1433   return JVMTI_ERROR_NONE;
1434 } /* end GetThreadGroupInfo */
1435 
1436 
1437 // thread_count_ptr - pre-checked for NULL
1438 // threads_ptr - pre-checked for NULL
1439 // group_count_ptr - pre-checked for NULL
1440 // groups_ptr - pre-checked for NULL
1441 jvmtiError
1442 JvmtiEnv::GetThreadGroupChildren(jthreadGroup group, jint* thread_count_ptr, jthread** threads_ptr, jint* group_count_ptr, jthreadGroup** groups_ptr) {
1443   JavaThread* current_thread = JavaThread::current();
1444   oop group_obj = (oop) JNIHandles::resolve_external_guard(group);
1445   NULL_CHECK(group_obj, JVMTI_ERROR_INVALID_THREAD_GROUP);
1446 
1447   Handle *thread_objs = NULL;
1448   Handle *group_objs  = NULL;
1449   int nthreads = 0;
1450   int ngroups = 0;
1451   int hidden_threads = 0;
1452 
1453   ResourceMark rm(current_thread);
1454   HandleMark hm(current_thread);
1455 
1456   Handle group_hdl(current_thread, group_obj);
1457 
1458   { // Cannot allow thread or group counts to change.
1459     MutexLocker mu(Threads_lock);
1460 
1461     nthreads = java_lang_ThreadGroup::nthreads(group_hdl());
1462     ngroups  = java_lang_ThreadGroup::ngroups(group_hdl());
1463 
1464     if (nthreads > 0) {
1465       ThreadsListHandle tlh(current_thread);
1466       objArrayOop threads = java_lang_ThreadGroup::threads(group_hdl());
1467       assert(nthreads <= threads->length(), "too many threads");
1468       thread_objs = NEW_RESOURCE_ARRAY(Handle,nthreads);
1469       for (int i=0, j=0; i<nthreads; i++) {
1470         oop thread_obj = threads->obj_at(i);
1471         assert(thread_obj != NULL, "thread_obj is NULL");
1472         JavaThread *java_thread = NULL;
1473         jvmtiError err = JvmtiExport::cv_oop_to_JavaThread(tlh.list(), thread_obj, &java_thread);
1474         if (err == JVMTI_ERROR_NONE) {
1475           // Have a valid JavaThread*.
1476           if (java_thread->is_hidden_from_external_view()) {
1477             // Filter out hidden java threads.
1478             hidden_threads++;
1479             continue;
1480           }
1481         } else {
1482           // We couldn't convert thread_obj into a JavaThread*.
1483           if (err == JVMTI_ERROR_INVALID_THREAD) {
1484             // The thread_obj does not refer to a java.lang.Thread object
1485             // so skip it.
1486             hidden_threads++;
1487             continue;
1488           }
1489           // We have a valid thread_obj, but no JavaThread*; the caller
1490           // can still have limited use for the thread_obj.
1491         }
1492         thread_objs[j++] = Handle(current_thread, thread_obj);
1493       }
1494       nthreads -= hidden_threads;
1495     } // ThreadsListHandle is destroyed here.
1496 
1497     if (ngroups > 0) {
1498       objArrayOop groups = java_lang_ThreadGroup::groups(group_hdl());
1499       assert(ngroups <= groups->length(), "too many groups");
1500       group_objs = NEW_RESOURCE_ARRAY(Handle,ngroups);
1501       for (int i=0; i<ngroups; i++) {
1502         oop group_obj = groups->obj_at(i);
1503         assert(group_obj != NULL, "group_obj != NULL");
1504         group_objs[i] = Handle(current_thread, group_obj);
1505       }
1506     }
1507   }
1508 
1509   // have to make global handles outside of Threads_lock
1510   *group_count_ptr  = ngroups;
1511   *thread_count_ptr = nthreads;
1512   *threads_ptr     = new_jthreadArray(nthreads, thread_objs);
1513   *groups_ptr      = new_jthreadGroupArray(ngroups, group_objs);
1514   if ((nthreads > 0) && (*threads_ptr == NULL)) {
1515     return JVMTI_ERROR_OUT_OF_MEMORY;
1516   }
1517   if ((ngroups > 0) && (*groups_ptr == NULL)) {
1518     return JVMTI_ERROR_OUT_OF_MEMORY;
1519   }
1520 
1521   return JVMTI_ERROR_NONE;
1522 } /* end GetThreadGroupChildren */
1523 
1524 
1525   //
1526   // Stack Frame functions
1527   //
1528 
1529 // Threads_lock NOT held, java_thread not protected by lock
1530 // java_thread - pre-checked
1531 // max_frame_count - pre-checked to be greater than or equal to 0
1532 // frame_buffer - pre-checked for NULL
1533 // count_ptr - pre-checked for NULL
1534 jvmtiError
1535 JvmtiEnv::GetStackTrace(JavaThread* java_thread, jint start_depth, jint max_frame_count, jvmtiFrameInfo* frame_buffer, jint* count_ptr) {
1536   jvmtiError err = JVMTI_ERROR_NONE;
1537 
1538   // It is only safe to perform the direct operation on the current
1539   // thread. All other usage needs to use a vm-safepoint-op for safety.
1540   if (java_thread == JavaThread::current()) {
1541     err = get_stack_trace(java_thread, start_depth, max_frame_count, frame_buffer, count_ptr);
1542   } else {
1543     // JVMTI get stack trace at safepoint. Do not require target thread to
1544     // be suspended.
1545     VM_GetStackTrace op(this, java_thread, start_depth, max_frame_count, frame_buffer, count_ptr);
1546     VMThread::execute(&op);
1547     err = op.result();
1548   }
1549 
1550   return err;
1551 } /* end GetStackTrace */
1552 
1553 
1554 // max_frame_count - pre-checked to be greater than or equal to 0
1555 // stack_info_ptr - pre-checked for NULL
1556 // thread_count_ptr - pre-checked for NULL
1557 jvmtiError
1558 JvmtiEnv::GetAllStackTraces(jint max_frame_count, jvmtiStackInfo** stack_info_ptr, jint* thread_count_ptr) {
1559   jvmtiError err = JVMTI_ERROR_NONE;
1560   JavaThread* calling_thread = JavaThread::current();
1561 
1562   // JVMTI get stack traces at safepoint.
1563   VM_GetAllStackTraces op(this, calling_thread, max_frame_count);
1564   VMThread::execute(&op);
1565   *thread_count_ptr = op.final_thread_count();
1566   *stack_info_ptr = op.stack_info();
1567   err = op.result();
1568   return err;
1569 } /* end GetAllStackTraces */
1570 
1571 
1572 // thread_count - pre-checked to be greater than or equal to 0
1573 // thread_list - pre-checked for NULL
1574 // max_frame_count - pre-checked to be greater than or equal to 0
1575 // stack_info_ptr - pre-checked for NULL
1576 jvmtiError
1577 JvmtiEnv::GetThreadListStackTraces(jint thread_count, const jthread* thread_list, jint max_frame_count, jvmtiStackInfo** stack_info_ptr) {
1578   jvmtiError err = JVMTI_ERROR_NONE;
1579   // JVMTI get stack traces at safepoint.
1580   VM_GetThreadListStackTraces op(this, thread_count, thread_list, max_frame_count);
1581   VMThread::execute(&op);
1582   err = op.result();
1583   if (err == JVMTI_ERROR_NONE) {
1584     *stack_info_ptr = op.stack_info();
1585   }
1586   return err;
1587 } /* end GetThreadListStackTraces */
1588 
1589 
1590 // Threads_lock NOT held, java_thread not protected by lock
1591 // java_thread - pre-checked
1592 // count_ptr - pre-checked for NULL
1593 jvmtiError
1594 JvmtiEnv::GetFrameCount(JavaThread* java_thread, jint* count_ptr) {
1595   jvmtiError err = JVMTI_ERROR_NONE;
1596 
1597   // retrieve or create JvmtiThreadState.
1598   JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
1599   if (state == NULL) {
1600     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1601   }
1602 
1603   // It is only safe to perform the direct operation on the current
1604   // thread. All other usage needs to use a vm-safepoint-op for safety.
1605   if (java_thread == JavaThread::current()) {
1606     err = get_frame_count(state, count_ptr);
1607   } else {
1608     // get java stack frame count at safepoint.
1609     VM_GetFrameCount op(this, state, count_ptr);
1610     VMThread::execute(&op);
1611     err = op.result();
1612   }
1613   return err;
1614 } /* end GetFrameCount */
1615 
1616 
1617 // Threads_lock NOT held, java_thread not protected by lock
1618 // java_thread - pre-checked
1619 jvmtiError
1620 JvmtiEnv::PopFrame(JavaThread* java_thread) {
1621   JavaThread* current_thread  = JavaThread::current();
1622   HandleMark hm(current_thread);
1623   uint32_t debug_bits = 0;
1624 
1625   // retrieve or create the state
1626   JvmtiThreadState* state = JvmtiThreadState::state_for(java_thread);
1627   if (state == NULL) {
1628     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1629   }
1630 
1631   // Check if java_thread is fully suspended
1632   if (!java_thread->is_thread_fully_suspended(true /* wait for suspend completion */, &debug_bits)) {
1633     return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1634   }
1635   // Check to see if a PopFrame was already in progress
1636   if (java_thread->popframe_condition() != JavaThread::popframe_inactive) {
1637     // Probably possible for JVMTI clients to trigger this, but the
1638     // JPDA backend shouldn't allow this to happen
1639     return JVMTI_ERROR_INTERNAL;
1640   }
1641 
1642   {
1643     // Was workaround bug
1644     //    4812902: popFrame hangs if the method is waiting at a synchronize
1645     // Catch this condition and return an error to avoid hanging.
1646     // Now JVMTI spec allows an implementation to bail out with an opaque frame error.
1647     OSThread* osThread = java_thread->osthread();
1648     if (osThread->get_state() == MONITOR_WAIT) {
1649       return JVMTI_ERROR_OPAQUE_FRAME;
1650     }
1651   }
1652 
1653   {
1654     ResourceMark rm(current_thread);
1655     // Check if there are more than one Java frame in this thread, that the top two frames
1656     // are Java (not native) frames, and that there is no intervening VM frame
1657     int frame_count = 0;
1658     bool is_interpreted[2];
1659     intptr_t *frame_sp[2];
1660     // The 2-nd arg of constructor is needed to stop iterating at java entry frame.
1661     for (vframeStream vfs(java_thread, true); !vfs.at_end(); vfs.next()) {
1662       methodHandle mh(current_thread, vfs.method());
1663       if (mh->is_native()) return(JVMTI_ERROR_OPAQUE_FRAME);
1664       is_interpreted[frame_count] = vfs.is_interpreted_frame();
1665       frame_sp[frame_count] = vfs.frame_id();
1666       if (++frame_count > 1) break;
1667     }
1668     if (frame_count < 2)  {
1669       // We haven't found two adjacent non-native Java frames on the top.
1670       // There can be two situations here:
1671       //  1. There are no more java frames
1672       //  2. Two top java frames are separated by non-java native frames
1673       if(vframeFor(java_thread, 1) == NULL) {
1674         return JVMTI_ERROR_NO_MORE_FRAMES;
1675       } else {
1676         // Intervening non-java native or VM frames separate java frames.
1677         // Current implementation does not support this. See bug #5031735.
1678         // In theory it is possible to pop frames in such cases.
1679         return JVMTI_ERROR_OPAQUE_FRAME;
1680       }
1681     }
1682 
1683     // If any of the top 2 frames is a compiled one, need to deoptimize it
1684     for (int i = 0; i < 2; i++) {
1685       if (!is_interpreted[i]) {
1686         Deoptimization::deoptimize_frame(java_thread, frame_sp[i]);
1687       }
1688     }
1689 
1690     // Update the thread state to reflect that the top frame is popped
1691     // so that cur_stack_depth is maintained properly and all frameIDs
1692     // are invalidated.
1693     // The current frame will be popped later when the suspended thread
1694     // is resumed and right before returning from VM to Java.
1695     // (see call_VM_base() in assembler_<cpu>.cpp).
1696 
1697     // It's fine to update the thread state here because no JVMTI events
1698     // shall be posted for this PopFrame.
1699 
1700     // It is only safe to perform the direct operation on the current
1701     // thread. All other usage needs to use a vm-safepoint-op for safety.
1702     if (java_thread == JavaThread::current()) {
1703       state->update_for_pop_top_frame();
1704     } else {
1705       VM_UpdateForPopTopFrame op(state);
1706       VMThread::execute(&op);
1707       jvmtiError err = op.result();
1708       if (err != JVMTI_ERROR_NONE) {
1709         return err;
1710       }
1711     }
1712 
1713     java_thread->set_popframe_condition(JavaThread::popframe_pending_bit);
1714     // Set pending step flag for this popframe and it is cleared when next
1715     // step event is posted.
1716     state->set_pending_step_for_popframe();
1717   }
1718 
1719   return JVMTI_ERROR_NONE;
1720 } /* end PopFrame */
1721 
1722 
1723 // Threads_lock NOT held, java_thread not protected by lock
1724 // java_thread - pre-checked
1725 // java_thread - unchecked
1726 // depth - pre-checked as non-negative
1727 // method_ptr - pre-checked for NULL
1728 // location_ptr - pre-checked for NULL
1729 jvmtiError
1730 JvmtiEnv::GetFrameLocation(JavaThread* java_thread, jint depth, jmethodID* method_ptr, jlocation* location_ptr) {
1731   jvmtiError err = JVMTI_ERROR_NONE;
1732 
1733   // It is only safe to perform the direct operation on the current
1734   // thread. All other usage needs to use a vm-safepoint-op for safety.
1735   if (java_thread == JavaThread::current()) {
1736     err = get_frame_location(java_thread, depth, method_ptr, location_ptr);
1737   } else {
1738     // JVMTI get java stack frame location at safepoint.
1739     VM_GetFrameLocation op(this, java_thread, depth, method_ptr, location_ptr);
1740     VMThread::execute(&op);
1741     err = op.result();
1742   }
1743   return err;
1744 } /* end GetFrameLocation */
1745 
1746 
1747 // Threads_lock NOT held, java_thread not protected by lock
1748 // java_thread - pre-checked
1749 // java_thread - unchecked
1750 // depth - pre-checked as non-negative
1751 jvmtiError
1752 JvmtiEnv::NotifyFramePop(JavaThread* java_thread, jint depth) {
1753   jvmtiError err = JVMTI_ERROR_NONE;
1754   ResourceMark rm;
1755   uint32_t debug_bits = 0;
1756 
1757   JvmtiThreadState *state = JvmtiThreadState::state_for(java_thread);
1758   if (state == NULL) {
1759     return JVMTI_ERROR_THREAD_NOT_ALIVE;
1760   }
1761 
1762   if (!java_thread->is_thread_fully_suspended(true, &debug_bits)) {
1763     return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
1764   }
1765 
1766   if (TraceJVMTICalls) {
1767     JvmtiSuspendControl::print();
1768   }
1769 
1770   vframe *vf = vframeFor(java_thread, depth);
1771   if (vf == NULL) {
1772     return JVMTI_ERROR_NO_MORE_FRAMES;
1773   }
1774 
1775   if (!vf->is_java_frame() || ((javaVFrame*) vf)->method()->is_native()) {
1776     return JVMTI_ERROR_OPAQUE_FRAME;
1777   }
1778 
1779   assert(vf->frame_pointer() != NULL, "frame pointer mustn't be NULL");
1780 
1781   // It is only safe to perform the direct operation on the current
1782   // thread. All other usage needs to use a vm-safepoint-op for safety.
1783   if (java_thread == JavaThread::current()) {
1784     int frame_number = state->count_frames() - depth;
1785     state->env_thread_state(this)->set_frame_pop(frame_number);
1786   } else {
1787     VM_SetFramePop op(this, state, depth);
1788     VMThread::execute(&op);
1789     err = op.result();
1790   }
1791   return err;
1792 } /* end NotifyFramePop */
1793 
1794 
1795   //
1796   // Force Early Return functions
1797   //
1798 
1799 // Threads_lock NOT held, java_thread not protected by lock
1800 // java_thread - pre-checked
1801 jvmtiError
1802 JvmtiEnv::ForceEarlyReturnObject(JavaThread* java_thread, jobject value) {
1803   jvalue val;
1804   val.l = value;
1805   return force_early_return(java_thread, val, atos);
1806 } /* end ForceEarlyReturnObject */
1807 
1808 
1809 // Threads_lock NOT held, java_thread not protected by lock
1810 // java_thread - pre-checked
1811 jvmtiError
1812 JvmtiEnv::ForceEarlyReturnInt(JavaThread* java_thread, jint value) {
1813   jvalue val;
1814   val.i = value;
1815   return force_early_return(java_thread, val, itos);
1816 } /* end ForceEarlyReturnInt */
1817 
1818 
1819 // Threads_lock NOT held, java_thread not protected by lock
1820 // java_thread - pre-checked
1821 jvmtiError
1822 JvmtiEnv::ForceEarlyReturnLong(JavaThread* java_thread, jlong value) {
1823   jvalue val;
1824   val.j = value;
1825   return force_early_return(java_thread, val, ltos);
1826 } /* end ForceEarlyReturnLong */
1827 
1828 
1829 // Threads_lock NOT held, java_thread not protected by lock
1830 // java_thread - pre-checked
1831 jvmtiError
1832 JvmtiEnv::ForceEarlyReturnFloat(JavaThread* java_thread, jfloat value) {
1833   jvalue val;
1834   val.f = value;
1835   return force_early_return(java_thread, val, ftos);
1836 } /* end ForceEarlyReturnFloat */
1837 
1838 
1839 // Threads_lock NOT held, java_thread not protected by lock
1840 // java_thread - pre-checked
1841 jvmtiError
1842 JvmtiEnv::ForceEarlyReturnDouble(JavaThread* java_thread, jdouble value) {
1843   jvalue val;
1844   val.d = value;
1845   return force_early_return(java_thread, val, dtos);
1846 } /* end ForceEarlyReturnDouble */
1847 
1848 
1849 // Threads_lock NOT held, java_thread not protected by lock
1850 // java_thread - pre-checked
1851 jvmtiError
1852 JvmtiEnv::ForceEarlyReturnVoid(JavaThread* java_thread) {
1853   jvalue val;
1854   val.j = 0L;
1855   return force_early_return(java_thread, val, vtos);
1856 } /* end ForceEarlyReturnVoid */
1857 
1858 
1859   //
1860   // Heap functions
1861   //
1862 
1863 // klass - NULL is a valid value, must be checked
1864 // initial_object - NULL is a valid value, must be checked
1865 // callbacks - pre-checked for NULL
1866 // user_data - NULL is a valid value, must be checked
1867 jvmtiError
1868 JvmtiEnv::FollowReferences(jint heap_filter, jclass klass, jobject initial_object, const jvmtiHeapCallbacks* callbacks, const void* user_data) {
1869   // check klass if provided
1870   Klass* k = NULL;
1871   if (klass != NULL) {
1872     oop k_mirror = JNIHandles::resolve_external_guard(klass);
1873     if (k_mirror == NULL) {
1874       return JVMTI_ERROR_INVALID_CLASS;
1875     }
1876     if (java_lang_Class::is_primitive(k_mirror)) {
1877       return JVMTI_ERROR_NONE;
1878     }
1879     k = java_lang_Class::as_Klass(k_mirror);
1880     if (klass == NULL) {
1881       return JVMTI_ERROR_INVALID_CLASS;
1882     }
1883   }
1884 
1885   if (initial_object != NULL) {
1886     oop init_obj = JNIHandles::resolve_external_guard(initial_object);
1887     if (init_obj == NULL) {
1888       return JVMTI_ERROR_INVALID_OBJECT;
1889     }
1890   }
1891 
1892   Thread *thread = Thread::current();
1893   HandleMark hm(thread);
1894 
1895   TraceTime t("FollowReferences", TRACETIME_LOG(Debug, jvmti, objecttagging));
1896   JvmtiTagMap::tag_map_for(this)->follow_references(heap_filter, k, initial_object, callbacks, user_data);
1897   return JVMTI_ERROR_NONE;
1898 } /* end FollowReferences */
1899 
1900 
1901 // klass - NULL is a valid value, must be checked
1902 // callbacks - pre-checked for NULL
1903 // user_data - NULL is a valid value, must be checked
1904 jvmtiError
1905 JvmtiEnv::IterateThroughHeap(jint heap_filter, jclass klass, const jvmtiHeapCallbacks* callbacks, const void* user_data) {
1906   // check klass if provided
1907   Klass* k = NULL;
1908   if (klass != NULL) {
1909     oop k_mirror = JNIHandles::resolve_external_guard(klass);
1910     if (k_mirror == NULL) {
1911       return JVMTI_ERROR_INVALID_CLASS;
1912     }
1913     if (java_lang_Class::is_primitive(k_mirror)) {
1914       return JVMTI_ERROR_NONE;
1915     }
1916     k = java_lang_Class::as_Klass(k_mirror);
1917     if (k == NULL) {
1918       return JVMTI_ERROR_INVALID_CLASS;
1919     }
1920   }
1921 
1922   TraceTime t("IterateThroughHeap", TRACETIME_LOG(Debug, jvmti, objecttagging));
1923   JvmtiTagMap::tag_map_for(this)->iterate_through_heap(heap_filter, k, callbacks, user_data);
1924   return JVMTI_ERROR_NONE;
1925 } /* end IterateThroughHeap */
1926 
1927 
1928 // tag_ptr - pre-checked for NULL
1929 jvmtiError
1930 JvmtiEnv::GetTag(jobject object, jlong* tag_ptr) {
1931   oop o = JNIHandles::resolve_external_guard(object);
1932   NULL_CHECK(o, JVMTI_ERROR_INVALID_OBJECT);
1933   *tag_ptr = JvmtiTagMap::tag_map_for(this)->get_tag(object);
1934   return JVMTI_ERROR_NONE;
1935 } /* end GetTag */
1936 
1937 
1938 jvmtiError
1939 JvmtiEnv::SetTag(jobject object, jlong tag) {
1940   oop o = JNIHandles::resolve_external_guard(object);
1941   NULL_CHECK(o, JVMTI_ERROR_INVALID_OBJECT);
1942   JvmtiTagMap::tag_map_for(this)->set_tag(object, tag);
1943   return JVMTI_ERROR_NONE;
1944 } /* end SetTag */
1945 
1946 
1947 // tag_count - pre-checked to be greater than or equal to 0
1948 // tags - pre-checked for NULL
1949 // count_ptr - pre-checked for NULL
1950 // object_result_ptr - NULL is a valid value, must be checked
1951 // tag_result_ptr - NULL is a valid value, must be checked
1952 jvmtiError
1953 JvmtiEnv::GetObjectsWithTags(jint tag_count, const jlong* tags, jint* count_ptr, jobject** object_result_ptr, jlong** tag_result_ptr) {
1954   TraceTime t("GetObjectsWithTags", TRACETIME_LOG(Debug, jvmti, objecttagging));
1955   return JvmtiTagMap::tag_map_for(this)->get_objects_with_tags((jlong*)tags, tag_count, count_ptr, object_result_ptr, tag_result_ptr);
1956 } /* end GetObjectsWithTags */
1957 
1958 
1959 jvmtiError
1960 JvmtiEnv::ForceGarbageCollection() {
1961   Universe::heap()->collect(GCCause::_jvmti_force_gc);
1962   return JVMTI_ERROR_NONE;
1963 } /* end ForceGarbageCollection */
1964 
1965 
1966   //
1967   // Heap (1.0) functions
1968   //
1969 
1970 // object_reference_callback - pre-checked for NULL
1971 // user_data - NULL is a valid value, must be checked
1972 jvmtiError
1973 JvmtiEnv::IterateOverObjectsReachableFromObject(jobject object, jvmtiObjectReferenceCallback object_reference_callback, const void* user_data) {
1974   oop o = JNIHandles::resolve_external_guard(object);
1975   NULL_CHECK(o, JVMTI_ERROR_INVALID_OBJECT);
1976   JvmtiTagMap::tag_map_for(this)->iterate_over_objects_reachable_from_object(object, object_reference_callback, user_data);
1977   return JVMTI_ERROR_NONE;
1978 } /* end IterateOverObjectsReachableFromObject */
1979 
1980 
1981 // heap_root_callback - NULL is a valid value, must be checked
1982 // stack_ref_callback - NULL is a valid value, must be checked
1983 // object_ref_callback - NULL is a valid value, must be checked
1984 // user_data - NULL is a valid value, must be checked
1985 jvmtiError
1986 JvmtiEnv::IterateOverReachableObjects(jvmtiHeapRootCallback heap_root_callback, jvmtiStackReferenceCallback stack_ref_callback, jvmtiObjectReferenceCallback object_ref_callback, const void* user_data) {
1987   TraceTime t("IterateOverReachableObjects", TRACETIME_LOG(Debug, jvmti, objecttagging));
1988   JvmtiTagMap::tag_map_for(this)->iterate_over_reachable_objects(heap_root_callback, stack_ref_callback, object_ref_callback, user_data);
1989   return JVMTI_ERROR_NONE;
1990 } /* end IterateOverReachableObjects */
1991 
1992 
1993 // heap_object_callback - pre-checked for NULL
1994 // user_data - NULL is a valid value, must be checked
1995 jvmtiError
1996 JvmtiEnv::IterateOverHeap(jvmtiHeapObjectFilter object_filter, jvmtiHeapObjectCallback heap_object_callback, const void* user_data) {
1997   TraceTime t("IterateOverHeap", TRACETIME_LOG(Debug, jvmti, objecttagging));
1998   Thread *thread = Thread::current();
1999   HandleMark hm(thread);
2000   JvmtiTagMap::tag_map_for(this)->iterate_over_heap(object_filter, NULL, heap_object_callback, user_data);
2001   return JVMTI_ERROR_NONE;
2002 } /* end IterateOverHeap */
2003 
2004 
2005 // k_mirror - may be primitive, this must be checked
2006 // heap_object_callback - pre-checked for NULL
2007 // user_data - NULL is a valid value, must be checked
2008 jvmtiError
2009 JvmtiEnv::IterateOverInstancesOfClass(oop k_mirror, jvmtiHeapObjectFilter object_filter, jvmtiHeapObjectCallback heap_object_callback, const void* user_data) {
2010   if (java_lang_Class::is_primitive(k_mirror)) {
2011     // DO PRIMITIVE CLASS PROCESSING
2012     return JVMTI_ERROR_NONE;
2013   }
2014   Klass* klass = java_lang_Class::as_Klass(k_mirror);
2015   if (klass == NULL) {
2016     return JVMTI_ERROR_INVALID_CLASS;
2017   }
2018   TraceTime t("IterateOverInstancesOfClass", TRACETIME_LOG(Debug, jvmti, objecttagging));
2019   JvmtiTagMap::tag_map_for(this)->iterate_over_heap(object_filter, klass, heap_object_callback, user_data);
2020   return JVMTI_ERROR_NONE;
2021 } /* end IterateOverInstancesOfClass */
2022 
2023 
2024   //
2025   // Local Variable functions
2026   //
2027 
2028 // Threads_lock NOT held, java_thread not protected by lock
2029 // java_thread - pre-checked
2030 // java_thread - unchecked
2031 // depth - pre-checked as non-negative
2032 // value_ptr - pre-checked for NULL
2033 jvmtiError
2034 JvmtiEnv::GetLocalObject(JavaThread* java_thread, jint depth, jint slot, jobject* value_ptr) {
2035   JavaThread* current_thread = JavaThread::current();
2036   // rm object is created to clean up the javaVFrame created in
2037   // doit_prologue(), but after doit() is finished with it.
2038   ResourceMark rm(current_thread);
2039 
2040   VM_GetOrSetLocal op(java_thread, current_thread, depth, slot);
2041   VMThread::execute(&op);
2042   jvmtiError err = op.result();
2043   if (err != JVMTI_ERROR_NONE) {
2044     return err;
2045   } else {
2046     *value_ptr = op.value().l;
2047     return JVMTI_ERROR_NONE;
2048   }
2049 } /* end GetLocalObject */
2050 
2051 // Threads_lock NOT held, java_thread not protected by lock
2052 // java_thread - pre-checked
2053 // java_thread - unchecked
2054 // depth - pre-checked as non-negative
2055 // value - pre-checked for NULL
2056 jvmtiError
2057 JvmtiEnv::GetLocalInstance(JavaThread* java_thread, jint depth, jobject* value_ptr){
2058   JavaThread* current_thread = JavaThread::current();
2059   // rm object is created to clean up the javaVFrame created in
2060   // doit_prologue(), but after doit() is finished with it.
2061   ResourceMark rm(current_thread);
2062 
2063   VM_GetReceiver op(java_thread, current_thread, depth);
2064   VMThread::execute(&op);
2065   jvmtiError err = op.result();
2066   if (err != JVMTI_ERROR_NONE) {
2067     return err;
2068   } else {
2069     *value_ptr = op.value().l;
2070     return JVMTI_ERROR_NONE;
2071   }
2072 } /* end GetLocalInstance */
2073 
2074 
2075 // Threads_lock NOT held, java_thread not protected by lock
2076 // java_thread - pre-checked
2077 // java_thread - unchecked
2078 // depth - pre-checked as non-negative
2079 // value_ptr - pre-checked for NULL
2080 jvmtiError
2081 JvmtiEnv::GetLocalInt(JavaThread* java_thread, jint depth, jint slot, jint* value_ptr) {
2082   // rm object is created to clean up the javaVFrame created in
2083   // doit_prologue(), but after doit() is finished with it.
2084   ResourceMark rm;
2085 
2086   VM_GetOrSetLocal op(java_thread, depth, slot, T_INT);
2087   VMThread::execute(&op);
2088   *value_ptr = op.value().i;
2089   return op.result();
2090 } /* end GetLocalInt */
2091 
2092 
2093 // Threads_lock NOT held, java_thread not protected by lock
2094 // java_thread - pre-checked
2095 // java_thread - unchecked
2096 // depth - pre-checked as non-negative
2097 // value_ptr - pre-checked for NULL
2098 jvmtiError
2099 JvmtiEnv::GetLocalLong(JavaThread* java_thread, jint depth, jint slot, jlong* value_ptr) {
2100   // rm object is created to clean up the javaVFrame created in
2101   // doit_prologue(), but after doit() is finished with it.
2102   ResourceMark rm;
2103 
2104   VM_GetOrSetLocal op(java_thread, depth, slot, T_LONG);
2105   VMThread::execute(&op);
2106   *value_ptr = op.value().j;
2107   return op.result();
2108 } /* end GetLocalLong */
2109 
2110 
2111 // Threads_lock NOT held, java_thread not protected by lock
2112 // java_thread - pre-checked
2113 // java_thread - unchecked
2114 // depth - pre-checked as non-negative
2115 // value_ptr - pre-checked for NULL
2116 jvmtiError
2117 JvmtiEnv::GetLocalFloat(JavaThread* java_thread, jint depth, jint slot, jfloat* value_ptr) {
2118   // rm object is created to clean up the javaVFrame created in
2119   // doit_prologue(), but after doit() is finished with it.
2120   ResourceMark rm;
2121 
2122   VM_GetOrSetLocal op(java_thread, depth, slot, T_FLOAT);
2123   VMThread::execute(&op);
2124   *value_ptr = op.value().f;
2125   return op.result();
2126 } /* end GetLocalFloat */
2127 
2128 
2129 // Threads_lock NOT held, java_thread not protected by lock
2130 // java_thread - pre-checked
2131 // java_thread - unchecked
2132 // depth - pre-checked as non-negative
2133 // value_ptr - pre-checked for NULL
2134 jvmtiError
2135 JvmtiEnv::GetLocalDouble(JavaThread* java_thread, jint depth, jint slot, jdouble* value_ptr) {
2136   // rm object is created to clean up the javaVFrame created in
2137   // doit_prologue(), but after doit() is finished with it.
2138   ResourceMark rm;
2139 
2140   VM_GetOrSetLocal op(java_thread, depth, slot, T_DOUBLE);
2141   VMThread::execute(&op);
2142   *value_ptr = op.value().d;
2143   return op.result();
2144 } /* end GetLocalDouble */
2145 
2146 
2147 // Threads_lock NOT held, java_thread not protected by lock
2148 // java_thread - pre-checked
2149 // java_thread - unchecked
2150 // depth - pre-checked as non-negative
2151 jvmtiError
2152 JvmtiEnv::SetLocalObject(JavaThread* java_thread, jint depth, jint slot, jobject value) {
2153   // rm object is created to clean up the javaVFrame created in
2154   // doit_prologue(), but after doit() is finished with it.
2155   ResourceMark rm;
2156   jvalue val;
2157   val.l = value;
2158   VM_GetOrSetLocal op(java_thread, depth, slot, T_OBJECT, val);
2159   VMThread::execute(&op);
2160   return op.result();
2161 } /* end SetLocalObject */
2162 
2163 
2164 // Threads_lock NOT held, java_thread not protected by lock
2165 // java_thread - pre-checked
2166 // java_thread - unchecked
2167 // depth - pre-checked as non-negative
2168 jvmtiError
2169 JvmtiEnv::SetLocalInt(JavaThread* java_thread, jint depth, jint slot, jint value) {
2170   // rm object is created to clean up the javaVFrame created in
2171   // doit_prologue(), but after doit() is finished with it.
2172   ResourceMark rm;
2173   jvalue val;
2174   val.i = value;
2175   VM_GetOrSetLocal op(java_thread, depth, slot, T_INT, val);
2176   VMThread::execute(&op);
2177   return op.result();
2178 } /* end SetLocalInt */
2179 
2180 
2181 // Threads_lock NOT held, java_thread not protected by lock
2182 // java_thread - pre-checked
2183 // java_thread - unchecked
2184 // depth - pre-checked as non-negative
2185 jvmtiError
2186 JvmtiEnv::SetLocalLong(JavaThread* java_thread, jint depth, jint slot, jlong value) {
2187   // rm object is created to clean up the javaVFrame created in
2188   // doit_prologue(), but after doit() is finished with it.
2189   ResourceMark rm;
2190   jvalue val;
2191   val.j = value;
2192   VM_GetOrSetLocal op(java_thread, depth, slot, T_LONG, val);
2193   VMThread::execute(&op);
2194   return op.result();
2195 } /* end SetLocalLong */
2196 
2197 
2198 // Threads_lock NOT held, java_thread not protected by lock
2199 // java_thread - pre-checked
2200 // java_thread - unchecked
2201 // depth - pre-checked as non-negative
2202 jvmtiError
2203 JvmtiEnv::SetLocalFloat(JavaThread* java_thread, jint depth, jint slot, jfloat value) {
2204   // rm object is created to clean up the javaVFrame created in
2205   // doit_prologue(), but after doit() is finished with it.
2206   ResourceMark rm;
2207   jvalue val;
2208   val.f = value;
2209   VM_GetOrSetLocal op(java_thread, depth, slot, T_FLOAT, val);
2210   VMThread::execute(&op);
2211   return op.result();
2212 } /* end SetLocalFloat */
2213 
2214 
2215 // Threads_lock NOT held, java_thread not protected by lock
2216 // java_thread - pre-checked
2217 // java_thread - unchecked
2218 // depth - pre-checked as non-negative
2219 jvmtiError
2220 JvmtiEnv::SetLocalDouble(JavaThread* java_thread, jint depth, jint slot, jdouble value) {
2221   // rm object is created to clean up the javaVFrame created in
2222   // doit_prologue(), but after doit() is finished with it.
2223   ResourceMark rm;
2224   jvalue val;
2225   val.d = value;
2226   VM_GetOrSetLocal op(java_thread, depth, slot, T_DOUBLE, val);
2227   VMThread::execute(&op);
2228   return op.result();
2229 } /* end SetLocalDouble */
2230 
2231 
2232   //
2233   // Breakpoint functions
2234   //
2235 
2236 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2237 jvmtiError
2238 JvmtiEnv::SetBreakpoint(Method* method_oop, jlocation location) {
2239   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2240   if (location < 0) {   // simple invalid location check first
2241     return JVMTI_ERROR_INVALID_LOCATION;
2242   }
2243   // verify that the breakpoint is not past the end of the method
2244   if (location >= (jlocation) method_oop->code_size()) {
2245     return JVMTI_ERROR_INVALID_LOCATION;
2246   }
2247 
2248   ResourceMark rm;
2249   JvmtiBreakpoint bp(method_oop, location);
2250   JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
2251   if (jvmti_breakpoints.set(bp) == JVMTI_ERROR_DUPLICATE)
2252     return JVMTI_ERROR_DUPLICATE;
2253 
2254   if (TraceJVMTICalls) {
2255     jvmti_breakpoints.print();
2256   }
2257 
2258   return JVMTI_ERROR_NONE;
2259 } /* end SetBreakpoint */
2260 
2261 
2262 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2263 jvmtiError
2264 JvmtiEnv::ClearBreakpoint(Method* method_oop, jlocation location) {
2265   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2266 
2267   if (location < 0) {   // simple invalid location check first
2268     return JVMTI_ERROR_INVALID_LOCATION;
2269   }
2270 
2271   // verify that the breakpoint is not past the end of the method
2272   if (location >= (jlocation) method_oop->code_size()) {
2273     return JVMTI_ERROR_INVALID_LOCATION;
2274   }
2275 
2276   JvmtiBreakpoint bp(method_oop, location);
2277 
2278   JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
2279   if (jvmti_breakpoints.clear(bp) == JVMTI_ERROR_NOT_FOUND)
2280     return JVMTI_ERROR_NOT_FOUND;
2281 
2282   if (TraceJVMTICalls) {
2283     jvmti_breakpoints.print();
2284   }
2285 
2286   return JVMTI_ERROR_NONE;
2287 } /* end ClearBreakpoint */
2288 
2289 
2290   //
2291   // Watched Field functions
2292   //
2293 
2294 jvmtiError
2295 JvmtiEnv::SetFieldAccessWatch(fieldDescriptor* fdesc_ptr) {
2296   // make sure we haven't set this watch before
2297   if (fdesc_ptr->is_field_access_watched()) return JVMTI_ERROR_DUPLICATE;
2298   fdesc_ptr->set_is_field_access_watched(true);
2299 
2300   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_ACCESS, true);
2301 
2302   return JVMTI_ERROR_NONE;
2303 } /* end SetFieldAccessWatch */
2304 
2305 
2306 jvmtiError
2307 JvmtiEnv::ClearFieldAccessWatch(fieldDescriptor* fdesc_ptr) {
2308   // make sure we have a watch to clear
2309   if (!fdesc_ptr->is_field_access_watched()) return JVMTI_ERROR_NOT_FOUND;
2310   fdesc_ptr->set_is_field_access_watched(false);
2311 
2312   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_ACCESS, false);
2313 
2314   return JVMTI_ERROR_NONE;
2315 } /* end ClearFieldAccessWatch */
2316 
2317 
2318 jvmtiError
2319 JvmtiEnv::SetFieldModificationWatch(fieldDescriptor* fdesc_ptr) {
2320   // make sure we haven't set this watch before
2321   if (fdesc_ptr->is_field_modification_watched()) return JVMTI_ERROR_DUPLICATE;
2322   fdesc_ptr->set_is_field_modification_watched(true);
2323 
2324   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_MODIFICATION, true);
2325 
2326   return JVMTI_ERROR_NONE;
2327 } /* end SetFieldModificationWatch */
2328 
2329 
2330 jvmtiError
2331 JvmtiEnv::ClearFieldModificationWatch(fieldDescriptor* fdesc_ptr) {
2332    // make sure we have a watch to clear
2333   if (!fdesc_ptr->is_field_modification_watched()) return JVMTI_ERROR_NOT_FOUND;
2334   fdesc_ptr->set_is_field_modification_watched(false);
2335 
2336   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_MODIFICATION, false);
2337 
2338   return JVMTI_ERROR_NONE;
2339 } /* end ClearFieldModificationWatch */
2340 
2341   //
2342   // Class functions
2343   //
2344 
2345 
2346 // k_mirror - may be primitive, this must be checked
2347 // signature_ptr - NULL is a valid value, must be checked
2348 // generic_ptr - NULL is a valid value, must be checked
2349 jvmtiError
2350 JvmtiEnv::GetClassSignature(oop k_mirror, char** signature_ptr, char** generic_ptr) {
2351   ResourceMark rm;
2352   bool isPrimitive = java_lang_Class::is_primitive(k_mirror);
2353   Klass* k = NULL;
2354   if (!isPrimitive) {
2355     k = java_lang_Class::as_Klass(k_mirror);
2356     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2357   }
2358   if (signature_ptr != NULL) {
2359     char* result = NULL;
2360     if (isPrimitive) {
2361       char tchar = type2char(java_lang_Class::primitive_type(k_mirror));
2362       result = (char*) jvmtiMalloc(2);
2363       result[0] = tchar;
2364       result[1] = '\0';
2365     } else {
2366       const char* class_sig = k->signature_name();
2367       result = (char *) jvmtiMalloc(strlen(class_sig)+1);
2368       strcpy(result, class_sig);
2369     }
2370     *signature_ptr = result;
2371   }
2372   if (generic_ptr != NULL) {
2373     *generic_ptr = NULL;
2374     if (!isPrimitive && k->is_instance_klass()) {
2375       Symbol* soo = InstanceKlass::cast(k)->generic_signature();
2376       if (soo != NULL) {
2377         const char *gen_sig = soo->as_C_string();
2378         if (gen_sig != NULL) {
2379           char* gen_result;
2380           jvmtiError err = allocate(strlen(gen_sig) + 1,
2381                                     (unsigned char **)&gen_result);
2382           if (err != JVMTI_ERROR_NONE) {
2383             return err;
2384           }
2385           strcpy(gen_result, gen_sig);
2386           *generic_ptr = gen_result;
2387         }
2388       }
2389     }
2390   }
2391   return JVMTI_ERROR_NONE;
2392 } /* end GetClassSignature */
2393 
2394 
2395 // k_mirror - may be primitive, this must be checked
2396 // status_ptr - pre-checked for NULL
2397 jvmtiError
2398 JvmtiEnv::GetClassStatus(oop k_mirror, jint* status_ptr) {
2399   jint result = 0;
2400   if (java_lang_Class::is_primitive(k_mirror)) {
2401     result |= JVMTI_CLASS_STATUS_PRIMITIVE;
2402   } else {
2403     Klass* k = java_lang_Class::as_Klass(k_mirror);
2404     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2405     result = k->jvmti_class_status();
2406   }
2407   *status_ptr = result;
2408 
2409   return JVMTI_ERROR_NONE;
2410 } /* end GetClassStatus */
2411 
2412 
2413 // k_mirror - may be primitive, this must be checked
2414 // source_name_ptr - pre-checked for NULL
2415 jvmtiError
2416 JvmtiEnv::GetSourceFileName(oop k_mirror, char** source_name_ptr) {
2417   if (java_lang_Class::is_primitive(k_mirror)) {
2418      return JVMTI_ERROR_ABSENT_INFORMATION;
2419   }
2420   Klass* k_klass = java_lang_Class::as_Klass(k_mirror);
2421   NULL_CHECK(k_klass, JVMTI_ERROR_INVALID_CLASS);
2422 
2423   if (!k_klass->is_instance_klass()) {
2424     return JVMTI_ERROR_ABSENT_INFORMATION;
2425   }
2426 
2427   Symbol* sfnOop = InstanceKlass::cast(k_klass)->source_file_name();
2428   NULL_CHECK(sfnOop, JVMTI_ERROR_ABSENT_INFORMATION);
2429   {
2430     JavaThread* current_thread  = JavaThread::current();
2431     ResourceMark rm(current_thread);
2432     const char* sfncp = (const char*) sfnOop->as_C_string();
2433     *source_name_ptr = (char *) jvmtiMalloc(strlen(sfncp)+1);
2434     strcpy(*source_name_ptr, sfncp);
2435   }
2436 
2437   return JVMTI_ERROR_NONE;
2438 } /* end GetSourceFileName */
2439 
2440 
2441 // k_mirror - may be primitive, this must be checked
2442 // modifiers_ptr - pre-checked for NULL
2443 jvmtiError
2444 JvmtiEnv::GetClassModifiers(oop k_mirror, jint* modifiers_ptr) {
2445   JavaThread* current_thread  = JavaThread::current();
2446   jint result = 0;
2447   if (!java_lang_Class::is_primitive(k_mirror)) {
2448     Klass* k = java_lang_Class::as_Klass(k_mirror);
2449     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2450     result = k->compute_modifier_flags(current_thread);
2451     JavaThread* THREAD = current_thread; // pass to macros
2452     if (HAS_PENDING_EXCEPTION) {
2453       CLEAR_PENDING_EXCEPTION;
2454       return JVMTI_ERROR_INTERNAL;
2455     };
2456 
2457     // Reset the deleted  ACC_SUPER bit ( deleted in compute_modifier_flags()).
2458     if(k->is_super()) {
2459       result |= JVM_ACC_SUPER;
2460     }
2461   } else {
2462     result = (JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
2463   }
2464   *modifiers_ptr = result;
2465 
2466   return JVMTI_ERROR_NONE;
2467 } /* end GetClassModifiers */
2468 
2469 
2470 // k_mirror - may be primitive, this must be checked
2471 // method_count_ptr - pre-checked for NULL
2472 // methods_ptr - pre-checked for NULL
2473 jvmtiError
2474 JvmtiEnv::GetClassMethods(oop k_mirror, jint* method_count_ptr, jmethodID** methods_ptr) {
2475   JavaThread* current_thread  = JavaThread::current();
2476   HandleMark hm(current_thread);
2477 
2478   if (java_lang_Class::is_primitive(k_mirror)) {
2479     *method_count_ptr = 0;
2480     *methods_ptr = (jmethodID*) jvmtiMalloc(0 * sizeof(jmethodID));
2481     return JVMTI_ERROR_NONE;
2482   }
2483   Klass* k = java_lang_Class::as_Klass(k_mirror);
2484   NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2485 
2486   // Return CLASS_NOT_PREPARED error as per JVMTI spec.
2487   if (!(k->jvmti_class_status() & (JVMTI_CLASS_STATUS_PREPARED|JVMTI_CLASS_STATUS_ARRAY) )) {
2488     return JVMTI_ERROR_CLASS_NOT_PREPARED;
2489   }
2490 
2491   if (!k->is_instance_klass()) {
2492     *method_count_ptr = 0;
2493     *methods_ptr = (jmethodID*) jvmtiMalloc(0 * sizeof(jmethodID));
2494     return JVMTI_ERROR_NONE;
2495   }
2496   InstanceKlass* ik = InstanceKlass::cast(k);
2497   // Allocate the result and fill it in
2498   int result_length = ik->methods()->length();
2499   jmethodID* result_list = (jmethodID*)jvmtiMalloc(result_length * sizeof(jmethodID));
2500   int index;
2501   bool jmethodids_found = true;
2502 
2503   if (JvmtiExport::can_maintain_original_method_order()) {
2504     // Use the original method ordering indices stored in the class, so we can emit
2505     // jmethodIDs in the order they appeared in the class file
2506     for (index = 0; index < result_length; index++) {
2507       Method* m = ik->methods()->at(index);
2508       int original_index = ik->method_ordering()->at(index);
2509       assert(original_index >= 0 && original_index < result_length, "invalid original method index");
2510       jmethodID id;
2511       if (jmethodids_found) {
2512         id = m->find_jmethod_id_or_null();
2513         if (id == NULL) {
2514           // If we find an uninitialized value, make sure there is
2515           // enough space for all the uninitialized values we might
2516           // find.
2517           ik->ensure_space_for_methodids(index);
2518           jmethodids_found = false;
2519           id = m->jmethod_id();
2520         }
2521       } else {
2522         id = m->jmethod_id();
2523       }
2524       result_list[original_index] = id;
2525     }
2526   } else {
2527     // otherwise just copy in any order
2528     for (index = 0; index < result_length; index++) {
2529       Method* m = ik->methods()->at(index);
2530       jmethodID id;
2531       if (jmethodids_found) {
2532         id = m->find_jmethod_id_or_null();
2533         if (id == NULL) {
2534           // If we find an uninitialized value, make sure there is
2535           // enough space for all the uninitialized values we might
2536           // find.
2537           ik->ensure_space_for_methodids(index);
2538           jmethodids_found = false;
2539           id = m->jmethod_id();
2540         }
2541       } else {
2542         id = m->jmethod_id();
2543       }
2544       result_list[index] = id;
2545     }
2546   }
2547   // Fill in return value.
2548   *method_count_ptr = result_length;
2549   *methods_ptr = result_list;
2550 
2551   return JVMTI_ERROR_NONE;
2552 } /* end GetClassMethods */
2553 
2554 
2555 // k_mirror - may be primitive, this must be checked
2556 // field_count_ptr - pre-checked for NULL
2557 // fields_ptr - pre-checked for NULL
2558 jvmtiError
2559 JvmtiEnv::GetClassFields(oop k_mirror, jint* field_count_ptr, jfieldID** fields_ptr) {
2560   if (java_lang_Class::is_primitive(k_mirror)) {
2561     *field_count_ptr = 0;
2562     *fields_ptr = (jfieldID*) jvmtiMalloc(0 * sizeof(jfieldID));
2563     return JVMTI_ERROR_NONE;
2564   }
2565   JavaThread* current_thread = JavaThread::current();
2566   HandleMark hm(current_thread);
2567   Klass* k = java_lang_Class::as_Klass(k_mirror);
2568   NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2569 
2570   // Return CLASS_NOT_PREPARED error as per JVMTI spec.
2571   if (!(k->jvmti_class_status() & (JVMTI_CLASS_STATUS_PREPARED|JVMTI_CLASS_STATUS_ARRAY) )) {
2572     return JVMTI_ERROR_CLASS_NOT_PREPARED;
2573   }
2574 
2575   if (!k->is_instance_klass()) {
2576     *field_count_ptr = 0;
2577     *fields_ptr = (jfieldID*) jvmtiMalloc(0 * sizeof(jfieldID));
2578     return JVMTI_ERROR_NONE;
2579   }
2580 
2581 
2582   InstanceKlass* ik = InstanceKlass::cast(k);
2583 
2584   int result_count = 0;
2585   // First, count the fields.
2586   FilteredFieldStream flds(ik, true, true);
2587   result_count = flds.field_count();
2588 
2589   // Allocate the result and fill it in
2590   jfieldID* result_list = (jfieldID*) jvmtiMalloc(result_count * sizeof(jfieldID));
2591   // The JVMTI spec requires fields in the order they occur in the class file,
2592   // this is the reverse order of what FieldStream hands out.
2593   int id_index = (result_count - 1);
2594 
2595   for (FilteredFieldStream src_st(ik, true, true); !src_st.eos(); src_st.next()) {
2596     result_list[id_index--] = jfieldIDWorkaround::to_jfieldID(
2597                                             ik, src_st.offset(),
2598                                             src_st.access_flags().is_static());
2599   }
2600   assert(id_index == -1, "just checking");
2601   // Fill in the results
2602   *field_count_ptr = result_count;
2603   *fields_ptr = result_list;
2604 
2605   return JVMTI_ERROR_NONE;
2606 } /* end GetClassFields */
2607 
2608 
2609 // k_mirror - may be primitive, this must be checked
2610 // interface_count_ptr - pre-checked for NULL
2611 // interfaces_ptr - pre-checked for NULL
2612 jvmtiError
2613 JvmtiEnv::GetImplementedInterfaces(oop k_mirror, jint* interface_count_ptr, jclass** interfaces_ptr) {
2614   {
2615     if (java_lang_Class::is_primitive(k_mirror)) {
2616       *interface_count_ptr = 0;
2617       *interfaces_ptr = (jclass*) jvmtiMalloc(0 * sizeof(jclass));
2618       return JVMTI_ERROR_NONE;
2619     }
2620     JavaThread* current_thread = JavaThread::current();
2621     HandleMark hm(current_thread);
2622     Klass* k = java_lang_Class::as_Klass(k_mirror);
2623     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2624 
2625     // Return CLASS_NOT_PREPARED error as per JVMTI spec.
2626     if (!(k->jvmti_class_status() & (JVMTI_CLASS_STATUS_PREPARED|JVMTI_CLASS_STATUS_ARRAY) ))
2627       return JVMTI_ERROR_CLASS_NOT_PREPARED;
2628 
2629     if (!k->is_instance_klass()) {
2630       *interface_count_ptr = 0;
2631       *interfaces_ptr = (jclass*) jvmtiMalloc(0 * sizeof(jclass));
2632       return JVMTI_ERROR_NONE;
2633     }
2634 
2635     Array<InstanceKlass*>* interface_list = InstanceKlass::cast(k)->local_interfaces();
2636     const int result_length = (interface_list == NULL ? 0 : interface_list->length());
2637     jclass* result_list = (jclass*) jvmtiMalloc(result_length * sizeof(jclass));
2638     for (int i_index = 0; i_index < result_length; i_index += 1) {
2639       InstanceKlass* klass_at = interface_list->at(i_index);
2640       assert(klass_at->is_klass(), "interfaces must be Klass*s");
2641       assert(klass_at->is_interface(), "interfaces must be interfaces");
2642       oop mirror_at = klass_at->java_mirror();
2643       Handle handle_at = Handle(current_thread, mirror_at);
2644       result_list[i_index] = (jclass) jni_reference(handle_at);
2645     }
2646     *interface_count_ptr = result_length;
2647     *interfaces_ptr = result_list;
2648   }
2649 
2650   return JVMTI_ERROR_NONE;
2651 } /* end GetImplementedInterfaces */
2652 
2653 
2654 // k_mirror - may be primitive, this must be checked
2655 // minor_version_ptr - pre-checked for NULL
2656 // major_version_ptr - pre-checked for NULL
2657 jvmtiError
2658 JvmtiEnv::GetClassVersionNumbers(oop k_mirror, jint* minor_version_ptr, jint* major_version_ptr) {
2659   if (java_lang_Class::is_primitive(k_mirror)) {
2660     return JVMTI_ERROR_ABSENT_INFORMATION;
2661   }
2662   Klass* klass = java_lang_Class::as_Klass(k_mirror);
2663 
2664   jint status = klass->jvmti_class_status();
2665   if (status & (JVMTI_CLASS_STATUS_ERROR)) {
2666     return JVMTI_ERROR_INVALID_CLASS;
2667   }
2668   if (status & (JVMTI_CLASS_STATUS_ARRAY)) {
2669     return JVMTI_ERROR_ABSENT_INFORMATION;
2670   }
2671 
2672   InstanceKlass* ik = InstanceKlass::cast(klass);
2673   *minor_version_ptr = ik->minor_version();
2674   *major_version_ptr = ik->major_version();
2675 
2676   return JVMTI_ERROR_NONE;
2677 } /* end GetClassVersionNumbers */
2678 
2679 
2680 // k_mirror - may be primitive, this must be checked
2681 // constant_pool_count_ptr - pre-checked for NULL
2682 // constant_pool_byte_count_ptr - pre-checked for NULL
2683 // constant_pool_bytes_ptr - pre-checked for NULL
2684 jvmtiError
2685 JvmtiEnv::GetConstantPool(oop k_mirror, jint* constant_pool_count_ptr, jint* constant_pool_byte_count_ptr, unsigned char** constant_pool_bytes_ptr) {
2686   if (java_lang_Class::is_primitive(k_mirror)) {
2687     return JVMTI_ERROR_ABSENT_INFORMATION;
2688   }
2689 
2690   Klass* klass = java_lang_Class::as_Klass(k_mirror);
2691   Thread *thread = Thread::current();
2692   ResourceMark rm(thread);
2693 
2694   jint status = klass->jvmti_class_status();
2695   if (status & (JVMTI_CLASS_STATUS_ERROR)) {
2696     return JVMTI_ERROR_INVALID_CLASS;
2697   }
2698   if (status & (JVMTI_CLASS_STATUS_ARRAY)) {
2699     return JVMTI_ERROR_ABSENT_INFORMATION;
2700   }
2701 
2702   InstanceKlass* ik = InstanceKlass::cast(klass);
2703   JvmtiConstantPoolReconstituter reconstituter(ik);
2704   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2705     return reconstituter.get_error();
2706   }
2707 
2708   unsigned char *cpool_bytes;
2709   int cpool_size = reconstituter.cpool_size();
2710   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2711     return reconstituter.get_error();
2712   }
2713   jvmtiError res = allocate(cpool_size, &cpool_bytes);
2714   if (res != JVMTI_ERROR_NONE) {
2715     return res;
2716   }
2717   reconstituter.copy_cpool_bytes(cpool_bytes);
2718   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2719     return reconstituter.get_error();
2720   }
2721 
2722   constantPoolHandle  constants(thread, ik->constants());
2723   *constant_pool_count_ptr      = constants->length();
2724   *constant_pool_byte_count_ptr = cpool_size;
2725   *constant_pool_bytes_ptr      = cpool_bytes;
2726 
2727   return JVMTI_ERROR_NONE;
2728 } /* end GetConstantPool */
2729 
2730 
2731 // k_mirror - may be primitive, this must be checked
2732 // is_interface_ptr - pre-checked for NULL
2733 jvmtiError
2734 JvmtiEnv::IsInterface(oop k_mirror, jboolean* is_interface_ptr) {
2735   {
2736     bool result = false;
2737     if (!java_lang_Class::is_primitive(k_mirror)) {
2738       Klass* k = java_lang_Class::as_Klass(k_mirror);
2739       if (k != NULL && k->is_interface()) {
2740         result = true;
2741       }
2742     }
2743     *is_interface_ptr = result;
2744   }
2745 
2746   return JVMTI_ERROR_NONE;
2747 } /* end IsInterface */
2748 
2749 
2750 // k_mirror - may be primitive, this must be checked
2751 // is_array_class_ptr - pre-checked for NULL
2752 jvmtiError
2753 JvmtiEnv::IsArrayClass(oop k_mirror, jboolean* is_array_class_ptr) {
2754   {
2755     bool result = false;
2756     if (!java_lang_Class::is_primitive(k_mirror)) {
2757       Klass* k = java_lang_Class::as_Klass(k_mirror);
2758       if (k != NULL && k->is_array_klass()) {
2759         result = true;
2760       }
2761     }
2762     *is_array_class_ptr = result;
2763   }
2764 
2765   return JVMTI_ERROR_NONE;
2766 } /* end IsArrayClass */
2767 
2768 
2769 // k_mirror - may be primitive, this must be checked
2770 // classloader_ptr - pre-checked for NULL
2771 jvmtiError
2772 JvmtiEnv::GetClassLoader(oop k_mirror, jobject* classloader_ptr) {
2773   {
2774     if (java_lang_Class::is_primitive(k_mirror)) {
2775       *classloader_ptr = (jclass) jni_reference(Handle());
2776       return JVMTI_ERROR_NONE;
2777     }
2778     JavaThread* current_thread = JavaThread::current();
2779     HandleMark hm(current_thread);
2780     Klass* k = java_lang_Class::as_Klass(k_mirror);
2781     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2782 
2783     oop result_oop = k->class_loader();
2784     if (result_oop == NULL) {
2785       *classloader_ptr = (jclass) jni_reference(Handle());
2786       return JVMTI_ERROR_NONE;
2787     }
2788     Handle result_handle = Handle(current_thread, result_oop);
2789     jclass result_jnihandle = (jclass) jni_reference(result_handle);
2790     *classloader_ptr = result_jnihandle;
2791   }
2792   return JVMTI_ERROR_NONE;
2793 } /* end GetClassLoader */
2794 
2795 
2796 // k_mirror - may be primitive, this must be checked
2797 // source_debug_extension_ptr - pre-checked for NULL
2798 jvmtiError
2799 JvmtiEnv::GetSourceDebugExtension(oop k_mirror, char** source_debug_extension_ptr) {
2800   {
2801     if (java_lang_Class::is_primitive(k_mirror)) {
2802       return JVMTI_ERROR_ABSENT_INFORMATION;
2803     }
2804     Klass* k = java_lang_Class::as_Klass(k_mirror);
2805     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2806     if (!k->is_instance_klass()) {
2807       return JVMTI_ERROR_ABSENT_INFORMATION;
2808     }
2809     const char* sde = InstanceKlass::cast(k)->source_debug_extension();
2810     NULL_CHECK(sde, JVMTI_ERROR_ABSENT_INFORMATION);
2811 
2812     {
2813       *source_debug_extension_ptr = (char *) jvmtiMalloc(strlen(sde)+1);
2814       strcpy(*source_debug_extension_ptr, sde);
2815     }
2816   }
2817 
2818   return JVMTI_ERROR_NONE;
2819 } /* end GetSourceDebugExtension */
2820 
2821   //
2822   // Object functions
2823   //
2824 
2825 // hash_code_ptr - pre-checked for NULL
2826 jvmtiError
2827 JvmtiEnv::GetObjectHashCode(jobject object, jint* hash_code_ptr) {
2828   oop mirror = JNIHandles::resolve_external_guard(object);
2829   NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
2830   NULL_CHECK(hash_code_ptr, JVMTI_ERROR_NULL_POINTER);
2831 
2832   {
2833     jint result = (jint) mirror->identity_hash();
2834     *hash_code_ptr = result;
2835   }
2836   return JVMTI_ERROR_NONE;
2837 } /* end GetObjectHashCode */
2838 
2839 
2840 // info_ptr - pre-checked for NULL
2841 jvmtiError
2842 JvmtiEnv::GetObjectMonitorUsage(jobject object, jvmtiMonitorUsage* info_ptr) {
2843   JavaThread* calling_thread = JavaThread::current();
2844   jvmtiError err = get_object_monitor_usage(calling_thread, object, info_ptr);
2845   if (err == JVMTI_ERROR_THREAD_NOT_SUSPENDED) {
2846     // Some of the critical threads were not suspended. go to a safepoint and try again
2847     VM_GetObjectMonitorUsage op(this, calling_thread, object, info_ptr);
2848     VMThread::execute(&op);
2849     err = op.result();
2850   }
2851   return err;
2852 } /* end GetObjectMonitorUsage */
2853 
2854 
2855   //
2856   // Field functions
2857   //
2858 
2859 // name_ptr - NULL is a valid value, must be checked
2860 // signature_ptr - NULL is a valid value, must be checked
2861 // generic_ptr - NULL is a valid value, must be checked
2862 jvmtiError
2863 JvmtiEnv::GetFieldName(fieldDescriptor* fdesc_ptr, char** name_ptr, char** signature_ptr, char** generic_ptr) {
2864   JavaThread* current_thread  = JavaThread::current();
2865   ResourceMark rm(current_thread);
2866   if (name_ptr == NULL) {
2867     // just don't return the name
2868   } else {
2869     const char* fieldName = fdesc_ptr->name()->as_C_string();
2870     *name_ptr =  (char*) jvmtiMalloc(strlen(fieldName) + 1);
2871     if (*name_ptr == NULL)
2872       return JVMTI_ERROR_OUT_OF_MEMORY;
2873     strcpy(*name_ptr, fieldName);
2874   }
2875   if (signature_ptr== NULL) {
2876     // just don't return the signature
2877   } else {
2878     const char* fieldSignature = fdesc_ptr->signature()->as_C_string();
2879     *signature_ptr = (char*) jvmtiMalloc(strlen(fieldSignature) + 1);
2880     if (*signature_ptr == NULL)
2881       return JVMTI_ERROR_OUT_OF_MEMORY;
2882     strcpy(*signature_ptr, fieldSignature);
2883   }
2884   if (generic_ptr != NULL) {
2885     *generic_ptr = NULL;
2886     Symbol* soop = fdesc_ptr->generic_signature();
2887     if (soop != NULL) {
2888       const char* gen_sig = soop->as_C_string();
2889       if (gen_sig != NULL) {
2890         jvmtiError err = allocate(strlen(gen_sig) + 1, (unsigned char **)generic_ptr);
2891         if (err != JVMTI_ERROR_NONE) {
2892           return err;
2893         }
2894         strcpy(*generic_ptr, gen_sig);
2895       }
2896     }
2897   }
2898   return JVMTI_ERROR_NONE;
2899 } /* end GetFieldName */
2900 
2901 
2902 // declaring_class_ptr - pre-checked for NULL
2903 jvmtiError
2904 JvmtiEnv::GetFieldDeclaringClass(fieldDescriptor* fdesc_ptr, jclass* declaring_class_ptr) {
2905 
2906   *declaring_class_ptr = get_jni_class_non_null(fdesc_ptr->field_holder());
2907   return JVMTI_ERROR_NONE;
2908 } /* end GetFieldDeclaringClass */
2909 
2910 
2911 // modifiers_ptr - pre-checked for NULL
2912 jvmtiError
2913 JvmtiEnv::GetFieldModifiers(fieldDescriptor* fdesc_ptr, jint* modifiers_ptr) {
2914 
2915   AccessFlags resultFlags = fdesc_ptr->access_flags();
2916   jint result = resultFlags.as_int();
2917   *modifiers_ptr = result;
2918 
2919   return JVMTI_ERROR_NONE;
2920 } /* end GetFieldModifiers */
2921 
2922 
2923 // is_synthetic_ptr - pre-checked for NULL
2924 jvmtiError
2925 JvmtiEnv::IsFieldSynthetic(fieldDescriptor* fdesc_ptr, jboolean* is_synthetic_ptr) {
2926   *is_synthetic_ptr = fdesc_ptr->is_synthetic();
2927   return JVMTI_ERROR_NONE;
2928 } /* end IsFieldSynthetic */
2929 
2930 
2931   //
2932   // Method functions
2933   //
2934 
2935 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2936 // name_ptr - NULL is a valid value, must be checked
2937 // signature_ptr - NULL is a valid value, must be checked
2938 // generic_ptr - NULL is a valid value, must be checked
2939 jvmtiError
2940 JvmtiEnv::GetMethodName(Method* method_oop, char** name_ptr, char** signature_ptr, char** generic_ptr) {
2941   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2942   JavaThread* current_thread  = JavaThread::current();
2943 
2944   ResourceMark rm(current_thread); // get the utf8 name and signature
2945   if (name_ptr == NULL) {
2946     // just don't return the name
2947   } else {
2948     const char* utf8_name = (const char *) method_oop->name()->as_utf8();
2949     *name_ptr = (char *) jvmtiMalloc(strlen(utf8_name)+1);
2950     strcpy(*name_ptr, utf8_name);
2951   }
2952   if (signature_ptr == NULL) {
2953     // just don't return the signature
2954   } else {
2955     const char* utf8_signature = (const char *) method_oop->signature()->as_utf8();
2956     *signature_ptr = (char *) jvmtiMalloc(strlen(utf8_signature) + 1);
2957     strcpy(*signature_ptr, utf8_signature);
2958   }
2959 
2960   if (generic_ptr != NULL) {
2961     *generic_ptr = NULL;
2962     Symbol* soop = method_oop->generic_signature();
2963     if (soop != NULL) {
2964       const char* gen_sig = soop->as_C_string();
2965       if (gen_sig != NULL) {
2966         jvmtiError err = allocate(strlen(gen_sig) + 1, (unsigned char **)generic_ptr);
2967         if (err != JVMTI_ERROR_NONE) {
2968           return err;
2969         }
2970         strcpy(*generic_ptr, gen_sig);
2971       }
2972     }
2973   }
2974   return JVMTI_ERROR_NONE;
2975 } /* end GetMethodName */
2976 
2977 
2978 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2979 // declaring_class_ptr - pre-checked for NULL
2980 jvmtiError
2981 JvmtiEnv::GetMethodDeclaringClass(Method* method_oop, jclass* declaring_class_ptr) {
2982   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2983   (*declaring_class_ptr) = get_jni_class_non_null(method_oop->method_holder());
2984   return JVMTI_ERROR_NONE;
2985 } /* end GetMethodDeclaringClass */
2986 
2987 
2988 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2989 // modifiers_ptr - pre-checked for NULL
2990 jvmtiError
2991 JvmtiEnv::GetMethodModifiers(Method* method_oop, jint* modifiers_ptr) {
2992   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2993   (*modifiers_ptr) = method_oop->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2994   return JVMTI_ERROR_NONE;
2995 } /* end GetMethodModifiers */
2996 
2997 
2998 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2999 // max_ptr - pre-checked for NULL
3000 jvmtiError
3001 JvmtiEnv::GetMaxLocals(Method* method_oop, jint* max_ptr) {
3002   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3003   // get max stack
3004   (*max_ptr) = method_oop->max_locals();
3005   return JVMTI_ERROR_NONE;
3006 } /* end GetMaxLocals */
3007 
3008 
3009 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3010 // size_ptr - pre-checked for NULL
3011 jvmtiError
3012 JvmtiEnv::GetArgumentsSize(Method* method_oop, jint* size_ptr) {
3013   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3014   // get size of arguments
3015 
3016   (*size_ptr) = method_oop->size_of_parameters();
3017   return JVMTI_ERROR_NONE;
3018 } /* end GetArgumentsSize */
3019 
3020 
3021 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3022 // entry_count_ptr - pre-checked for NULL
3023 // table_ptr - pre-checked for NULL
3024 jvmtiError
3025 JvmtiEnv::GetLineNumberTable(Method* method_oop, jint* entry_count_ptr, jvmtiLineNumberEntry** table_ptr) {
3026   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3027   if (!method_oop->has_linenumber_table()) {
3028     return (JVMTI_ERROR_ABSENT_INFORMATION);
3029   }
3030 
3031   // The line number table is compressed so we don't know how big it is until decompressed.
3032   // Decompression is really fast so we just do it twice.
3033 
3034   // Compute size of table
3035   jint num_entries = 0;
3036   CompressedLineNumberReadStream stream(method_oop->compressed_linenumber_table());
3037   while (stream.read_pair()) {
3038     num_entries++;
3039   }
3040   jvmtiLineNumberEntry *jvmti_table =
3041             (jvmtiLineNumberEntry *)jvmtiMalloc(num_entries * (sizeof(jvmtiLineNumberEntry)));
3042 
3043   // Fill jvmti table
3044   if (num_entries > 0) {
3045     int index = 0;
3046     CompressedLineNumberReadStream stream(method_oop->compressed_linenumber_table());
3047     while (stream.read_pair()) {
3048       jvmti_table[index].start_location = (jlocation) stream.bci();
3049       jvmti_table[index].line_number = (jint) stream.line();
3050       index++;
3051     }
3052     assert(index == num_entries, "sanity check");
3053   }
3054 
3055   // Set up results
3056   (*entry_count_ptr) = num_entries;
3057   (*table_ptr) = jvmti_table;
3058 
3059   return JVMTI_ERROR_NONE;
3060 } /* end GetLineNumberTable */
3061 
3062 
3063 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3064 // start_location_ptr - pre-checked for NULL
3065 // end_location_ptr - pre-checked for NULL
3066 jvmtiError
3067 JvmtiEnv::GetMethodLocation(Method* method_oop, jlocation* start_location_ptr, jlocation* end_location_ptr) {
3068 
3069   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3070   // get start and end location
3071   (*end_location_ptr) = (jlocation) (method_oop->code_size() - 1);
3072   if (method_oop->code_size() == 0) {
3073     // there is no code so there is no start location
3074     (*start_location_ptr) = (jlocation)(-1);
3075   } else {
3076     (*start_location_ptr) = (jlocation)(0);
3077   }
3078 
3079   return JVMTI_ERROR_NONE;
3080 } /* end GetMethodLocation */
3081 
3082 
3083 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3084 // entry_count_ptr - pre-checked for NULL
3085 // table_ptr - pre-checked for NULL
3086 jvmtiError
3087 JvmtiEnv::GetLocalVariableTable(Method* method_oop, jint* entry_count_ptr, jvmtiLocalVariableEntry** table_ptr) {
3088 
3089   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3090   JavaThread* current_thread  = JavaThread::current();
3091 
3092   // does the klass have any local variable information?
3093   InstanceKlass* ik = method_oop->method_holder();
3094   if (!ik->access_flags().has_localvariable_table()) {
3095     return (JVMTI_ERROR_ABSENT_INFORMATION);
3096   }
3097 
3098   ConstantPool* constants = method_oop->constants();
3099   NULL_CHECK(constants, JVMTI_ERROR_ABSENT_INFORMATION);
3100 
3101   // in the vm localvariable table representation, 6 consecutive elements in the table
3102   // represent a 6-tuple of shorts
3103   // [start_pc, length, name_index, descriptor_index, signature_index, index]
3104   jint num_entries = method_oop->localvariable_table_length();
3105   jvmtiLocalVariableEntry *jvmti_table = (jvmtiLocalVariableEntry *)
3106                 jvmtiMalloc(num_entries * (sizeof(jvmtiLocalVariableEntry)));
3107 
3108   if (num_entries > 0) {
3109     LocalVariableTableElement* table = method_oop->localvariable_table_start();
3110     for (int i = 0; i < num_entries; i++) {
3111       // get the 5 tuple information from the vm table
3112       jlocation start_location = (jlocation) table[i].start_bci;
3113       jint length = (jint) table[i].length;
3114       int name_index = (int) table[i].name_cp_index;
3115       int signature_index = (int) table[i].descriptor_cp_index;
3116       int generic_signature_index = (int) table[i].signature_cp_index;
3117       jint slot = (jint) table[i].slot;
3118 
3119       // get utf8 name and signature
3120       char *name_buf = NULL;
3121       char *sig_buf = NULL;
3122       char *gen_sig_buf = NULL;
3123       {
3124         ResourceMark rm(current_thread);
3125 
3126         const char *utf8_name = (const char *) constants->symbol_at(name_index)->as_utf8();
3127         name_buf = (char *) jvmtiMalloc(strlen(utf8_name)+1);
3128         strcpy(name_buf, utf8_name);
3129 
3130         const char *utf8_signature = (const char *) constants->symbol_at(signature_index)->as_utf8();
3131         sig_buf = (char *) jvmtiMalloc(strlen(utf8_signature)+1);
3132         strcpy(sig_buf, utf8_signature);
3133 
3134         if (generic_signature_index > 0) {
3135           const char *utf8_gen_sign = (const char *)
3136                                        constants->symbol_at(generic_signature_index)->as_utf8();
3137           gen_sig_buf = (char *) jvmtiMalloc(strlen(utf8_gen_sign)+1);
3138           strcpy(gen_sig_buf, utf8_gen_sign);
3139         }
3140       }
3141 
3142       // fill in the jvmti local variable table
3143       jvmti_table[i].start_location = start_location;
3144       jvmti_table[i].length = length;
3145       jvmti_table[i].name = name_buf;
3146       jvmti_table[i].signature = sig_buf;
3147       jvmti_table[i].generic_signature = gen_sig_buf;
3148       jvmti_table[i].slot = slot;
3149     }
3150   }
3151 
3152   // set results
3153   (*entry_count_ptr) = num_entries;
3154   (*table_ptr) = jvmti_table;
3155 
3156   return JVMTI_ERROR_NONE;
3157 } /* end GetLocalVariableTable */
3158 
3159 
3160 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3161 // bytecode_count_ptr - pre-checked for NULL
3162 // bytecodes_ptr - pre-checked for NULL
3163 jvmtiError
3164 JvmtiEnv::GetBytecodes(Method* method_oop, jint* bytecode_count_ptr, unsigned char** bytecodes_ptr) {
3165   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3166 
3167   HandleMark hm;
3168   methodHandle method(method_oop);
3169   jint size = (jint)method->code_size();
3170   jvmtiError err = allocate(size, bytecodes_ptr);
3171   if (err != JVMTI_ERROR_NONE) {
3172     return err;
3173   }
3174 
3175   (*bytecode_count_ptr) = size;
3176   // get byte codes
3177   JvmtiClassFileReconstituter::copy_bytecodes(method, *bytecodes_ptr);
3178 
3179   return JVMTI_ERROR_NONE;
3180 } /* end GetBytecodes */
3181 
3182 
3183 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3184 // is_native_ptr - pre-checked for NULL
3185 jvmtiError
3186 JvmtiEnv::IsMethodNative(Method* method_oop, jboolean* is_native_ptr) {
3187   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3188   (*is_native_ptr) = method_oop->is_native();
3189   return JVMTI_ERROR_NONE;
3190 } /* end IsMethodNative */
3191 
3192 
3193 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3194 // is_synthetic_ptr - pre-checked for NULL
3195 jvmtiError
3196 JvmtiEnv::IsMethodSynthetic(Method* method_oop, jboolean* is_synthetic_ptr) {
3197   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3198   (*is_synthetic_ptr) = method_oop->is_synthetic();
3199   return JVMTI_ERROR_NONE;
3200 } /* end IsMethodSynthetic */
3201 
3202 
3203 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3204 // is_obsolete_ptr - pre-checked for NULL
3205 jvmtiError
3206 JvmtiEnv::IsMethodObsolete(Method* method_oop, jboolean* is_obsolete_ptr) {
3207   if (use_version_1_0_semantics() &&
3208       get_capabilities()->can_redefine_classes == 0) {
3209     // This JvmtiEnv requested version 1.0 semantics and this function
3210     // requires the can_redefine_classes capability in version 1.0 so
3211     // we need to return an error here.
3212     return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
3213   }
3214 
3215   if (method_oop == NULL || method_oop->is_obsolete()) {
3216     *is_obsolete_ptr = true;
3217   } else {
3218     *is_obsolete_ptr = false;
3219   }
3220   return JVMTI_ERROR_NONE;
3221 } /* end IsMethodObsolete */
3222 
3223   //
3224   // Raw Monitor functions
3225   //
3226 
3227 // name - pre-checked for NULL
3228 // monitor_ptr - pre-checked for NULL
3229 jvmtiError
3230 JvmtiEnv::CreateRawMonitor(const char* name, jrawMonitorID* monitor_ptr) {
3231   JvmtiRawMonitor* rmonitor = new JvmtiRawMonitor(name);
3232   NULL_CHECK(rmonitor, JVMTI_ERROR_OUT_OF_MEMORY);
3233 
3234   *monitor_ptr = (jrawMonitorID)rmonitor;
3235 
3236   return JVMTI_ERROR_NONE;
3237 } /* end CreateRawMonitor */
3238 
3239 
3240 // rmonitor - pre-checked for validity
3241 jvmtiError
3242 JvmtiEnv::DestroyRawMonitor(JvmtiRawMonitor * rmonitor) {
3243   if (Threads::number_of_threads() == 0) {
3244     // Remove this  monitor from pending raw monitors list
3245     // if it has entered in onload or start phase.
3246     JvmtiPendingMonitors::destroy(rmonitor);
3247   } else {
3248     Thread* thread  = Thread::current();
3249     if (rmonitor->is_entered(thread)) {
3250       // The caller owns this monitor which we are about to destroy.
3251       // We exit the underlying synchronization object so that the
3252       // "delete monitor" call below can work without an assertion
3253       // failure on systems that don't like destroying synchronization
3254       // objects that are locked.
3255       int r;
3256       intptr_t recursion = rmonitor->recursions();
3257       for (intptr_t i=0; i <= recursion; i++) {
3258         r = rmonitor->raw_exit(thread);
3259         assert(r == ObjectMonitor::OM_OK, "raw_exit should have worked");
3260         if (r != ObjectMonitor::OM_OK) {  // robustness
3261           return JVMTI_ERROR_INTERNAL;
3262         }
3263       }
3264     }
3265     if (rmonitor->owner() != NULL) {
3266       // The caller is trying to destroy a monitor that is locked by
3267       // someone else. While this is not forbidden by the JVMTI
3268       // spec, it will cause an assertion failure on systems that don't
3269       // like destroying synchronization objects that are locked.
3270       // We indicate a problem with the error return (and leak the
3271       // monitor's memory).
3272       return JVMTI_ERROR_NOT_MONITOR_OWNER;
3273     }
3274   }
3275 
3276   delete rmonitor;
3277 
3278   return JVMTI_ERROR_NONE;
3279 } /* end DestroyRawMonitor */
3280 
3281 
3282 // rmonitor - pre-checked for validity
3283 jvmtiError
3284 JvmtiEnv::RawMonitorEnter(JvmtiRawMonitor * rmonitor) {
3285   if (Threads::number_of_threads() == 0) {
3286     // No JavaThreads exist so ObjectMonitor enter cannot be
3287     // used, add this raw monitor to the pending list.
3288     // The pending monitors will be actually entered when
3289     // the VM is setup.
3290     // See transition_pending_raw_monitors in create_vm()
3291     // in thread.cpp.
3292     JvmtiPendingMonitors::enter(rmonitor);
3293   } else {
3294     int r = 0;
3295     Thread* thread = Thread::current();
3296 
3297     if (thread->is_Java_thread()) {
3298       JavaThread* current_thread = (JavaThread*)thread;
3299 
3300 #ifdef PROPER_TRANSITIONS
3301       // Not really unknown but ThreadInVMfromNative does more than we want
3302       ThreadInVMfromUnknown __tiv;
3303       {
3304         ThreadBlockInVM __tbivm(current_thread);
3305         r = rmonitor->raw_enter(current_thread);
3306       }
3307 #else
3308       /* Transition to thread_blocked without entering vm state          */
3309       /* This is really evil. Normally you can't undo _thread_blocked    */
3310       /* transitions like this because it would cause us to miss a       */
3311       /* safepoint but since the thread was already in _thread_in_native */
3312       /* the thread is not leaving a safepoint safe state and it will    */
3313       /* block when it tries to return from native. We can't safepoint   */
3314       /* block in here because we could deadlock the vmthread. Blech.    */
3315 
3316       JavaThreadState state = current_thread->thread_state();
3317       assert(state == _thread_in_native, "Must be _thread_in_native");
3318       // frame should already be walkable since we are in native
3319       assert(!current_thread->has_last_Java_frame() ||
3320              current_thread->frame_anchor()->walkable(), "Must be walkable");
3321       current_thread->set_thread_state(_thread_blocked);
3322 
3323       r = rmonitor->raw_enter(current_thread);
3324       // restore state, still at a safepoint safe state
3325       current_thread->set_thread_state(state);
3326 
3327 #endif /* PROPER_TRANSITIONS */
3328       assert(r == ObjectMonitor::OM_OK, "raw_enter should have worked");
3329     } else {
3330       if (thread->is_Named_thread()) {
3331         r = rmonitor->raw_enter(thread);
3332       } else {
3333         ShouldNotReachHere();
3334       }
3335     }
3336 
3337     if (r != ObjectMonitor::OM_OK) {  // robustness
3338       return JVMTI_ERROR_INTERNAL;
3339     }
3340   }
3341   return JVMTI_ERROR_NONE;
3342 } /* end RawMonitorEnter */
3343 
3344 
3345 // rmonitor - pre-checked for validity
3346 jvmtiError
3347 JvmtiEnv::RawMonitorExit(JvmtiRawMonitor * rmonitor) {
3348   jvmtiError err = JVMTI_ERROR_NONE;
3349 
3350   if (Threads::number_of_threads() == 0) {
3351     // No JavaThreads exist so just remove this monitor from the pending list.
3352     // Bool value from exit is false if rmonitor is not in the list.
3353     if (!JvmtiPendingMonitors::exit(rmonitor)) {
3354       err = JVMTI_ERROR_NOT_MONITOR_OWNER;
3355     }
3356   } else {
3357     int r = 0;
3358     Thread* thread = Thread::current();
3359 
3360     if (thread->is_Java_thread()) {
3361       JavaThread* current_thread = (JavaThread*)thread;
3362 #ifdef PROPER_TRANSITIONS
3363       // Not really unknown but ThreadInVMfromNative does more than we want
3364       ThreadInVMfromUnknown __tiv;
3365 #endif /* PROPER_TRANSITIONS */
3366       r = rmonitor->raw_exit(current_thread);
3367     } else {
3368       if (thread->is_Named_thread()) {
3369         r = rmonitor->raw_exit(thread);
3370       } else {
3371         ShouldNotReachHere();
3372       }
3373     }
3374 
3375     if (r == ObjectMonitor::OM_ILLEGAL_MONITOR_STATE) {
3376       err = JVMTI_ERROR_NOT_MONITOR_OWNER;
3377     } else {
3378       assert(r == ObjectMonitor::OM_OK, "raw_exit should have worked");
3379       if (r != ObjectMonitor::OM_OK) {  // robustness
3380         err = JVMTI_ERROR_INTERNAL;
3381       }
3382     }
3383   }
3384   return err;
3385 } /* end RawMonitorExit */
3386 
3387 
3388 // rmonitor - pre-checked for validity
3389 jvmtiError
3390 JvmtiEnv::RawMonitorWait(JvmtiRawMonitor * rmonitor, jlong millis) {
3391   int r = 0;
3392   Thread* thread = Thread::current();
3393 
3394   if (thread->is_Java_thread()) {
3395     JavaThread* current_thread = (JavaThread*)thread;
3396 #ifdef PROPER_TRANSITIONS
3397     // Not really unknown but ThreadInVMfromNative does more than we want
3398     ThreadInVMfromUnknown __tiv;
3399     {
3400       ThreadBlockInVM __tbivm(current_thread);
3401       r = rmonitor->raw_wait(millis, true, current_thread);
3402     }
3403 #else
3404     /* Transition to thread_blocked without entering vm state          */
3405     /* This is really evil. Normally you can't undo _thread_blocked    */
3406     /* transitions like this because it would cause us to miss a       */
3407     /* safepoint but since the thread was already in _thread_in_native */
3408     /* the thread is not leaving a safepoint safe state and it will    */
3409     /* block when it tries to return from native. We can't safepoint   */
3410     /* block in here because we could deadlock the vmthread. Blech.    */
3411 
3412     JavaThreadState state = current_thread->thread_state();
3413     assert(state == _thread_in_native, "Must be _thread_in_native");
3414     // frame should already be walkable since we are in native
3415     assert(!current_thread->has_last_Java_frame() ||
3416            current_thread->frame_anchor()->walkable(), "Must be walkable");
3417     current_thread->set_thread_state(_thread_blocked);
3418 
3419     r = rmonitor->raw_wait(millis, true, current_thread);
3420     // restore state, still at a safepoint safe state
3421     current_thread->set_thread_state(state);
3422 
3423 #endif /* PROPER_TRANSITIONS */
3424   } else {
3425     if (thread->is_Named_thread()) {
3426       r = rmonitor->raw_wait(millis, true, thread);
3427     } else {
3428       ShouldNotReachHere();
3429     }
3430   }
3431 
3432   switch (r) {
3433   case ObjectMonitor::OM_INTERRUPTED:
3434     return JVMTI_ERROR_INTERRUPT;
3435   case ObjectMonitor::OM_ILLEGAL_MONITOR_STATE:
3436     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3437   }
3438   assert(r == ObjectMonitor::OM_OK, "raw_wait should have worked");
3439   if (r != ObjectMonitor::OM_OK) {  // robustness
3440     return JVMTI_ERROR_INTERNAL;
3441   }
3442 
3443   return JVMTI_ERROR_NONE;
3444 } /* end RawMonitorWait */
3445 
3446 
3447 // rmonitor - pre-checked for validity
3448 jvmtiError
3449 JvmtiEnv::RawMonitorNotify(JvmtiRawMonitor * rmonitor) {
3450   int r = 0;
3451   Thread* thread = Thread::current();
3452 
3453   if (thread->is_Java_thread()) {
3454     JavaThread* current_thread = (JavaThread*)thread;
3455     // Not really unknown but ThreadInVMfromNative does more than we want
3456     ThreadInVMfromUnknown __tiv;
3457     r = rmonitor->raw_notify(current_thread);
3458   } else {
3459     if (thread->is_Named_thread()) {
3460       r = rmonitor->raw_notify(thread);
3461     } else {
3462       ShouldNotReachHere();
3463     }
3464   }
3465 
3466   if (r == ObjectMonitor::OM_ILLEGAL_MONITOR_STATE) {
3467     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3468   }
3469   assert(r == ObjectMonitor::OM_OK, "raw_notify should have worked");
3470   if (r != ObjectMonitor::OM_OK) {  // robustness
3471     return JVMTI_ERROR_INTERNAL;
3472   }
3473 
3474   return JVMTI_ERROR_NONE;
3475 } /* end RawMonitorNotify */
3476 
3477 
3478 // rmonitor - pre-checked for validity
3479 jvmtiError
3480 JvmtiEnv::RawMonitorNotifyAll(JvmtiRawMonitor * rmonitor) {
3481   int r = 0;
3482   Thread* thread = Thread::current();
3483 
3484   if (thread->is_Java_thread()) {
3485     JavaThread* current_thread = (JavaThread*)thread;
3486     ThreadInVMfromUnknown __tiv;
3487     r = rmonitor->raw_notifyAll(current_thread);
3488   } else {
3489     if (thread->is_Named_thread()) {
3490       r = rmonitor->raw_notifyAll(thread);
3491     } else {
3492       ShouldNotReachHere();
3493     }
3494   }
3495 
3496   if (r == ObjectMonitor::OM_ILLEGAL_MONITOR_STATE) {
3497     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3498   }
3499   assert(r == ObjectMonitor::OM_OK, "raw_notifyAll should have worked");
3500   if (r != ObjectMonitor::OM_OK) {  // robustness
3501     return JVMTI_ERROR_INTERNAL;
3502   }
3503 
3504   return JVMTI_ERROR_NONE;
3505 } /* end RawMonitorNotifyAll */
3506 
3507 
3508   //
3509   // JNI Function Interception functions
3510   //
3511 
3512 
3513 // function_table - pre-checked for NULL
3514 jvmtiError
3515 JvmtiEnv::SetJNIFunctionTable(const jniNativeInterface* function_table) {
3516   // Copy jni function table at safepoint.
3517   VM_JNIFunctionTableCopier copier(function_table);
3518   VMThread::execute(&copier);
3519 
3520   return JVMTI_ERROR_NONE;
3521 } /* end SetJNIFunctionTable */
3522 
3523 
3524 // function_table - pre-checked for NULL
3525 jvmtiError
3526 JvmtiEnv::GetJNIFunctionTable(jniNativeInterface** function_table) {
3527   *function_table=(jniNativeInterface*)jvmtiMalloc(sizeof(jniNativeInterface));
3528   if (*function_table == NULL)
3529     return JVMTI_ERROR_OUT_OF_MEMORY;
3530   memcpy(*function_table,(JavaThread::current())->get_jni_functions(),sizeof(jniNativeInterface));
3531   return JVMTI_ERROR_NONE;
3532 } /* end GetJNIFunctionTable */
3533 
3534 
3535   //
3536   // Event Management functions
3537   //
3538 
3539 jvmtiError
3540 JvmtiEnv::GenerateEvents(jvmtiEvent event_type) {
3541   // can only generate two event types
3542   if (event_type != JVMTI_EVENT_COMPILED_METHOD_LOAD &&
3543       event_type != JVMTI_EVENT_DYNAMIC_CODE_GENERATED) {
3544     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
3545   }
3546 
3547   // for compiled_method_load events we must check that the environment
3548   // has the can_generate_compiled_method_load_events capability.
3549   if (event_type == JVMTI_EVENT_COMPILED_METHOD_LOAD) {
3550     if (get_capabilities()->can_generate_compiled_method_load_events == 0) {
3551       return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
3552     }
3553     return JvmtiCodeBlobEvents::generate_compiled_method_load_events(this);
3554   } else {
3555     return JvmtiCodeBlobEvents::generate_dynamic_code_events(this);
3556   }
3557 
3558 } /* end GenerateEvents */
3559 
3560 
3561   //
3562   // Extension Mechanism functions
3563   //
3564 
3565 // extension_count_ptr - pre-checked for NULL
3566 // extensions - pre-checked for NULL
3567 jvmtiError
3568 JvmtiEnv::GetExtensionFunctions(jint* extension_count_ptr, jvmtiExtensionFunctionInfo** extensions) {
3569   return JvmtiExtensions::get_functions(this, extension_count_ptr, extensions);
3570 } /* end GetExtensionFunctions */
3571 
3572 
3573 // extension_count_ptr - pre-checked for NULL
3574 // extensions - pre-checked for NULL
3575 jvmtiError
3576 JvmtiEnv::GetExtensionEvents(jint* extension_count_ptr, jvmtiExtensionEventInfo** extensions) {
3577   return JvmtiExtensions::get_events(this, extension_count_ptr, extensions);
3578 } /* end GetExtensionEvents */
3579 
3580 
3581 // callback - NULL is a valid value, must be checked
3582 jvmtiError
3583 JvmtiEnv::SetExtensionEventCallback(jint extension_event_index, jvmtiExtensionEvent callback) {
3584   return JvmtiExtensions::set_event_callback(this, extension_event_index, callback);
3585 } /* end SetExtensionEventCallback */
3586 
3587   //
3588   // Timers functions
3589   //
3590 
3591 // info_ptr - pre-checked for NULL
3592 jvmtiError
3593 JvmtiEnv::GetCurrentThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {
3594   os::current_thread_cpu_time_info(info_ptr);
3595   return JVMTI_ERROR_NONE;
3596 } /* end GetCurrentThreadCpuTimerInfo */
3597 
3598 
3599 // nanos_ptr - pre-checked for NULL
3600 jvmtiError
3601 JvmtiEnv::GetCurrentThreadCpuTime(jlong* nanos_ptr) {
3602   *nanos_ptr = os::current_thread_cpu_time();
3603   return JVMTI_ERROR_NONE;
3604 } /* end GetCurrentThreadCpuTime */
3605 
3606 
3607 // info_ptr - pre-checked for NULL
3608 jvmtiError
3609 JvmtiEnv::GetThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {
3610   os::thread_cpu_time_info(info_ptr);
3611   return JVMTI_ERROR_NONE;
3612 } /* end GetThreadCpuTimerInfo */
3613 
3614 
3615 // Threads_lock NOT held, java_thread not protected by lock
3616 // java_thread - pre-checked
3617 // nanos_ptr - pre-checked for NULL
3618 jvmtiError
3619 JvmtiEnv::GetThreadCpuTime(JavaThread* java_thread, jlong* nanos_ptr) {
3620   *nanos_ptr = os::thread_cpu_time(java_thread);
3621   return JVMTI_ERROR_NONE;
3622 } /* end GetThreadCpuTime */
3623 
3624 
3625 // info_ptr - pre-checked for NULL
3626 jvmtiError
3627 JvmtiEnv::GetTimerInfo(jvmtiTimerInfo* info_ptr) {
3628   os::javaTimeNanos_info(info_ptr);
3629   return JVMTI_ERROR_NONE;
3630 } /* end GetTimerInfo */
3631 
3632 
3633 // nanos_ptr - pre-checked for NULL
3634 jvmtiError
3635 JvmtiEnv::GetTime(jlong* nanos_ptr) {
3636   *nanos_ptr = os::javaTimeNanos();
3637   return JVMTI_ERROR_NONE;
3638 } /* end GetTime */
3639 
3640 
3641 // processor_count_ptr - pre-checked for NULL
3642 jvmtiError
3643 JvmtiEnv::GetAvailableProcessors(jint* processor_count_ptr) {
3644   *processor_count_ptr = os::active_processor_count();
3645   return JVMTI_ERROR_NONE;
3646 } /* end GetAvailableProcessors */
3647 
3648 jvmtiError
3649 JvmtiEnv::SetHeapSamplingInterval(jint sampling_interval) {
3650   if (sampling_interval < 0) {
3651     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
3652   }
3653   ThreadHeapSampler::set_sampling_interval(sampling_interval);
3654   return JVMTI_ERROR_NONE;
3655 } /* end SetHeapSamplingInterval */
3656 
3657   //
3658   // System Properties functions
3659   //
3660 
3661 // count_ptr - pre-checked for NULL
3662 // property_ptr - pre-checked for NULL
3663 jvmtiError
3664 JvmtiEnv::GetSystemProperties(jint* count_ptr, char*** property_ptr) {
3665   jvmtiError err = JVMTI_ERROR_NONE;
3666 
3667   // Get the number of readable properties.
3668   *count_ptr = Arguments::PropertyList_readable_count(Arguments::system_properties());
3669 
3670   // Allocate memory to hold the exact number of readable properties.
3671   err = allocate(*count_ptr * sizeof(char *), (unsigned char **)property_ptr);
3672   if (err != JVMTI_ERROR_NONE) {
3673     return err;
3674   }
3675   int readable_count = 0;
3676   // Loop through the system properties until all the readable properties are found.
3677   for (SystemProperty* p = Arguments::system_properties(); p != NULL && readable_count < *count_ptr; p = p->next()) {
3678     if (p->is_readable()) {
3679       const char *key = p->key();
3680       char **tmp_value = *property_ptr+readable_count;
3681       readable_count++;
3682       err = allocate((strlen(key)+1) * sizeof(char), (unsigned char**)tmp_value);
3683       if (err == JVMTI_ERROR_NONE) {
3684         strcpy(*tmp_value, key);
3685       } else {
3686         // clean up previously allocated memory.
3687         for (int j=0; j<readable_count; j++) {
3688           Deallocate((unsigned char*)*property_ptr+j);
3689         }
3690         Deallocate((unsigned char*)property_ptr);
3691         break;
3692       }
3693     }
3694   }
3695   assert(err != JVMTI_ERROR_NONE || readable_count == *count_ptr, "Bad readable property count");
3696   return err;
3697 } /* end GetSystemProperties */
3698 
3699 
3700 // property - pre-checked for NULL
3701 // value_ptr - pre-checked for NULL
3702 jvmtiError
3703 JvmtiEnv::GetSystemProperty(const char* property, char** value_ptr) {
3704   jvmtiError err = JVMTI_ERROR_NONE;
3705   const char *value;
3706 
3707   // Return JVMTI_ERROR_NOT_AVAILABLE if property is not readable or doesn't exist.
3708   value = Arguments::PropertyList_get_readable_value(Arguments::system_properties(), property);
3709   if (value == NULL) {
3710     err =  JVMTI_ERROR_NOT_AVAILABLE;
3711   } else {
3712     err = allocate((strlen(value)+1) * sizeof(char), (unsigned char **)value_ptr);
3713     if (err == JVMTI_ERROR_NONE) {
3714       strcpy(*value_ptr, value);
3715     }
3716   }
3717   return err;
3718 } /* end GetSystemProperty */
3719 
3720 
3721 // property - pre-checked for NULL
3722 // value - NULL is a valid value, must be checked
3723 jvmtiError
3724 JvmtiEnv::SetSystemProperty(const char* property, const char* value_ptr) {
3725   jvmtiError err =JVMTI_ERROR_NOT_AVAILABLE;
3726 
3727   for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
3728     if (strcmp(property, p->key()) == 0) {
3729       if (p->set_writeable_value(value_ptr)) {
3730         err =  JVMTI_ERROR_NONE;
3731       }
3732     }
3733   }
3734   return err;
3735 } /* end SetSystemProperty */