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