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