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