1 /*
   2  * Copyright (c) 2003, 2017, 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   if (initial_object != NULL) {
1800     oop init_obj = JNIHandles::resolve_external_guard(initial_object);
1801     if (init_obj == NULL) {
1802       return JVMTI_ERROR_INVALID_OBJECT;
1803     }
1804   }
1805 
1806   Thread *thread = Thread::current();
1807   HandleMark hm(thread);
1808   KlassHandle kh (thread, k_oop);
1809 
1810   TraceTime t("FollowReferences", TRACETIME_LOG(Debug, jvmti, objecttagging));
1811   JvmtiTagMap::tag_map_for(this)->follow_references(heap_filter, kh, initial_object, callbacks, user_data);
1812   return JVMTI_ERROR_NONE;
1813 } /* end FollowReferences */
1814 
1815 
1816 // klass - NULL is a valid value, must be checked
1817 // callbacks - pre-checked for NULL
1818 // user_data - NULL is a valid value, must be checked
1819 jvmtiError
1820 JvmtiEnv::IterateThroughHeap(jint heap_filter, jclass klass, const jvmtiHeapCallbacks* callbacks, const void* user_data) {
1821   // check klass if provided
1822   Klass* k_oop = NULL;
1823   if (klass != NULL) {
1824     oop k_mirror = JNIHandles::resolve_external_guard(klass);
1825     if (k_mirror == NULL) {
1826       return JVMTI_ERROR_INVALID_CLASS;
1827     }
1828     if (java_lang_Class::is_primitive(k_mirror)) {
1829       return JVMTI_ERROR_NONE;
1830     }
1831     k_oop = java_lang_Class::as_Klass(k_mirror);
1832     if (k_oop == NULL) {
1833       return JVMTI_ERROR_INVALID_CLASS;
1834     }
1835   }
1836 
1837   Thread *thread = Thread::current();
1838   HandleMark hm(thread);
1839   KlassHandle kh (thread, k_oop);
1840 
1841   TraceTime t("IterateThroughHeap", TRACETIME_LOG(Debug, jvmti, objecttagging));
1842   JvmtiTagMap::tag_map_for(this)->iterate_through_heap(heap_filter, kh, callbacks, user_data);
1843   return JVMTI_ERROR_NONE;
1844 } /* end IterateThroughHeap */
1845 
1846 
1847 // tag_ptr - pre-checked for NULL
1848 jvmtiError
1849 JvmtiEnv::GetTag(jobject object, jlong* tag_ptr) {
1850   oop o = JNIHandles::resolve_external_guard(object);
1851   NULL_CHECK(o, JVMTI_ERROR_INVALID_OBJECT);
1852   *tag_ptr = JvmtiTagMap::tag_map_for(this)->get_tag(object);
1853   return JVMTI_ERROR_NONE;
1854 } /* end GetTag */
1855 
1856 
1857 jvmtiError
1858 JvmtiEnv::SetTag(jobject object, jlong tag) {
1859   oop o = JNIHandles::resolve_external_guard(object);
1860   NULL_CHECK(o, JVMTI_ERROR_INVALID_OBJECT);
1861   JvmtiTagMap::tag_map_for(this)->set_tag(object, tag);
1862   return JVMTI_ERROR_NONE;
1863 } /* end SetTag */
1864 
1865 
1866 // tag_count - pre-checked to be greater than or equal to 0
1867 // tags - pre-checked for NULL
1868 // count_ptr - pre-checked for NULL
1869 // object_result_ptr - NULL is a valid value, must be checked
1870 // tag_result_ptr - NULL is a valid value, must be checked
1871 jvmtiError
1872 JvmtiEnv::GetObjectsWithTags(jint tag_count, const jlong* tags, jint* count_ptr, jobject** object_result_ptr, jlong** tag_result_ptr) {
1873   TraceTime t("GetObjectsWithTags", TRACETIME_LOG(Debug, jvmti, objecttagging));
1874   return JvmtiTagMap::tag_map_for(this)->get_objects_with_tags((jlong*)tags, tag_count, count_ptr, object_result_ptr, tag_result_ptr);
1875 } /* end GetObjectsWithTags */
1876 
1877 
1878 jvmtiError
1879 JvmtiEnv::ForceGarbageCollection() {
1880   Universe::heap()->collect(GCCause::_jvmti_force_gc);
1881   return JVMTI_ERROR_NONE;
1882 } /* end ForceGarbageCollection */
1883 
1884 
1885   //
1886   // Heap (1.0) functions
1887   //
1888 
1889 // object_reference_callback - pre-checked for NULL
1890 // user_data - NULL is a valid value, must be checked
1891 jvmtiError
1892 JvmtiEnv::IterateOverObjectsReachableFromObject(jobject object, jvmtiObjectReferenceCallback object_reference_callback, const void* user_data) {
1893   oop o = JNIHandles::resolve_external_guard(object);
1894   NULL_CHECK(o, JVMTI_ERROR_INVALID_OBJECT);
1895   JvmtiTagMap::tag_map_for(this)->iterate_over_objects_reachable_from_object(object, object_reference_callback, user_data);
1896   return JVMTI_ERROR_NONE;
1897 } /* end IterateOverObjectsReachableFromObject */
1898 
1899 
1900 // heap_root_callback - NULL is a valid value, must be checked
1901 // stack_ref_callback - NULL is a valid value, must be checked
1902 // object_ref_callback - NULL is a valid value, must be checked
1903 // user_data - NULL is a valid value, must be checked
1904 jvmtiError
1905 JvmtiEnv::IterateOverReachableObjects(jvmtiHeapRootCallback heap_root_callback, jvmtiStackReferenceCallback stack_ref_callback, jvmtiObjectReferenceCallback object_ref_callback, const void* user_data) {
1906   TraceTime t("IterateOverReachableObjects", TRACETIME_LOG(Debug, jvmti, objecttagging));
1907   JvmtiTagMap::tag_map_for(this)->iterate_over_reachable_objects(heap_root_callback, stack_ref_callback, object_ref_callback, user_data);
1908   return JVMTI_ERROR_NONE;
1909 } /* end IterateOverReachableObjects */
1910 
1911 
1912 // heap_object_callback - pre-checked for NULL
1913 // user_data - NULL is a valid value, must be checked
1914 jvmtiError
1915 JvmtiEnv::IterateOverHeap(jvmtiHeapObjectFilter object_filter, jvmtiHeapObjectCallback heap_object_callback, const void* user_data) {
1916   TraceTime t("IterateOverHeap", TRACETIME_LOG(Debug, jvmti, objecttagging));
1917   Thread *thread = Thread::current();
1918   HandleMark hm(thread);
1919   JvmtiTagMap::tag_map_for(this)->iterate_over_heap(object_filter, KlassHandle(), heap_object_callback, user_data);
1920   return JVMTI_ERROR_NONE;
1921 } /* end IterateOverHeap */
1922 
1923 
1924 // k_mirror - may be primitive, this must be checked
1925 // heap_object_callback - pre-checked for NULL
1926 // user_data - NULL is a valid value, must be checked
1927 jvmtiError
1928 JvmtiEnv::IterateOverInstancesOfClass(oop k_mirror, jvmtiHeapObjectFilter object_filter, jvmtiHeapObjectCallback heap_object_callback, const void* user_data) {
1929   if (java_lang_Class::is_primitive(k_mirror)) {
1930     // DO PRIMITIVE CLASS PROCESSING
1931     return JVMTI_ERROR_NONE;
1932   }
1933   Klass* k_oop = java_lang_Class::as_Klass(k_mirror);
1934   if (k_oop == NULL) {
1935     return JVMTI_ERROR_INVALID_CLASS;
1936   }
1937   Thread *thread = Thread::current();
1938   HandleMark hm(thread);
1939   KlassHandle klass (thread, k_oop);
1940   TraceTime t("IterateOverInstancesOfClass", TRACETIME_LOG(Debug, jvmti, objecttagging));
1941   JvmtiTagMap::tag_map_for(this)->iterate_over_heap(object_filter, klass, heap_object_callback, user_data);
1942   return JVMTI_ERROR_NONE;
1943 } /* end IterateOverInstancesOfClass */
1944 
1945 
1946   //
1947   // Local Variable functions
1948   //
1949 
1950 // Threads_lock NOT held, java_thread not protected by lock
1951 // java_thread - pre-checked
1952 // java_thread - unchecked
1953 // depth - pre-checked as non-negative
1954 // value_ptr - pre-checked for NULL
1955 jvmtiError
1956 JvmtiEnv::GetLocalObject(JavaThread* java_thread, jint depth, jint slot, jobject* value_ptr) {
1957   JavaThread* current_thread = JavaThread::current();
1958   // rm object is created to clean up the javaVFrame created in
1959   // doit_prologue(), but after doit() is finished with it.
1960   ResourceMark rm(current_thread);
1961 
1962   VM_GetOrSetLocal op(java_thread, current_thread, depth, slot);
1963   VMThread::execute(&op);
1964   jvmtiError err = op.result();
1965   if (err != JVMTI_ERROR_NONE) {
1966     return err;
1967   } else {
1968     *value_ptr = op.value().l;
1969     return JVMTI_ERROR_NONE;
1970   }
1971 } /* end GetLocalObject */
1972 
1973 // Threads_lock NOT held, java_thread not protected by lock
1974 // java_thread - pre-checked
1975 // java_thread - unchecked
1976 // depth - pre-checked as non-negative
1977 // value - pre-checked for NULL
1978 jvmtiError
1979 JvmtiEnv::GetLocalInstance(JavaThread* java_thread, jint depth, jobject* value_ptr){
1980   JavaThread* current_thread = JavaThread::current();
1981   // rm object is created to clean up the javaVFrame created in
1982   // doit_prologue(), but after doit() is finished with it.
1983   ResourceMark rm(current_thread);
1984 
1985   VM_GetReceiver op(java_thread, current_thread, depth);
1986   VMThread::execute(&op);
1987   jvmtiError err = op.result();
1988   if (err != JVMTI_ERROR_NONE) {
1989     return err;
1990   } else {
1991     *value_ptr = op.value().l;
1992     return JVMTI_ERROR_NONE;
1993   }
1994 } /* end GetLocalInstance */
1995 
1996 
1997 // Threads_lock NOT held, java_thread not protected by lock
1998 // java_thread - pre-checked
1999 // java_thread - unchecked
2000 // depth - pre-checked as non-negative
2001 // value_ptr - pre-checked for NULL
2002 jvmtiError
2003 JvmtiEnv::GetLocalInt(JavaThread* java_thread, jint depth, jint slot, jint* value_ptr) {
2004   // rm object is created to clean up the javaVFrame created in
2005   // doit_prologue(), but after doit() is finished with it.
2006   ResourceMark rm;
2007 
2008   VM_GetOrSetLocal op(java_thread, depth, slot, T_INT);
2009   VMThread::execute(&op);
2010   *value_ptr = op.value().i;
2011   return op.result();
2012 } /* end GetLocalInt */
2013 
2014 
2015 // Threads_lock NOT held, java_thread not protected by lock
2016 // java_thread - pre-checked
2017 // java_thread - unchecked
2018 // depth - pre-checked as non-negative
2019 // value_ptr - pre-checked for NULL
2020 jvmtiError
2021 JvmtiEnv::GetLocalLong(JavaThread* java_thread, jint depth, jint slot, jlong* value_ptr) {
2022   // rm object is created to clean up the javaVFrame created in
2023   // doit_prologue(), but after doit() is finished with it.
2024   ResourceMark rm;
2025 
2026   VM_GetOrSetLocal op(java_thread, depth, slot, T_LONG);
2027   VMThread::execute(&op);
2028   *value_ptr = op.value().j;
2029   return op.result();
2030 } /* end GetLocalLong */
2031 
2032 
2033 // Threads_lock NOT held, java_thread not protected by lock
2034 // java_thread - pre-checked
2035 // java_thread - unchecked
2036 // depth - pre-checked as non-negative
2037 // value_ptr - pre-checked for NULL
2038 jvmtiError
2039 JvmtiEnv::GetLocalFloat(JavaThread* java_thread, jint depth, jint slot, jfloat* value_ptr) {
2040   // rm object is created to clean up the javaVFrame created in
2041   // doit_prologue(), but after doit() is finished with it.
2042   ResourceMark rm;
2043 
2044   VM_GetOrSetLocal op(java_thread, depth, slot, T_FLOAT);
2045   VMThread::execute(&op);
2046   *value_ptr = op.value().f;
2047   return op.result();
2048 } /* end GetLocalFloat */
2049 
2050 
2051 // Threads_lock NOT held, java_thread not protected by lock
2052 // java_thread - pre-checked
2053 // java_thread - unchecked
2054 // depth - pre-checked as non-negative
2055 // value_ptr - pre-checked for NULL
2056 jvmtiError
2057 JvmtiEnv::GetLocalDouble(JavaThread* java_thread, jint depth, jint slot, jdouble* value_ptr) {
2058   // rm object is created to clean up the javaVFrame created in
2059   // doit_prologue(), but after doit() is finished with it.
2060   ResourceMark rm;
2061 
2062   VM_GetOrSetLocal op(java_thread, depth, slot, T_DOUBLE);
2063   VMThread::execute(&op);
2064   *value_ptr = op.value().d;
2065   return op.result();
2066 } /* end GetLocalDouble */
2067 
2068 
2069 // Threads_lock NOT held, java_thread not protected by lock
2070 // java_thread - pre-checked
2071 // java_thread - unchecked
2072 // depth - pre-checked as non-negative
2073 jvmtiError
2074 JvmtiEnv::SetLocalObject(JavaThread* java_thread, jint depth, jint slot, jobject value) {
2075   // rm object is created to clean up the javaVFrame created in
2076   // doit_prologue(), but after doit() is finished with it.
2077   ResourceMark rm;
2078   jvalue val;
2079   val.l = value;
2080   VM_GetOrSetLocal op(java_thread, depth, slot, T_OBJECT, val);
2081   VMThread::execute(&op);
2082   return op.result();
2083 } /* end SetLocalObject */
2084 
2085 
2086 // Threads_lock NOT held, java_thread not protected by lock
2087 // java_thread - pre-checked
2088 // java_thread - unchecked
2089 // depth - pre-checked as non-negative
2090 jvmtiError
2091 JvmtiEnv::SetLocalInt(JavaThread* java_thread, jint depth, jint slot, jint value) {
2092   // rm object is created to clean up the javaVFrame created in
2093   // doit_prologue(), but after doit() is finished with it.
2094   ResourceMark rm;
2095   jvalue val;
2096   val.i = value;
2097   VM_GetOrSetLocal op(java_thread, depth, slot, T_INT, val);
2098   VMThread::execute(&op);
2099   return op.result();
2100 } /* end SetLocalInt */
2101 
2102 
2103 // Threads_lock NOT held, java_thread not protected by lock
2104 // java_thread - pre-checked
2105 // java_thread - unchecked
2106 // depth - pre-checked as non-negative
2107 jvmtiError
2108 JvmtiEnv::SetLocalLong(JavaThread* java_thread, jint depth, jint slot, jlong value) {
2109   // rm object is created to clean up the javaVFrame created in
2110   // doit_prologue(), but after doit() is finished with it.
2111   ResourceMark rm;
2112   jvalue val;
2113   val.j = value;
2114   VM_GetOrSetLocal op(java_thread, depth, slot, T_LONG, val);
2115   VMThread::execute(&op);
2116   return op.result();
2117 } /* end SetLocalLong */
2118 
2119 
2120 // Threads_lock NOT held, java_thread not protected by lock
2121 // java_thread - pre-checked
2122 // java_thread - unchecked
2123 // depth - pre-checked as non-negative
2124 jvmtiError
2125 JvmtiEnv::SetLocalFloat(JavaThread* java_thread, jint depth, jint slot, jfloat value) {
2126   // rm object is created to clean up the javaVFrame created in
2127   // doit_prologue(), but after doit() is finished with it.
2128   ResourceMark rm;
2129   jvalue val;
2130   val.f = value;
2131   VM_GetOrSetLocal op(java_thread, depth, slot, T_FLOAT, val);
2132   VMThread::execute(&op);
2133   return op.result();
2134 } /* end SetLocalFloat */
2135 
2136 
2137 // Threads_lock NOT held, java_thread not protected by lock
2138 // java_thread - pre-checked
2139 // java_thread - unchecked
2140 // depth - pre-checked as non-negative
2141 jvmtiError
2142 JvmtiEnv::SetLocalDouble(JavaThread* java_thread, jint depth, jint slot, jdouble value) {
2143   // rm object is created to clean up the javaVFrame created in
2144   // doit_prologue(), but after doit() is finished with it.
2145   ResourceMark rm;
2146   jvalue val;
2147   val.d = value;
2148   VM_GetOrSetLocal op(java_thread, depth, slot, T_DOUBLE, val);
2149   VMThread::execute(&op);
2150   return op.result();
2151 } /* end SetLocalDouble */
2152 
2153 
2154   //
2155   // Breakpoint functions
2156   //
2157 
2158 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2159 jvmtiError
2160 JvmtiEnv::SetBreakpoint(Method* method_oop, jlocation location) {
2161   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2162   if (location < 0) {   // simple invalid location check first
2163     return JVMTI_ERROR_INVALID_LOCATION;
2164   }
2165   // verify that the breakpoint is not past the end of the method
2166   if (location >= (jlocation) method_oop->code_size()) {
2167     return JVMTI_ERROR_INVALID_LOCATION;
2168   }
2169 
2170   ResourceMark rm;
2171   JvmtiBreakpoint bp(method_oop, location);
2172   JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
2173   if (jvmti_breakpoints.set(bp) == JVMTI_ERROR_DUPLICATE)
2174     return JVMTI_ERROR_DUPLICATE;
2175 
2176   if (TraceJVMTICalls) {
2177     jvmti_breakpoints.print();
2178   }
2179 
2180   return JVMTI_ERROR_NONE;
2181 } /* end SetBreakpoint */
2182 
2183 
2184 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2185 jvmtiError
2186 JvmtiEnv::ClearBreakpoint(Method* method_oop, jlocation location) {
2187   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2188 
2189   if (location < 0) {   // simple invalid location check first
2190     return JVMTI_ERROR_INVALID_LOCATION;
2191   }
2192 
2193   // verify that the breakpoint is not past the end of the method
2194   if (location >= (jlocation) method_oop->code_size()) {
2195     return JVMTI_ERROR_INVALID_LOCATION;
2196   }
2197 
2198   JvmtiBreakpoint bp(method_oop, location);
2199 
2200   JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
2201   if (jvmti_breakpoints.clear(bp) == JVMTI_ERROR_NOT_FOUND)
2202     return JVMTI_ERROR_NOT_FOUND;
2203 
2204   if (TraceJVMTICalls) {
2205     jvmti_breakpoints.print();
2206   }
2207 
2208   return JVMTI_ERROR_NONE;
2209 } /* end ClearBreakpoint */
2210 
2211 
2212   //
2213   // Watched Field functions
2214   //
2215 
2216 jvmtiError
2217 JvmtiEnv::SetFieldAccessWatch(fieldDescriptor* fdesc_ptr) {
2218   // make sure we haven't set this watch before
2219   if (fdesc_ptr->is_field_access_watched()) return JVMTI_ERROR_DUPLICATE;
2220   fdesc_ptr->set_is_field_access_watched(true);
2221 
2222   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_ACCESS, true);
2223 
2224   return JVMTI_ERROR_NONE;
2225 } /* end SetFieldAccessWatch */
2226 
2227 
2228 jvmtiError
2229 JvmtiEnv::ClearFieldAccessWatch(fieldDescriptor* fdesc_ptr) {
2230   // make sure we have a watch to clear
2231   if (!fdesc_ptr->is_field_access_watched()) return JVMTI_ERROR_NOT_FOUND;
2232   fdesc_ptr->set_is_field_access_watched(false);
2233 
2234   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_ACCESS, false);
2235 
2236   return JVMTI_ERROR_NONE;
2237 } /* end ClearFieldAccessWatch */
2238 
2239 
2240 jvmtiError
2241 JvmtiEnv::SetFieldModificationWatch(fieldDescriptor* fdesc_ptr) {
2242   // make sure we haven't set this watch before
2243   if (fdesc_ptr->is_field_modification_watched()) return JVMTI_ERROR_DUPLICATE;
2244   fdesc_ptr->set_is_field_modification_watched(true);
2245 
2246   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_MODIFICATION, true);
2247 
2248   return JVMTI_ERROR_NONE;
2249 } /* end SetFieldModificationWatch */
2250 
2251 
2252 jvmtiError
2253 JvmtiEnv::ClearFieldModificationWatch(fieldDescriptor* fdesc_ptr) {
2254    // make sure we have a watch to clear
2255   if (!fdesc_ptr->is_field_modification_watched()) return JVMTI_ERROR_NOT_FOUND;
2256   fdesc_ptr->set_is_field_modification_watched(false);
2257 
2258   JvmtiEventController::change_field_watch(JVMTI_EVENT_FIELD_MODIFICATION, false);
2259 
2260   return JVMTI_ERROR_NONE;
2261 } /* end ClearFieldModificationWatch */
2262 
2263   //
2264   // Class functions
2265   //
2266 
2267 
2268 // k_mirror - may be primitive, this must be checked
2269 // signature_ptr - NULL is a valid value, must be checked
2270 // generic_ptr - NULL is a valid value, must be checked
2271 jvmtiError
2272 JvmtiEnv::GetClassSignature(oop k_mirror, char** signature_ptr, char** generic_ptr) {
2273   ResourceMark rm;
2274   bool isPrimitive = java_lang_Class::is_primitive(k_mirror);
2275   Klass* k = NULL;
2276   if (!isPrimitive) {
2277     k = java_lang_Class::as_Klass(k_mirror);
2278     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2279   }
2280   if (signature_ptr != NULL) {
2281     char* result = NULL;
2282     if (isPrimitive) {
2283       char tchar = type2char(java_lang_Class::primitive_type(k_mirror));
2284       result = (char*) jvmtiMalloc(2);
2285       result[0] = tchar;
2286       result[1] = '\0';
2287     } else {
2288       const char* class_sig = k->signature_name();
2289       result = (char *) jvmtiMalloc(strlen(class_sig)+1);
2290       strcpy(result, class_sig);
2291     }
2292     *signature_ptr = result;
2293   }
2294   if (generic_ptr != NULL) {
2295     *generic_ptr = NULL;
2296     if (!isPrimitive && k->is_instance_klass()) {
2297       Symbol* soo = InstanceKlass::cast(k)->generic_signature();
2298       if (soo != NULL) {
2299         const char *gen_sig = soo->as_C_string();
2300         if (gen_sig != NULL) {
2301           char* gen_result;
2302           jvmtiError err = allocate(strlen(gen_sig) + 1,
2303                                     (unsigned char **)&gen_result);
2304           if (err != JVMTI_ERROR_NONE) {
2305             return err;
2306           }
2307           strcpy(gen_result, gen_sig);
2308           *generic_ptr = gen_result;
2309         }
2310       }
2311     }
2312   }
2313   return JVMTI_ERROR_NONE;
2314 } /* end GetClassSignature */
2315 
2316 
2317 // k_mirror - may be primitive, this must be checked
2318 // status_ptr - pre-checked for NULL
2319 jvmtiError
2320 JvmtiEnv::GetClassStatus(oop k_mirror, jint* status_ptr) {
2321   jint result = 0;
2322   if (java_lang_Class::is_primitive(k_mirror)) {
2323     result |= JVMTI_CLASS_STATUS_PRIMITIVE;
2324   } else {
2325     Klass* k = java_lang_Class::as_Klass(k_mirror);
2326     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2327     result = k->jvmti_class_status();
2328   }
2329   *status_ptr = result;
2330 
2331   return JVMTI_ERROR_NONE;
2332 } /* end GetClassStatus */
2333 
2334 
2335 // k_mirror - may be primitive, this must be checked
2336 // source_name_ptr - pre-checked for NULL
2337 jvmtiError
2338 JvmtiEnv::GetSourceFileName(oop k_mirror, char** source_name_ptr) {
2339   if (java_lang_Class::is_primitive(k_mirror)) {
2340      return JVMTI_ERROR_ABSENT_INFORMATION;
2341   }
2342   Klass* k_klass = java_lang_Class::as_Klass(k_mirror);
2343   NULL_CHECK(k_klass, JVMTI_ERROR_INVALID_CLASS);
2344 
2345   if (!k_klass->is_instance_klass()) {
2346     return JVMTI_ERROR_ABSENT_INFORMATION;
2347   }
2348 
2349   Symbol* sfnOop = InstanceKlass::cast(k_klass)->source_file_name();
2350   NULL_CHECK(sfnOop, JVMTI_ERROR_ABSENT_INFORMATION);
2351   {
2352     JavaThread* current_thread  = JavaThread::current();
2353     ResourceMark rm(current_thread);
2354     const char* sfncp = (const char*) sfnOop->as_C_string();
2355     *source_name_ptr = (char *) jvmtiMalloc(strlen(sfncp)+1);
2356     strcpy(*source_name_ptr, sfncp);
2357   }
2358 
2359   return JVMTI_ERROR_NONE;
2360 } /* end GetSourceFileName */
2361 
2362 
2363 // k_mirror - may be primitive, this must be checked
2364 // modifiers_ptr - pre-checked for NULL
2365 jvmtiError
2366 JvmtiEnv::GetClassModifiers(oop k_mirror, jint* modifiers_ptr) {
2367   JavaThread* current_thread  = JavaThread::current();
2368   jint result = 0;
2369   if (!java_lang_Class::is_primitive(k_mirror)) {
2370     Klass* k = java_lang_Class::as_Klass(k_mirror);
2371     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2372     result = k->compute_modifier_flags(current_thread);
2373     JavaThread* THREAD = current_thread; // pass to macros
2374     if (HAS_PENDING_EXCEPTION) {
2375       CLEAR_PENDING_EXCEPTION;
2376       return JVMTI_ERROR_INTERNAL;
2377     };
2378 
2379     // Reset the deleted  ACC_SUPER bit ( deleted in compute_modifier_flags()).
2380     if(k->is_super()) {
2381       result |= JVM_ACC_SUPER;
2382     }
2383   } else {
2384     result = (JVM_ACC_ABSTRACT | JVM_ACC_FINAL | JVM_ACC_PUBLIC);
2385   }
2386   *modifiers_ptr = result;
2387 
2388   return JVMTI_ERROR_NONE;
2389 } /* end GetClassModifiers */
2390 
2391 
2392 // k_mirror - may be primitive, this must be checked
2393 // method_count_ptr - pre-checked for NULL
2394 // methods_ptr - pre-checked for NULL
2395 jvmtiError
2396 JvmtiEnv::GetClassMethods(oop k_mirror, jint* method_count_ptr, jmethodID** methods_ptr) {
2397   JavaThread* current_thread  = JavaThread::current();
2398   HandleMark hm(current_thread);
2399 
2400   if (java_lang_Class::is_primitive(k_mirror)) {
2401     *method_count_ptr = 0;
2402     *methods_ptr = (jmethodID*) jvmtiMalloc(0 * sizeof(jmethodID));
2403     return JVMTI_ERROR_NONE;
2404   }
2405   Klass* k = java_lang_Class::as_Klass(k_mirror);
2406   NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2407 
2408   // Return CLASS_NOT_PREPARED error as per JVMTI spec.
2409   if (!(k->jvmti_class_status() & (JVMTI_CLASS_STATUS_PREPARED|JVMTI_CLASS_STATUS_ARRAY) )) {
2410     return JVMTI_ERROR_CLASS_NOT_PREPARED;
2411   }
2412 
2413   if (!k->is_instance_klass()) {
2414     *method_count_ptr = 0;
2415     *methods_ptr = (jmethodID*) jvmtiMalloc(0 * sizeof(jmethodID));
2416     return JVMTI_ERROR_NONE;
2417   }
2418   instanceKlassHandle instanceK_h(current_thread, k);
2419   // Allocate the result and fill it in
2420   int result_length = instanceK_h->methods()->length();
2421   jmethodID* result_list = (jmethodID*)jvmtiMalloc(result_length * sizeof(jmethodID));
2422   int index;
2423   bool jmethodids_found = true;
2424 
2425   if (JvmtiExport::can_maintain_original_method_order()) {
2426     // Use the original method ordering indices stored in the class, so we can emit
2427     // jmethodIDs in the order they appeared in the class file
2428     for (index = 0; index < result_length; index++) {
2429       Method* m = instanceK_h->methods()->at(index);
2430       int original_index = instanceK_h->method_ordering()->at(index);
2431       assert(original_index >= 0 && original_index < result_length, "invalid original method index");
2432       jmethodID id;
2433       if (jmethodids_found) {
2434         id = m->find_jmethod_id_or_null();
2435         if (id == NULL) {
2436           // If we find an uninitialized value, make sure there is
2437           // enough space for all the uninitialized values we might
2438           // find.
2439           instanceK_h->ensure_space_for_methodids(index);
2440           jmethodids_found = false;
2441           id = m->jmethod_id();
2442         }
2443       } else {
2444         id = m->jmethod_id();
2445       }
2446       result_list[original_index] = id;
2447     }
2448   } else {
2449     // otherwise just copy in any order
2450     for (index = 0; index < result_length; index++) {
2451       Method* m = instanceK_h->methods()->at(index);
2452       jmethodID id;
2453       if (jmethodids_found) {
2454         id = m->find_jmethod_id_or_null();
2455         if (id == NULL) {
2456           // If we find an uninitialized value, make sure there is
2457           // enough space for all the uninitialized values we might
2458           // find.
2459           instanceK_h->ensure_space_for_methodids(index);
2460           jmethodids_found = false;
2461           id = m->jmethod_id();
2462         }
2463       } else {
2464         id = m->jmethod_id();
2465       }
2466       result_list[index] = id;
2467     }
2468   }
2469   // Fill in return value.
2470   *method_count_ptr = result_length;
2471   *methods_ptr = result_list;
2472 
2473   return JVMTI_ERROR_NONE;
2474 } /* end GetClassMethods */
2475 
2476 
2477 // k_mirror - may be primitive, this must be checked
2478 // field_count_ptr - pre-checked for NULL
2479 // fields_ptr - pre-checked for NULL
2480 jvmtiError
2481 JvmtiEnv::GetClassFields(oop k_mirror, jint* field_count_ptr, jfieldID** fields_ptr) {
2482   if (java_lang_Class::is_primitive(k_mirror)) {
2483     *field_count_ptr = 0;
2484     *fields_ptr = (jfieldID*) jvmtiMalloc(0 * sizeof(jfieldID));
2485     return JVMTI_ERROR_NONE;
2486   }
2487   JavaThread* current_thread = JavaThread::current();
2488   HandleMark hm(current_thread);
2489   Klass* k = java_lang_Class::as_Klass(k_mirror);
2490   NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2491 
2492   // Return CLASS_NOT_PREPARED error as per JVMTI spec.
2493   if (!(k->jvmti_class_status() & (JVMTI_CLASS_STATUS_PREPARED|JVMTI_CLASS_STATUS_ARRAY) )) {
2494     return JVMTI_ERROR_CLASS_NOT_PREPARED;
2495   }
2496 
2497   if (!k->is_instance_klass()) {
2498     *field_count_ptr = 0;
2499     *fields_ptr = (jfieldID*) jvmtiMalloc(0 * sizeof(jfieldID));
2500     return JVMTI_ERROR_NONE;
2501   }
2502 
2503 
2504   instanceKlassHandle instanceK_h(current_thread, k);
2505 
2506   int result_count = 0;
2507   // First, count the fields.
2508   FilteredFieldStream flds(instanceK_h, true, true);
2509   result_count = flds.field_count();
2510 
2511   // Allocate the result and fill it in
2512   jfieldID* result_list = (jfieldID*) jvmtiMalloc(result_count * sizeof(jfieldID));
2513   // The JVMTI spec requires fields in the order they occur in the class file,
2514   // this is the reverse order of what FieldStream hands out.
2515   int id_index = (result_count - 1);
2516 
2517   for (FilteredFieldStream src_st(instanceK_h, true, true); !src_st.eos(); src_st.next()) {
2518     result_list[id_index--] = jfieldIDWorkaround::to_jfieldID(
2519                                             instanceK_h, src_st.offset(),
2520                                             src_st.access_flags().is_static());
2521   }
2522   assert(id_index == -1, "just checking");
2523   // Fill in the results
2524   *field_count_ptr = result_count;
2525   *fields_ptr = result_list;
2526 
2527   return JVMTI_ERROR_NONE;
2528 } /* end GetClassFields */
2529 
2530 
2531 // k_mirror - may be primitive, this must be checked
2532 // interface_count_ptr - pre-checked for NULL
2533 // interfaces_ptr - pre-checked for NULL
2534 jvmtiError
2535 JvmtiEnv::GetImplementedInterfaces(oop k_mirror, jint* interface_count_ptr, jclass** interfaces_ptr) {
2536   {
2537     if (java_lang_Class::is_primitive(k_mirror)) {
2538       *interface_count_ptr = 0;
2539       *interfaces_ptr = (jclass*) jvmtiMalloc(0 * sizeof(jclass));
2540       return JVMTI_ERROR_NONE;
2541     }
2542     JavaThread* current_thread = JavaThread::current();
2543     HandleMark hm(current_thread);
2544     Klass* k = java_lang_Class::as_Klass(k_mirror);
2545     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2546 
2547     // Return CLASS_NOT_PREPARED error as per JVMTI spec.
2548     if (!(k->jvmti_class_status() & (JVMTI_CLASS_STATUS_PREPARED|JVMTI_CLASS_STATUS_ARRAY) ))
2549       return JVMTI_ERROR_CLASS_NOT_PREPARED;
2550 
2551     if (!k->is_instance_klass()) {
2552       *interface_count_ptr = 0;
2553       *interfaces_ptr = (jclass*) jvmtiMalloc(0 * sizeof(jclass));
2554       return JVMTI_ERROR_NONE;
2555     }
2556 
2557     Array<Klass*>* interface_list = InstanceKlass::cast(k)->local_interfaces();
2558     const int result_length = (interface_list == NULL ? 0 : interface_list->length());
2559     jclass* result_list = (jclass*) jvmtiMalloc(result_length * sizeof(jclass));
2560     for (int i_index = 0; i_index < result_length; i_index += 1) {
2561       Klass* klass_at = interface_list->at(i_index);
2562       assert(klass_at->is_klass(), "interfaces must be Klass*s");
2563       assert(klass_at->is_interface(), "interfaces must be interfaces");
2564       oop mirror_at = klass_at->java_mirror();
2565       Handle handle_at = Handle(current_thread, mirror_at);
2566       result_list[i_index] = (jclass) jni_reference(handle_at);
2567     }
2568     *interface_count_ptr = result_length;
2569     *interfaces_ptr = result_list;
2570   }
2571 
2572   return JVMTI_ERROR_NONE;
2573 } /* end GetImplementedInterfaces */
2574 
2575 
2576 // k_mirror - may be primitive, this must be checked
2577 // minor_version_ptr - pre-checked for NULL
2578 // major_version_ptr - pre-checked for NULL
2579 jvmtiError
2580 JvmtiEnv::GetClassVersionNumbers(oop k_mirror, jint* minor_version_ptr, jint* major_version_ptr) {
2581   if (java_lang_Class::is_primitive(k_mirror)) {
2582     return JVMTI_ERROR_ABSENT_INFORMATION;
2583   }
2584   Klass* k_oop = java_lang_Class::as_Klass(k_mirror);
2585   Thread *thread = Thread::current();
2586   HandleMark hm(thread);
2587   KlassHandle klass(thread, k_oop);
2588 
2589   jint status = klass->jvmti_class_status();
2590   if (status & (JVMTI_CLASS_STATUS_ERROR)) {
2591     return JVMTI_ERROR_INVALID_CLASS;
2592   }
2593   if (status & (JVMTI_CLASS_STATUS_ARRAY)) {
2594     return JVMTI_ERROR_ABSENT_INFORMATION;
2595   }
2596 
2597   instanceKlassHandle ik(thread, k_oop);
2598   *minor_version_ptr = ik->minor_version();
2599   *major_version_ptr = ik->major_version();
2600 
2601   return JVMTI_ERROR_NONE;
2602 } /* end GetClassVersionNumbers */
2603 
2604 
2605 // k_mirror - may be primitive, this must be checked
2606 // constant_pool_count_ptr - pre-checked for NULL
2607 // constant_pool_byte_count_ptr - pre-checked for NULL
2608 // constant_pool_bytes_ptr - pre-checked for NULL
2609 jvmtiError
2610 JvmtiEnv::GetConstantPool(oop k_mirror, jint* constant_pool_count_ptr, jint* constant_pool_byte_count_ptr, unsigned char** constant_pool_bytes_ptr) {
2611   if (java_lang_Class::is_primitive(k_mirror)) {
2612     return JVMTI_ERROR_ABSENT_INFORMATION;
2613   }
2614 
2615   Klass* k_oop = java_lang_Class::as_Klass(k_mirror);
2616   Thread *thread = Thread::current();
2617   HandleMark hm(thread);
2618   ResourceMark rm(thread);
2619   KlassHandle klass(thread, k_oop);
2620 
2621   jint status = klass->jvmti_class_status();
2622   if (status & (JVMTI_CLASS_STATUS_ERROR)) {
2623     return JVMTI_ERROR_INVALID_CLASS;
2624   }
2625   if (status & (JVMTI_CLASS_STATUS_ARRAY)) {
2626     return JVMTI_ERROR_ABSENT_INFORMATION;
2627   }
2628 
2629   instanceKlassHandle ikh(thread, k_oop);
2630   JvmtiConstantPoolReconstituter reconstituter(ikh);
2631   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2632     return reconstituter.get_error();
2633   }
2634 
2635   unsigned char *cpool_bytes;
2636   int cpool_size = reconstituter.cpool_size();
2637   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2638     return reconstituter.get_error();
2639   }
2640   jvmtiError res = allocate(cpool_size, &cpool_bytes);
2641   if (res != JVMTI_ERROR_NONE) {
2642     return res;
2643   }
2644   reconstituter.copy_cpool_bytes(cpool_bytes);
2645   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2646     return reconstituter.get_error();
2647   }
2648 
2649   constantPoolHandle  constants(thread, ikh->constants());
2650   *constant_pool_count_ptr      = constants->length();
2651   *constant_pool_byte_count_ptr = cpool_size;
2652   *constant_pool_bytes_ptr      = cpool_bytes;
2653 
2654   return JVMTI_ERROR_NONE;
2655 } /* end GetConstantPool */
2656 
2657 
2658 // k_mirror - may be primitive, this must be checked
2659 // is_interface_ptr - pre-checked for NULL
2660 jvmtiError
2661 JvmtiEnv::IsInterface(oop k_mirror, jboolean* is_interface_ptr) {
2662   {
2663     bool result = false;
2664     if (!java_lang_Class::is_primitive(k_mirror)) {
2665       Klass* k = java_lang_Class::as_Klass(k_mirror);
2666       if (k != NULL && k->is_interface()) {
2667         result = true;
2668       }
2669     }
2670     *is_interface_ptr = result;
2671   }
2672 
2673   return JVMTI_ERROR_NONE;
2674 } /* end IsInterface */
2675 
2676 
2677 // k_mirror - may be primitive, this must be checked
2678 // is_array_class_ptr - pre-checked for NULL
2679 jvmtiError
2680 JvmtiEnv::IsArrayClass(oop k_mirror, jboolean* is_array_class_ptr) {
2681   {
2682     bool result = false;
2683     if (!java_lang_Class::is_primitive(k_mirror)) {
2684       Klass* k = java_lang_Class::as_Klass(k_mirror);
2685       if (k != NULL && k->is_array_klass()) {
2686         result = true;
2687       }
2688     }
2689     *is_array_class_ptr = result;
2690   }
2691 
2692   return JVMTI_ERROR_NONE;
2693 } /* end IsArrayClass */
2694 
2695 
2696 // k_mirror - may be primitive, this must be checked
2697 // classloader_ptr - pre-checked for NULL
2698 jvmtiError
2699 JvmtiEnv::GetClassLoader(oop k_mirror, jobject* classloader_ptr) {
2700   {
2701     if (java_lang_Class::is_primitive(k_mirror)) {
2702       *classloader_ptr = (jclass) jni_reference(Handle());
2703       return JVMTI_ERROR_NONE;
2704     }
2705     JavaThread* current_thread = JavaThread::current();
2706     HandleMark hm(current_thread);
2707     Klass* k = java_lang_Class::as_Klass(k_mirror);
2708     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2709 
2710     oop result_oop = k->class_loader();
2711     if (result_oop == NULL) {
2712       *classloader_ptr = (jclass) jni_reference(Handle());
2713       return JVMTI_ERROR_NONE;
2714     }
2715     Handle result_handle = Handle(current_thread, result_oop);
2716     jclass result_jnihandle = (jclass) jni_reference(result_handle);
2717     *classloader_ptr = result_jnihandle;
2718   }
2719   return JVMTI_ERROR_NONE;
2720 } /* end GetClassLoader */
2721 
2722 
2723 // k_mirror - may be primitive, this must be checked
2724 // source_debug_extension_ptr - pre-checked for NULL
2725 jvmtiError
2726 JvmtiEnv::GetSourceDebugExtension(oop k_mirror, char** source_debug_extension_ptr) {
2727   {
2728     if (java_lang_Class::is_primitive(k_mirror)) {
2729       return JVMTI_ERROR_ABSENT_INFORMATION;
2730     }
2731     Klass* k = java_lang_Class::as_Klass(k_mirror);
2732     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2733     if (!k->is_instance_klass()) {
2734       return JVMTI_ERROR_ABSENT_INFORMATION;
2735     }
2736     const char* sde = InstanceKlass::cast(k)->source_debug_extension();
2737     NULL_CHECK(sde, JVMTI_ERROR_ABSENT_INFORMATION);
2738 
2739     {
2740       *source_debug_extension_ptr = (char *) jvmtiMalloc(strlen(sde)+1);
2741       strcpy(*source_debug_extension_ptr, sde);
2742     }
2743   }
2744 
2745   return JVMTI_ERROR_NONE;
2746 } /* end GetSourceDebugExtension */
2747 
2748   //
2749   // Object functions
2750   //
2751 
2752 // hash_code_ptr - pre-checked for NULL
2753 jvmtiError
2754 JvmtiEnv::GetObjectHashCode(jobject object, jint* hash_code_ptr) {
2755   oop mirror = JNIHandles::resolve_external_guard(object);
2756   NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
2757   NULL_CHECK(hash_code_ptr, JVMTI_ERROR_NULL_POINTER);
2758 
2759   {
2760     jint result = (jint) mirror->identity_hash();
2761     *hash_code_ptr = result;
2762   }
2763   return JVMTI_ERROR_NONE;
2764 } /* end GetObjectHashCode */
2765 
2766 
2767 // info_ptr - pre-checked for NULL
2768 jvmtiError
2769 JvmtiEnv::GetObjectMonitorUsage(jobject object, jvmtiMonitorUsage* info_ptr) {
2770   JavaThread* calling_thread = JavaThread::current();
2771   jvmtiError err = get_object_monitor_usage(calling_thread, object, info_ptr);
2772   if (err == JVMTI_ERROR_THREAD_NOT_SUSPENDED) {
2773     // Some of the critical threads were not suspended. go to a safepoint and try again
2774     VM_GetObjectMonitorUsage op(this, calling_thread, object, info_ptr);
2775     VMThread::execute(&op);
2776     err = op.result();
2777   }
2778   return err;
2779 } /* end GetObjectMonitorUsage */
2780 
2781 
2782   //
2783   // Field functions
2784   //
2785 
2786 // name_ptr - NULL is a valid value, must be checked
2787 // signature_ptr - NULL is a valid value, must be checked
2788 // generic_ptr - NULL is a valid value, must be checked
2789 jvmtiError
2790 JvmtiEnv::GetFieldName(fieldDescriptor* fdesc_ptr, char** name_ptr, char** signature_ptr, char** generic_ptr) {
2791   JavaThread* current_thread  = JavaThread::current();
2792   ResourceMark rm(current_thread);
2793   if (name_ptr == NULL) {
2794     // just don't return the name
2795   } else {
2796     const char* fieldName = fdesc_ptr->name()->as_C_string();
2797     *name_ptr =  (char*) jvmtiMalloc(strlen(fieldName) + 1);
2798     if (*name_ptr == NULL)
2799       return JVMTI_ERROR_OUT_OF_MEMORY;
2800     strcpy(*name_ptr, fieldName);
2801   }
2802   if (signature_ptr== NULL) {
2803     // just don't return the signature
2804   } else {
2805     const char* fieldSignature = fdesc_ptr->signature()->as_C_string();
2806     *signature_ptr = (char*) jvmtiMalloc(strlen(fieldSignature) + 1);
2807     if (*signature_ptr == NULL)
2808       return JVMTI_ERROR_OUT_OF_MEMORY;
2809     strcpy(*signature_ptr, fieldSignature);
2810   }
2811   if (generic_ptr != NULL) {
2812     *generic_ptr = NULL;
2813     Symbol* soop = fdesc_ptr->generic_signature();
2814     if (soop != NULL) {
2815       const char* gen_sig = soop->as_C_string();
2816       if (gen_sig != NULL) {
2817         jvmtiError err = allocate(strlen(gen_sig) + 1, (unsigned char **)generic_ptr);
2818         if (err != JVMTI_ERROR_NONE) {
2819           return err;
2820         }
2821         strcpy(*generic_ptr, gen_sig);
2822       }
2823     }
2824   }
2825   return JVMTI_ERROR_NONE;
2826 } /* end GetFieldName */
2827 
2828 
2829 // declaring_class_ptr - pre-checked for NULL
2830 jvmtiError
2831 JvmtiEnv::GetFieldDeclaringClass(fieldDescriptor* fdesc_ptr, jclass* declaring_class_ptr) {
2832 
2833   *declaring_class_ptr = get_jni_class_non_null(fdesc_ptr->field_holder());
2834   return JVMTI_ERROR_NONE;
2835 } /* end GetFieldDeclaringClass */
2836 
2837 
2838 // modifiers_ptr - pre-checked for NULL
2839 jvmtiError
2840 JvmtiEnv::GetFieldModifiers(fieldDescriptor* fdesc_ptr, jint* modifiers_ptr) {
2841 
2842   AccessFlags resultFlags = fdesc_ptr->access_flags();
2843   jint result = resultFlags.as_int();
2844   *modifiers_ptr = result;
2845 
2846   return JVMTI_ERROR_NONE;
2847 } /* end GetFieldModifiers */
2848 
2849 
2850 // is_synthetic_ptr - pre-checked for NULL
2851 jvmtiError
2852 JvmtiEnv::IsFieldSynthetic(fieldDescriptor* fdesc_ptr, jboolean* is_synthetic_ptr) {
2853   *is_synthetic_ptr = fdesc_ptr->is_synthetic();
2854   return JVMTI_ERROR_NONE;
2855 } /* end IsFieldSynthetic */
2856 
2857 
2858   //
2859   // Method functions
2860   //
2861 
2862 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2863 // name_ptr - NULL is a valid value, must be checked
2864 // signature_ptr - NULL is a valid value, must be checked
2865 // generic_ptr - NULL is a valid value, must be checked
2866 jvmtiError
2867 JvmtiEnv::GetMethodName(Method* method_oop, char** name_ptr, char** signature_ptr, char** generic_ptr) {
2868   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2869   JavaThread* current_thread  = JavaThread::current();
2870 
2871   ResourceMark rm(current_thread); // get the utf8 name and signature
2872   if (name_ptr == NULL) {
2873     // just don't return the name
2874   } else {
2875     const char* utf8_name = (const char *) method_oop->name()->as_utf8();
2876     *name_ptr = (char *) jvmtiMalloc(strlen(utf8_name)+1);
2877     strcpy(*name_ptr, utf8_name);
2878   }
2879   if (signature_ptr == NULL) {
2880     // just don't return the signature
2881   } else {
2882     const char* utf8_signature = (const char *) method_oop->signature()->as_utf8();
2883     *signature_ptr = (char *) jvmtiMalloc(strlen(utf8_signature) + 1);
2884     strcpy(*signature_ptr, utf8_signature);
2885   }
2886 
2887   if (generic_ptr != NULL) {
2888     *generic_ptr = NULL;
2889     Symbol* soop = method_oop->generic_signature();
2890     if (soop != NULL) {
2891       const char* gen_sig = soop->as_C_string();
2892       if (gen_sig != NULL) {
2893         jvmtiError err = allocate(strlen(gen_sig) + 1, (unsigned char **)generic_ptr);
2894         if (err != JVMTI_ERROR_NONE) {
2895           return err;
2896         }
2897         strcpy(*generic_ptr, gen_sig);
2898       }
2899     }
2900   }
2901   return JVMTI_ERROR_NONE;
2902 } /* end GetMethodName */
2903 
2904 
2905 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2906 // declaring_class_ptr - pre-checked for NULL
2907 jvmtiError
2908 JvmtiEnv::GetMethodDeclaringClass(Method* method_oop, jclass* declaring_class_ptr) {
2909   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2910   (*declaring_class_ptr) = get_jni_class_non_null(method_oop->method_holder());
2911   return JVMTI_ERROR_NONE;
2912 } /* end GetMethodDeclaringClass */
2913 
2914 
2915 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2916 // modifiers_ptr - pre-checked for NULL
2917 jvmtiError
2918 JvmtiEnv::GetMethodModifiers(Method* method_oop, jint* modifiers_ptr) {
2919   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2920   (*modifiers_ptr) = method_oop->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2921   return JVMTI_ERROR_NONE;
2922 } /* end GetMethodModifiers */
2923 
2924 
2925 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2926 // max_ptr - pre-checked for NULL
2927 jvmtiError
2928 JvmtiEnv::GetMaxLocals(Method* method_oop, jint* max_ptr) {
2929   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2930   // get max stack
2931   (*max_ptr) = method_oop->max_locals();
2932   return JVMTI_ERROR_NONE;
2933 } /* end GetMaxLocals */
2934 
2935 
2936 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2937 // size_ptr - pre-checked for NULL
2938 jvmtiError
2939 JvmtiEnv::GetArgumentsSize(Method* method_oop, jint* size_ptr) {
2940   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2941   // get size of arguments
2942 
2943   (*size_ptr) = method_oop->size_of_parameters();
2944   return JVMTI_ERROR_NONE;
2945 } /* end GetArgumentsSize */
2946 
2947 
2948 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2949 // entry_count_ptr - pre-checked for NULL
2950 // table_ptr - pre-checked for NULL
2951 jvmtiError
2952 JvmtiEnv::GetLineNumberTable(Method* method_oop, jint* entry_count_ptr, jvmtiLineNumberEntry** table_ptr) {
2953   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2954   if (!method_oop->has_linenumber_table()) {
2955     return (JVMTI_ERROR_ABSENT_INFORMATION);
2956   }
2957 
2958   // The line number table is compressed so we don't know how big it is until decompressed.
2959   // Decompression is really fast so we just do it twice.
2960 
2961   // Compute size of table
2962   jint num_entries = 0;
2963   CompressedLineNumberReadStream stream(method_oop->compressed_linenumber_table());
2964   while (stream.read_pair()) {
2965     num_entries++;
2966   }
2967   jvmtiLineNumberEntry *jvmti_table =
2968             (jvmtiLineNumberEntry *)jvmtiMalloc(num_entries * (sizeof(jvmtiLineNumberEntry)));
2969 
2970   // Fill jvmti table
2971   if (num_entries > 0) {
2972     int index = 0;
2973     CompressedLineNumberReadStream stream(method_oop->compressed_linenumber_table());
2974     while (stream.read_pair()) {
2975       jvmti_table[index].start_location = (jlocation) stream.bci();
2976       jvmti_table[index].line_number = (jint) stream.line();
2977       index++;
2978     }
2979     assert(index == num_entries, "sanity check");
2980   }
2981 
2982   // Set up results
2983   (*entry_count_ptr) = num_entries;
2984   (*table_ptr) = jvmti_table;
2985 
2986   return JVMTI_ERROR_NONE;
2987 } /* end GetLineNumberTable */
2988 
2989 
2990 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2991 // start_location_ptr - pre-checked for NULL
2992 // end_location_ptr - pre-checked for NULL
2993 jvmtiError
2994 JvmtiEnv::GetMethodLocation(Method* method_oop, jlocation* start_location_ptr, jlocation* end_location_ptr) {
2995 
2996   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2997   // get start and end location
2998   (*end_location_ptr) = (jlocation) (method_oop->code_size() - 1);
2999   if (method_oop->code_size() == 0) {
3000     // there is no code so there is no start location
3001     (*start_location_ptr) = (jlocation)(-1);
3002   } else {
3003     (*start_location_ptr) = (jlocation)(0);
3004   }
3005 
3006   return JVMTI_ERROR_NONE;
3007 } /* end GetMethodLocation */
3008 
3009 
3010 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3011 // entry_count_ptr - pre-checked for NULL
3012 // table_ptr - pre-checked for NULL
3013 jvmtiError
3014 JvmtiEnv::GetLocalVariableTable(Method* method_oop, jint* entry_count_ptr, jvmtiLocalVariableEntry** table_ptr) {
3015 
3016   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3017   JavaThread* current_thread  = JavaThread::current();
3018 
3019   // does the klass have any local variable information?
3020   InstanceKlass* ik = method_oop->method_holder();
3021   if (!ik->access_flags().has_localvariable_table()) {
3022     return (JVMTI_ERROR_ABSENT_INFORMATION);
3023   }
3024 
3025   ConstantPool* constants = method_oop->constants();
3026   NULL_CHECK(constants, JVMTI_ERROR_ABSENT_INFORMATION);
3027 
3028   // in the vm localvariable table representation, 6 consecutive elements in the table
3029   // represent a 6-tuple of shorts
3030   // [start_pc, length, name_index, descriptor_index, signature_index, index]
3031   jint num_entries = method_oop->localvariable_table_length();
3032   jvmtiLocalVariableEntry *jvmti_table = (jvmtiLocalVariableEntry *)
3033                 jvmtiMalloc(num_entries * (sizeof(jvmtiLocalVariableEntry)));
3034 
3035   if (num_entries > 0) {
3036     LocalVariableTableElement* table = method_oop->localvariable_table_start();
3037     for (int i = 0; i < num_entries; i++) {
3038       // get the 5 tuple information from the vm table
3039       jlocation start_location = (jlocation) table[i].start_bci;
3040       jint length = (jint) table[i].length;
3041       int name_index = (int) table[i].name_cp_index;
3042       int signature_index = (int) table[i].descriptor_cp_index;
3043       int generic_signature_index = (int) table[i].signature_cp_index;
3044       jint slot = (jint) table[i].slot;
3045 
3046       // get utf8 name and signature
3047       char *name_buf = NULL;
3048       char *sig_buf = NULL;
3049       char *gen_sig_buf = NULL;
3050       {
3051         ResourceMark rm(current_thread);
3052 
3053         const char *utf8_name = (const char *) constants->symbol_at(name_index)->as_utf8();
3054         name_buf = (char *) jvmtiMalloc(strlen(utf8_name)+1);
3055         strcpy(name_buf, utf8_name);
3056 
3057         const char *utf8_signature = (const char *) constants->symbol_at(signature_index)->as_utf8();
3058         sig_buf = (char *) jvmtiMalloc(strlen(utf8_signature)+1);
3059         strcpy(sig_buf, utf8_signature);
3060 
3061         if (generic_signature_index > 0) {
3062           const char *utf8_gen_sign = (const char *)
3063                                        constants->symbol_at(generic_signature_index)->as_utf8();
3064           gen_sig_buf = (char *) jvmtiMalloc(strlen(utf8_gen_sign)+1);
3065           strcpy(gen_sig_buf, utf8_gen_sign);
3066         }
3067       }
3068 
3069       // fill in the jvmti local variable table
3070       jvmti_table[i].start_location = start_location;
3071       jvmti_table[i].length = length;
3072       jvmti_table[i].name = name_buf;
3073       jvmti_table[i].signature = sig_buf;
3074       jvmti_table[i].generic_signature = gen_sig_buf;
3075       jvmti_table[i].slot = slot;
3076     }
3077   }
3078 
3079   // set results
3080   (*entry_count_ptr) = num_entries;
3081   (*table_ptr) = jvmti_table;
3082 
3083   return JVMTI_ERROR_NONE;
3084 } /* end GetLocalVariableTable */
3085 
3086 
3087 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3088 // bytecode_count_ptr - pre-checked for NULL
3089 // bytecodes_ptr - pre-checked for NULL
3090 jvmtiError
3091 JvmtiEnv::GetBytecodes(Method* method_oop, jint* bytecode_count_ptr, unsigned char** bytecodes_ptr) {
3092   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3093 
3094   HandleMark hm;
3095   methodHandle method(method_oop);
3096   jint size = (jint)method->code_size();
3097   jvmtiError err = allocate(size, bytecodes_ptr);
3098   if (err != JVMTI_ERROR_NONE) {
3099     return err;
3100   }
3101 
3102   (*bytecode_count_ptr) = size;
3103   // get byte codes
3104   JvmtiClassFileReconstituter::copy_bytecodes(method, *bytecodes_ptr);
3105 
3106   return JVMTI_ERROR_NONE;
3107 } /* end GetBytecodes */
3108 
3109 
3110 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3111 // is_native_ptr - pre-checked for NULL
3112 jvmtiError
3113 JvmtiEnv::IsMethodNative(Method* method_oop, jboolean* is_native_ptr) {
3114   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3115   (*is_native_ptr) = method_oop->is_native();
3116   return JVMTI_ERROR_NONE;
3117 } /* end IsMethodNative */
3118 
3119 
3120 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3121 // is_synthetic_ptr - pre-checked for NULL
3122 jvmtiError
3123 JvmtiEnv::IsMethodSynthetic(Method* method_oop, jboolean* is_synthetic_ptr) {
3124   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3125   (*is_synthetic_ptr) = method_oop->is_synthetic();
3126   return JVMTI_ERROR_NONE;
3127 } /* end IsMethodSynthetic */
3128 
3129 
3130 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3131 // is_obsolete_ptr - pre-checked for NULL
3132 jvmtiError
3133 JvmtiEnv::IsMethodObsolete(Method* method_oop, jboolean* is_obsolete_ptr) {
3134   if (use_version_1_0_semantics() &&
3135       get_capabilities()->can_redefine_classes == 0) {
3136     // This JvmtiEnv requested version 1.0 semantics and this function
3137     // requires the can_redefine_classes capability in version 1.0 so
3138     // we need to return an error here.
3139     return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
3140   }
3141 
3142   if (method_oop == NULL || method_oop->is_obsolete()) {
3143     *is_obsolete_ptr = true;
3144   } else {
3145     *is_obsolete_ptr = false;
3146   }
3147   return JVMTI_ERROR_NONE;
3148 } /* end IsMethodObsolete */
3149 
3150   //
3151   // Raw Monitor functions
3152   //
3153 
3154 // name - pre-checked for NULL
3155 // monitor_ptr - pre-checked for NULL
3156 jvmtiError
3157 JvmtiEnv::CreateRawMonitor(const char* name, jrawMonitorID* monitor_ptr) {
3158   JvmtiRawMonitor* rmonitor = new JvmtiRawMonitor(name);
3159   NULL_CHECK(rmonitor, JVMTI_ERROR_OUT_OF_MEMORY);
3160 
3161   *monitor_ptr = (jrawMonitorID)rmonitor;
3162 
3163   return JVMTI_ERROR_NONE;
3164 } /* end CreateRawMonitor */
3165 
3166 
3167 // rmonitor - pre-checked for validity
3168 jvmtiError
3169 JvmtiEnv::DestroyRawMonitor(JvmtiRawMonitor * rmonitor) {
3170   if (Threads::number_of_threads() == 0) {
3171     // Remove this  monitor from pending raw monitors list
3172     // if it has entered in onload or start phase.
3173     JvmtiPendingMonitors::destroy(rmonitor);
3174   } else {
3175     Thread* thread  = Thread::current();
3176     if (rmonitor->is_entered(thread)) {
3177       // The caller owns this monitor which we are about to destroy.
3178       // We exit the underlying synchronization object so that the
3179       // "delete monitor" call below can work without an assertion
3180       // failure on systems that don't like destroying synchronization
3181       // objects that are locked.
3182       int r;
3183       intptr_t recursion = rmonitor->recursions();
3184       for (intptr_t i=0; i <= recursion; i++) {
3185         r = rmonitor->raw_exit(thread);
3186         assert(r == ObjectMonitor::OM_OK, "raw_exit should have worked");
3187         if (r != ObjectMonitor::OM_OK) {  // robustness
3188           return JVMTI_ERROR_INTERNAL;
3189         }
3190       }
3191     }
3192     if (rmonitor->owner() != NULL) {
3193       // The caller is trying to destroy a monitor that is locked by
3194       // someone else. While this is not forbidden by the JVMTI
3195       // spec, it will cause an assertion failure on systems that don't
3196       // like destroying synchronization objects that are locked.
3197       // We indicate a problem with the error return (and leak the
3198       // monitor's memory).
3199       return JVMTI_ERROR_NOT_MONITOR_OWNER;
3200     }
3201   }
3202 
3203   delete rmonitor;
3204 
3205   return JVMTI_ERROR_NONE;
3206 } /* end DestroyRawMonitor */
3207 
3208 
3209 // rmonitor - pre-checked for validity
3210 jvmtiError
3211 JvmtiEnv::RawMonitorEnter(JvmtiRawMonitor * rmonitor) {
3212   if (Threads::number_of_threads() == 0) {
3213     // No JavaThreads exist so ObjectMonitor enter cannot be
3214     // used, add this raw monitor to the pending list.
3215     // The pending monitors will be actually entered when
3216     // the VM is setup.
3217     // See transition_pending_raw_monitors in create_vm()
3218     // in thread.cpp.
3219     JvmtiPendingMonitors::enter(rmonitor);
3220   } else {
3221     int r = 0;
3222     Thread* thread = Thread::current();
3223 
3224     if (thread->is_Java_thread()) {
3225       JavaThread* current_thread = (JavaThread*)thread;
3226 
3227 #ifdef PROPER_TRANSITIONS
3228       // Not really unknown but ThreadInVMfromNative does more than we want
3229       ThreadInVMfromUnknown __tiv;
3230       {
3231         ThreadBlockInVM __tbivm(current_thread);
3232         r = rmonitor->raw_enter(current_thread);
3233       }
3234 #else
3235       /* Transition to thread_blocked without entering vm state          */
3236       /* This is really evil. Normally you can't undo _thread_blocked    */
3237       /* transitions like this because it would cause us to miss a       */
3238       /* safepoint but since the thread was already in _thread_in_native */
3239       /* the thread is not leaving a safepoint safe state and it will    */
3240       /* block when it tries to return from native. We can't safepoint   */
3241       /* block in here because we could deadlock the vmthread. Blech.    */
3242 
3243       JavaThreadState state = current_thread->thread_state();
3244       assert(state == _thread_in_native, "Must be _thread_in_native");
3245       // frame should already be walkable since we are in native
3246       assert(!current_thread->has_last_Java_frame() ||
3247              current_thread->frame_anchor()->walkable(), "Must be walkable");
3248       current_thread->set_thread_state(_thread_blocked);
3249 
3250       r = rmonitor->raw_enter(current_thread);
3251       // restore state, still at a safepoint safe state
3252       current_thread->set_thread_state(state);
3253 
3254 #endif /* PROPER_TRANSITIONS */
3255       assert(r == ObjectMonitor::OM_OK, "raw_enter should have worked");
3256     } else {
3257       if (thread->is_VM_thread() || thread->is_ConcurrentGC_thread()) {
3258         r = rmonitor->raw_enter(thread);
3259       } else {
3260         ShouldNotReachHere();
3261       }
3262     }
3263 
3264     if (r != ObjectMonitor::OM_OK) {  // robustness
3265       return JVMTI_ERROR_INTERNAL;
3266     }
3267   }
3268   return JVMTI_ERROR_NONE;
3269 } /* end RawMonitorEnter */
3270 
3271 
3272 // rmonitor - pre-checked for validity
3273 jvmtiError
3274 JvmtiEnv::RawMonitorExit(JvmtiRawMonitor * rmonitor) {
3275   jvmtiError err = JVMTI_ERROR_NONE;
3276 
3277   if (Threads::number_of_threads() == 0) {
3278     // No JavaThreads exist so just remove this monitor from the pending list.
3279     // Bool value from exit is false if rmonitor is not in the list.
3280     if (!JvmtiPendingMonitors::exit(rmonitor)) {
3281       err = JVMTI_ERROR_NOT_MONITOR_OWNER;
3282     }
3283   } else {
3284     int r = 0;
3285     Thread* thread = Thread::current();
3286 
3287     if (thread->is_Java_thread()) {
3288       JavaThread* current_thread = (JavaThread*)thread;
3289 #ifdef PROPER_TRANSITIONS
3290       // Not really unknown but ThreadInVMfromNative does more than we want
3291       ThreadInVMfromUnknown __tiv;
3292 #endif /* PROPER_TRANSITIONS */
3293       r = rmonitor->raw_exit(current_thread);
3294     } else {
3295       if (thread->is_VM_thread() || thread->is_ConcurrentGC_thread()) {
3296         r = rmonitor->raw_exit(thread);
3297       } else {
3298         ShouldNotReachHere();
3299       }
3300     }
3301 
3302     if (r == ObjectMonitor::OM_ILLEGAL_MONITOR_STATE) {
3303       err = JVMTI_ERROR_NOT_MONITOR_OWNER;
3304     } else {
3305       assert(r == ObjectMonitor::OM_OK, "raw_exit should have worked");
3306       if (r != ObjectMonitor::OM_OK) {  // robustness
3307         err = JVMTI_ERROR_INTERNAL;
3308       }
3309     }
3310   }
3311   return err;
3312 } /* end RawMonitorExit */
3313 
3314 
3315 // rmonitor - pre-checked for validity
3316 jvmtiError
3317 JvmtiEnv::RawMonitorWait(JvmtiRawMonitor * rmonitor, jlong millis) {
3318   int r = 0;
3319   Thread* thread = Thread::current();
3320 
3321   if (thread->is_Java_thread()) {
3322     JavaThread* current_thread = (JavaThread*)thread;
3323 #ifdef PROPER_TRANSITIONS
3324     // Not really unknown but ThreadInVMfromNative does more than we want
3325     ThreadInVMfromUnknown __tiv;
3326     {
3327       ThreadBlockInVM __tbivm(current_thread);
3328       r = rmonitor->raw_wait(millis, true, current_thread);
3329     }
3330 #else
3331     /* Transition to thread_blocked without entering vm state          */
3332     /* This is really evil. Normally you can't undo _thread_blocked    */
3333     /* transitions like this because it would cause us to miss a       */
3334     /* safepoint but since the thread was already in _thread_in_native */
3335     /* the thread is not leaving a safepoint safe state and it will    */
3336     /* block when it tries to return from native. We can't safepoint   */
3337     /* block in here because we could deadlock the vmthread. Blech.    */
3338 
3339     JavaThreadState state = current_thread->thread_state();
3340     assert(state == _thread_in_native, "Must be _thread_in_native");
3341     // frame should already be walkable since we are in native
3342     assert(!current_thread->has_last_Java_frame() ||
3343            current_thread->frame_anchor()->walkable(), "Must be walkable");
3344     current_thread->set_thread_state(_thread_blocked);
3345 
3346     r = rmonitor->raw_wait(millis, true, current_thread);
3347     // restore state, still at a safepoint safe state
3348     current_thread->set_thread_state(state);
3349 
3350 #endif /* PROPER_TRANSITIONS */
3351   } else {
3352     if (thread->is_VM_thread() || thread->is_ConcurrentGC_thread()) {
3353       r = rmonitor->raw_wait(millis, true, thread);
3354     } else {
3355       ShouldNotReachHere();
3356     }
3357   }
3358 
3359   switch (r) {
3360   case ObjectMonitor::OM_INTERRUPTED:
3361     return JVMTI_ERROR_INTERRUPT;
3362   case ObjectMonitor::OM_ILLEGAL_MONITOR_STATE:
3363     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3364   }
3365   assert(r == ObjectMonitor::OM_OK, "raw_wait should have worked");
3366   if (r != ObjectMonitor::OM_OK) {  // robustness
3367     return JVMTI_ERROR_INTERNAL;
3368   }
3369 
3370   return JVMTI_ERROR_NONE;
3371 } /* end RawMonitorWait */
3372 
3373 
3374 // rmonitor - pre-checked for validity
3375 jvmtiError
3376 JvmtiEnv::RawMonitorNotify(JvmtiRawMonitor * rmonitor) {
3377   int r = 0;
3378   Thread* thread = Thread::current();
3379 
3380   if (thread->is_Java_thread()) {
3381     JavaThread* current_thread = (JavaThread*)thread;
3382     // Not really unknown but ThreadInVMfromNative does more than we want
3383     ThreadInVMfromUnknown __tiv;
3384     r = rmonitor->raw_notify(current_thread);
3385   } else {
3386     if (thread->is_VM_thread() || thread->is_ConcurrentGC_thread()) {
3387       r = rmonitor->raw_notify(thread);
3388     } else {
3389       ShouldNotReachHere();
3390     }
3391   }
3392 
3393   if (r == ObjectMonitor::OM_ILLEGAL_MONITOR_STATE) {
3394     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3395   }
3396   assert(r == ObjectMonitor::OM_OK, "raw_notify should have worked");
3397   if (r != ObjectMonitor::OM_OK) {  // robustness
3398     return JVMTI_ERROR_INTERNAL;
3399   }
3400 
3401   return JVMTI_ERROR_NONE;
3402 } /* end RawMonitorNotify */
3403 
3404 
3405 // rmonitor - pre-checked for validity
3406 jvmtiError
3407 JvmtiEnv::RawMonitorNotifyAll(JvmtiRawMonitor * rmonitor) {
3408   int r = 0;
3409   Thread* thread = Thread::current();
3410 
3411   if (thread->is_Java_thread()) {
3412     JavaThread* current_thread = (JavaThread*)thread;
3413     ThreadInVMfromUnknown __tiv;
3414     r = rmonitor->raw_notifyAll(current_thread);
3415   } else {
3416     if (thread->is_VM_thread() || thread->is_ConcurrentGC_thread()) {
3417       r = rmonitor->raw_notifyAll(thread);
3418     } else {
3419       ShouldNotReachHere();
3420     }
3421   }
3422 
3423   if (r == ObjectMonitor::OM_ILLEGAL_MONITOR_STATE) {
3424     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3425   }
3426   assert(r == ObjectMonitor::OM_OK, "raw_notifyAll should have worked");
3427   if (r != ObjectMonitor::OM_OK) {  // robustness
3428     return JVMTI_ERROR_INTERNAL;
3429   }
3430 
3431   return JVMTI_ERROR_NONE;
3432 } /* end RawMonitorNotifyAll */
3433 
3434 
3435   //
3436   // JNI Function Interception functions
3437   //
3438 
3439 
3440 // function_table - pre-checked for NULL
3441 jvmtiError
3442 JvmtiEnv::SetJNIFunctionTable(const jniNativeInterface* function_table) {
3443   // Copy jni function table at safepoint.
3444   VM_JNIFunctionTableCopier copier(function_table);
3445   VMThread::execute(&copier);
3446 
3447   return JVMTI_ERROR_NONE;
3448 } /* end SetJNIFunctionTable */
3449 
3450 
3451 // function_table - pre-checked for NULL
3452 jvmtiError
3453 JvmtiEnv::GetJNIFunctionTable(jniNativeInterface** function_table) {
3454   *function_table=(jniNativeInterface*)jvmtiMalloc(sizeof(jniNativeInterface));
3455   if (*function_table == NULL)
3456     return JVMTI_ERROR_OUT_OF_MEMORY;
3457   memcpy(*function_table,(JavaThread::current())->get_jni_functions(),sizeof(jniNativeInterface));
3458   return JVMTI_ERROR_NONE;
3459 } /* end GetJNIFunctionTable */
3460 
3461 
3462   //
3463   // Event Management functions
3464   //
3465 
3466 jvmtiError
3467 JvmtiEnv::GenerateEvents(jvmtiEvent event_type) {
3468   // can only generate two event types
3469   if (event_type != JVMTI_EVENT_COMPILED_METHOD_LOAD &&
3470       event_type != JVMTI_EVENT_DYNAMIC_CODE_GENERATED) {
3471     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
3472   }
3473 
3474   // for compiled_method_load events we must check that the environment
3475   // has the can_generate_compiled_method_load_events capability.
3476   if (event_type == JVMTI_EVENT_COMPILED_METHOD_LOAD) {
3477     if (get_capabilities()->can_generate_compiled_method_load_events == 0) {
3478       return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
3479     }
3480     return JvmtiCodeBlobEvents::generate_compiled_method_load_events(this);
3481   } else {
3482     return JvmtiCodeBlobEvents::generate_dynamic_code_events(this);
3483   }
3484 
3485 } /* end GenerateEvents */
3486 
3487 
3488   //
3489   // Extension Mechanism functions
3490   //
3491 
3492 // extension_count_ptr - pre-checked for NULL
3493 // extensions - pre-checked for NULL
3494 jvmtiError
3495 JvmtiEnv::GetExtensionFunctions(jint* extension_count_ptr, jvmtiExtensionFunctionInfo** extensions) {
3496   return JvmtiExtensions::get_functions(this, extension_count_ptr, extensions);
3497 } /* end GetExtensionFunctions */
3498 
3499 
3500 // extension_count_ptr - pre-checked for NULL
3501 // extensions - pre-checked for NULL
3502 jvmtiError
3503 JvmtiEnv::GetExtensionEvents(jint* extension_count_ptr, jvmtiExtensionEventInfo** extensions) {
3504   return JvmtiExtensions::get_events(this, extension_count_ptr, extensions);
3505 } /* end GetExtensionEvents */
3506 
3507 
3508 // callback - NULL is a valid value, must be checked
3509 jvmtiError
3510 JvmtiEnv::SetExtensionEventCallback(jint extension_event_index, jvmtiExtensionEvent callback) {
3511   return JvmtiExtensions::set_event_callback(this, extension_event_index, callback);
3512 } /* end SetExtensionEventCallback */
3513 
3514   //
3515   // Timers functions
3516   //
3517 
3518 // info_ptr - pre-checked for NULL
3519 jvmtiError
3520 JvmtiEnv::GetCurrentThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {
3521   os::current_thread_cpu_time_info(info_ptr);
3522   return JVMTI_ERROR_NONE;
3523 } /* end GetCurrentThreadCpuTimerInfo */
3524 
3525 
3526 // nanos_ptr - pre-checked for NULL
3527 jvmtiError
3528 JvmtiEnv::GetCurrentThreadCpuTime(jlong* nanos_ptr) {
3529   *nanos_ptr = os::current_thread_cpu_time();
3530   return JVMTI_ERROR_NONE;
3531 } /* end GetCurrentThreadCpuTime */
3532 
3533 
3534 // info_ptr - pre-checked for NULL
3535 jvmtiError
3536 JvmtiEnv::GetThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {
3537   os::thread_cpu_time_info(info_ptr);
3538   return JVMTI_ERROR_NONE;
3539 } /* end GetThreadCpuTimerInfo */
3540 
3541 
3542 // Threads_lock NOT held, java_thread not protected by lock
3543 // java_thread - pre-checked
3544 // nanos_ptr - pre-checked for NULL
3545 jvmtiError
3546 JvmtiEnv::GetThreadCpuTime(JavaThread* java_thread, jlong* nanos_ptr) {
3547   *nanos_ptr = os::thread_cpu_time(java_thread);
3548   return JVMTI_ERROR_NONE;
3549 } /* end GetThreadCpuTime */
3550 
3551 
3552 // info_ptr - pre-checked for NULL
3553 jvmtiError
3554 JvmtiEnv::GetTimerInfo(jvmtiTimerInfo* info_ptr) {
3555   os::javaTimeNanos_info(info_ptr);
3556   return JVMTI_ERROR_NONE;
3557 } /* end GetTimerInfo */
3558 
3559 
3560 // nanos_ptr - pre-checked for NULL
3561 jvmtiError
3562 JvmtiEnv::GetTime(jlong* nanos_ptr) {
3563   *nanos_ptr = os::javaTimeNanos();
3564   return JVMTI_ERROR_NONE;
3565 } /* end GetTime */
3566 
3567 
3568 // processor_count_ptr - pre-checked for NULL
3569 jvmtiError
3570 JvmtiEnv::GetAvailableProcessors(jint* processor_count_ptr) {
3571   *processor_count_ptr = os::active_processor_count();
3572   return JVMTI_ERROR_NONE;
3573 } /* end GetAvailableProcessors */
3574 
3575   //
3576   // System Properties functions
3577   //
3578 
3579 // count_ptr - pre-checked for NULL
3580 // property_ptr - pre-checked for NULL
3581 jvmtiError
3582 JvmtiEnv::GetSystemProperties(jint* count_ptr, char*** property_ptr) {
3583   jvmtiError err = JVMTI_ERROR_NONE;
3584 
3585   // Get the number of readable properties.
3586   *count_ptr = Arguments::PropertyList_readable_count(Arguments::system_properties());
3587 
3588   // Allocate memory to hold the exact number of readable properties.
3589   err = allocate(*count_ptr * sizeof(char *), (unsigned char **)property_ptr);
3590   if (err != JVMTI_ERROR_NONE) {
3591     return err;
3592   }
3593   int readable_count = 0;
3594   // Loop through the system properties until all the readable properties are found.
3595   for (SystemProperty* p = Arguments::system_properties(); p != NULL && readable_count < *count_ptr; p = p->next()) {
3596     if (p->is_readable()) {
3597       const char *key = p->key();
3598       char **tmp_value = *property_ptr+readable_count;
3599       readable_count++;
3600       err = allocate((strlen(key)+1) * sizeof(char), (unsigned char**)tmp_value);
3601       if (err == JVMTI_ERROR_NONE) {
3602         strcpy(*tmp_value, key);
3603       } else {
3604         // clean up previously allocated memory.
3605         for (int j=0; j<readable_count; j++) {
3606           Deallocate((unsigned char*)*property_ptr+j);
3607         }
3608         Deallocate((unsigned char*)property_ptr);
3609         break;
3610       }
3611     }
3612   }
3613   assert(err != JVMTI_ERROR_NONE || readable_count == *count_ptr, "Bad readable property count");
3614   return err;
3615 } /* end GetSystemProperties */
3616 
3617 
3618 // property - pre-checked for NULL
3619 // value_ptr - pre-checked for NULL
3620 jvmtiError
3621 JvmtiEnv::GetSystemProperty(const char* property, char** value_ptr) {
3622   jvmtiError err = JVMTI_ERROR_NONE;
3623   const char *value;
3624 
3625   // Return JVMTI_ERROR_NOT_AVAILABLE if property is not readable or doesn't exist.
3626   value = Arguments::PropertyList_get_readable_value(Arguments::system_properties(), property);
3627   if (value == NULL) {
3628     err =  JVMTI_ERROR_NOT_AVAILABLE;
3629   } else {
3630     err = allocate((strlen(value)+1) * sizeof(char), (unsigned char **)value_ptr);
3631     if (err == JVMTI_ERROR_NONE) {
3632       strcpy(*value_ptr, value);
3633     }
3634   }
3635   return err;
3636 } /* end GetSystemProperty */
3637 
3638 
3639 // property - pre-checked for NULL
3640 // value - NULL is a valid value, must be checked
3641 jvmtiError
3642 JvmtiEnv::SetSystemProperty(const char* property, const char* value_ptr) {
3643   jvmtiError err =JVMTI_ERROR_NOT_AVAILABLE;
3644 
3645   for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
3646     if (strcmp(property, p->key()) == 0) {
3647       if (p->set_writeable_value(value_ptr)) {
3648         err =  JVMTI_ERROR_NONE;
3649       }
3650     }
3651   }
3652   return err;
3653 } /* end SetSystemProperty */