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