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