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