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