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