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