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