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