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   java_thread->interrupt();
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                                             src_st.field_descriptor().is_flattened());
2588   }
2589   assert(id_index == -1, "just checking");
2590   // Fill in the results
2591   *field_count_ptr = result_count;
2592   *fields_ptr = result_list;
2593 
2594   return JVMTI_ERROR_NONE;
2595 } /* end GetClassFields */
2596 
2597 
2598 // k_mirror - may be primitive, this must be checked
2599 // interface_count_ptr - pre-checked for NULL
2600 // interfaces_ptr - pre-checked for NULL
2601 jvmtiError
2602 JvmtiEnv::GetImplementedInterfaces(oop k_mirror, jint* interface_count_ptr, jclass** interfaces_ptr) {
2603   {
2604     if (java_lang_Class::is_primitive(k_mirror)) {
2605       *interface_count_ptr = 0;
2606       *interfaces_ptr = (jclass*) jvmtiMalloc(0 * sizeof(jclass));
2607       return JVMTI_ERROR_NONE;
2608     }
2609     JavaThread* current_thread = JavaThread::current();
2610     HandleMark hm(current_thread);
2611     Klass* k = java_lang_Class::as_Klass(k_mirror);
2612     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2613 
2614     // Return CLASS_NOT_PREPARED error as per JVMTI spec.
2615     if (!(k->jvmti_class_status() & (JVMTI_CLASS_STATUS_PREPARED|JVMTI_CLASS_STATUS_ARRAY) ))
2616       return JVMTI_ERROR_CLASS_NOT_PREPARED;
2617 
2618     if (!k->is_instance_klass()) {
2619       *interface_count_ptr = 0;
2620       *interfaces_ptr = (jclass*) jvmtiMalloc(0 * sizeof(jclass));
2621       return JVMTI_ERROR_NONE;
2622     }
2623 
2624     Array<InstanceKlass*>* interface_list = InstanceKlass::cast(k)->local_interfaces();
2625     const int result_length = (interface_list == NULL ? 0 : interface_list->length());
2626     jclass* result_list = (jclass*) jvmtiMalloc(result_length * sizeof(jclass));
2627     for (int i_index = 0; i_index < result_length; i_index += 1) {
2628       InstanceKlass* klass_at = interface_list->at(i_index);
2629       assert(klass_at->is_klass(), "interfaces must be Klass*s");
2630       assert(klass_at->is_interface(), "interfaces must be interfaces");
2631       oop mirror_at = klass_at->java_mirror();
2632       Handle handle_at = Handle(current_thread, mirror_at);
2633       result_list[i_index] = (jclass) jni_reference(handle_at);
2634     }
2635     *interface_count_ptr = result_length;
2636     *interfaces_ptr = result_list;
2637   }
2638 
2639   return JVMTI_ERROR_NONE;
2640 } /* end GetImplementedInterfaces */
2641 
2642 
2643 // k_mirror - may be primitive, this must be checked
2644 // minor_version_ptr - pre-checked for NULL
2645 // major_version_ptr - pre-checked for NULL
2646 jvmtiError
2647 JvmtiEnv::GetClassVersionNumbers(oop k_mirror, jint* minor_version_ptr, jint* major_version_ptr) {
2648   if (java_lang_Class::is_primitive(k_mirror)) {
2649     return JVMTI_ERROR_ABSENT_INFORMATION;
2650   }
2651   Klass* klass = java_lang_Class::as_Klass(k_mirror);
2652 
2653   jint status = klass->jvmti_class_status();
2654   if (status & (JVMTI_CLASS_STATUS_ERROR)) {
2655     return JVMTI_ERROR_INVALID_CLASS;
2656   }
2657   if (status & (JVMTI_CLASS_STATUS_ARRAY)) {
2658     return JVMTI_ERROR_ABSENT_INFORMATION;
2659   }
2660 
2661   InstanceKlass* ik = InstanceKlass::cast(klass);
2662   *minor_version_ptr = ik->minor_version();
2663   *major_version_ptr = ik->major_version();
2664 
2665   return JVMTI_ERROR_NONE;
2666 } /* end GetClassVersionNumbers */
2667 
2668 
2669 // k_mirror - may be primitive, this must be checked
2670 // constant_pool_count_ptr - pre-checked for NULL
2671 // constant_pool_byte_count_ptr - pre-checked for NULL
2672 // constant_pool_bytes_ptr - pre-checked for NULL
2673 jvmtiError
2674 JvmtiEnv::GetConstantPool(oop k_mirror, jint* constant_pool_count_ptr, jint* constant_pool_byte_count_ptr, unsigned char** constant_pool_bytes_ptr) {
2675   if (java_lang_Class::is_primitive(k_mirror)) {
2676     return JVMTI_ERROR_ABSENT_INFORMATION;
2677   }
2678 
2679   Klass* klass = java_lang_Class::as_Klass(k_mirror);
2680   Thread *thread = Thread::current();
2681   ResourceMark rm(thread);
2682 
2683   jint status = klass->jvmti_class_status();
2684   if (status & (JVMTI_CLASS_STATUS_ERROR)) {
2685     return JVMTI_ERROR_INVALID_CLASS;
2686   }
2687   if (status & (JVMTI_CLASS_STATUS_ARRAY)) {
2688     return JVMTI_ERROR_ABSENT_INFORMATION;
2689   }
2690 
2691   InstanceKlass* ik = InstanceKlass::cast(klass);
2692   JvmtiConstantPoolReconstituter reconstituter(ik);
2693   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2694     return reconstituter.get_error();
2695   }
2696 
2697   unsigned char *cpool_bytes;
2698   int cpool_size = reconstituter.cpool_size();
2699   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2700     return reconstituter.get_error();
2701   }
2702   jvmtiError res = allocate(cpool_size, &cpool_bytes);
2703   if (res != JVMTI_ERROR_NONE) {
2704     return res;
2705   }
2706   reconstituter.copy_cpool_bytes(cpool_bytes);
2707   if (reconstituter.get_error() != JVMTI_ERROR_NONE) {
2708     return reconstituter.get_error();
2709   }
2710 
2711   constantPoolHandle  constants(thread, ik->constants());
2712   *constant_pool_count_ptr      = constants->length();
2713   *constant_pool_byte_count_ptr = cpool_size;
2714   *constant_pool_bytes_ptr      = cpool_bytes;
2715 
2716   return JVMTI_ERROR_NONE;
2717 } /* end GetConstantPool */
2718 
2719 
2720 // k_mirror - may be primitive, this must be checked
2721 // is_interface_ptr - pre-checked for NULL
2722 jvmtiError
2723 JvmtiEnv::IsInterface(oop k_mirror, jboolean* is_interface_ptr) {
2724   {
2725     bool result = false;
2726     if (!java_lang_Class::is_primitive(k_mirror)) {
2727       Klass* k = java_lang_Class::as_Klass(k_mirror);
2728       if (k != NULL && k->is_interface()) {
2729         result = true;
2730       }
2731     }
2732     *is_interface_ptr = result;
2733   }
2734 
2735   return JVMTI_ERROR_NONE;
2736 } /* end IsInterface */
2737 
2738 
2739 // k_mirror - may be primitive, this must be checked
2740 // is_array_class_ptr - pre-checked for NULL
2741 jvmtiError
2742 JvmtiEnv::IsArrayClass(oop k_mirror, jboolean* is_array_class_ptr) {
2743   {
2744     bool result = false;
2745     if (!java_lang_Class::is_primitive(k_mirror)) {
2746       Klass* k = java_lang_Class::as_Klass(k_mirror);
2747       if (k != NULL && k->is_array_klass()) {
2748         result = true;
2749       }
2750     }
2751     *is_array_class_ptr = result;
2752   }
2753 
2754   return JVMTI_ERROR_NONE;
2755 } /* end IsArrayClass */
2756 
2757 
2758 // k_mirror - may be primitive, this must be checked
2759 // classloader_ptr - pre-checked for NULL
2760 jvmtiError
2761 JvmtiEnv::GetClassLoader(oop k_mirror, jobject* classloader_ptr) {
2762   {
2763     if (java_lang_Class::is_primitive(k_mirror)) {
2764       *classloader_ptr = (jclass) jni_reference(Handle());
2765       return JVMTI_ERROR_NONE;
2766     }
2767     JavaThread* current_thread = JavaThread::current();
2768     HandleMark hm(current_thread);
2769     Klass* k = java_lang_Class::as_Klass(k_mirror);
2770     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2771 
2772     oop result_oop = k->class_loader();
2773     if (result_oop == NULL) {
2774       *classloader_ptr = (jclass) jni_reference(Handle());
2775       return JVMTI_ERROR_NONE;
2776     }
2777     Handle result_handle = Handle(current_thread, result_oop);
2778     jclass result_jnihandle = (jclass) jni_reference(result_handle);
2779     *classloader_ptr = result_jnihandle;
2780   }
2781   return JVMTI_ERROR_NONE;
2782 } /* end GetClassLoader */
2783 
2784 
2785 // k_mirror - may be primitive, this must be checked
2786 // source_debug_extension_ptr - pre-checked for NULL
2787 jvmtiError
2788 JvmtiEnv::GetSourceDebugExtension(oop k_mirror, char** source_debug_extension_ptr) {
2789   {
2790     if (java_lang_Class::is_primitive(k_mirror)) {
2791       return JVMTI_ERROR_ABSENT_INFORMATION;
2792     }
2793     Klass* k = java_lang_Class::as_Klass(k_mirror);
2794     NULL_CHECK(k, JVMTI_ERROR_INVALID_CLASS);
2795     if (!k->is_instance_klass()) {
2796       return JVMTI_ERROR_ABSENT_INFORMATION;
2797     }
2798     const char* sde = InstanceKlass::cast(k)->source_debug_extension();
2799     NULL_CHECK(sde, JVMTI_ERROR_ABSENT_INFORMATION);
2800 
2801     {
2802       *source_debug_extension_ptr = (char *) jvmtiMalloc(strlen(sde)+1);
2803       strcpy(*source_debug_extension_ptr, sde);
2804     }
2805   }
2806 
2807   return JVMTI_ERROR_NONE;
2808 } /* end GetSourceDebugExtension */
2809 
2810   //
2811   // Object functions
2812   //
2813 
2814 // hash_code_ptr - pre-checked for NULL
2815 jvmtiError
2816 JvmtiEnv::GetObjectHashCode(jobject object, jint* hash_code_ptr) {
2817   oop mirror = JNIHandles::resolve_external_guard(object);
2818   NULL_CHECK(mirror, JVMTI_ERROR_INVALID_OBJECT);
2819   NULL_CHECK(hash_code_ptr, JVMTI_ERROR_NULL_POINTER);
2820 
2821   {
2822     jint result = (jint) mirror->identity_hash();
2823     *hash_code_ptr = result;
2824   }
2825   return JVMTI_ERROR_NONE;
2826 } /* end GetObjectHashCode */
2827 
2828 
2829 // info_ptr - pre-checked for NULL
2830 jvmtiError
2831 JvmtiEnv::GetObjectMonitorUsage(jobject object, jvmtiMonitorUsage* info_ptr) {
2832   JavaThread* calling_thread = JavaThread::current();
2833   jvmtiError err = get_object_monitor_usage(calling_thread, object, info_ptr);
2834   if (err == JVMTI_ERROR_THREAD_NOT_SUSPENDED) {
2835     // Some of the critical threads were not suspended. go to a safepoint and try again
2836     VM_GetObjectMonitorUsage op(this, calling_thread, object, info_ptr);
2837     VMThread::execute(&op);
2838     err = op.result();
2839   }
2840   return err;
2841 } /* end GetObjectMonitorUsage */
2842 
2843 
2844   //
2845   // Field functions
2846   //
2847 
2848 // name_ptr - NULL is a valid value, must be checked
2849 // signature_ptr - NULL is a valid value, must be checked
2850 // generic_ptr - NULL is a valid value, must be checked
2851 jvmtiError
2852 JvmtiEnv::GetFieldName(fieldDescriptor* fdesc_ptr, char** name_ptr, char** signature_ptr, char** generic_ptr) {
2853   JavaThread* current_thread  = JavaThread::current();
2854   ResourceMark rm(current_thread);
2855   if (name_ptr == NULL) {
2856     // just don't return the name
2857   } else {
2858     const char* fieldName = fdesc_ptr->name()->as_C_string();
2859     *name_ptr =  (char*) jvmtiMalloc(strlen(fieldName) + 1);
2860     if (*name_ptr == NULL)
2861       return JVMTI_ERROR_OUT_OF_MEMORY;
2862     strcpy(*name_ptr, fieldName);
2863   }
2864   if (signature_ptr== NULL) {
2865     // just don't return the signature
2866   } else {
2867     const char* fieldSignature = fdesc_ptr->signature()->as_C_string();
2868     *signature_ptr = (char*) jvmtiMalloc(strlen(fieldSignature) + 1);
2869     if (*signature_ptr == NULL)
2870       return JVMTI_ERROR_OUT_OF_MEMORY;
2871     strcpy(*signature_ptr, fieldSignature);
2872   }
2873   if (generic_ptr != NULL) {
2874     *generic_ptr = NULL;
2875     Symbol* soop = fdesc_ptr->generic_signature();
2876     if (soop != NULL) {
2877       const char* gen_sig = soop->as_C_string();
2878       if (gen_sig != NULL) {
2879         jvmtiError err = allocate(strlen(gen_sig) + 1, (unsigned char **)generic_ptr);
2880         if (err != JVMTI_ERROR_NONE) {
2881           return err;
2882         }
2883         strcpy(*generic_ptr, gen_sig);
2884       }
2885     }
2886   }
2887   return JVMTI_ERROR_NONE;
2888 } /* end GetFieldName */
2889 
2890 
2891 // declaring_class_ptr - pre-checked for NULL
2892 jvmtiError
2893 JvmtiEnv::GetFieldDeclaringClass(fieldDescriptor* fdesc_ptr, jclass* declaring_class_ptr) {
2894 
2895   *declaring_class_ptr = get_jni_class_non_null(fdesc_ptr->field_holder());
2896   return JVMTI_ERROR_NONE;
2897 } /* end GetFieldDeclaringClass */
2898 
2899 
2900 // modifiers_ptr - pre-checked for NULL
2901 jvmtiError
2902 JvmtiEnv::GetFieldModifiers(fieldDescriptor* fdesc_ptr, jint* modifiers_ptr) {
2903 
2904   AccessFlags resultFlags = fdesc_ptr->access_flags();
2905   jint result = resultFlags.as_int();
2906   *modifiers_ptr = result;
2907 
2908   return JVMTI_ERROR_NONE;
2909 } /* end GetFieldModifiers */
2910 
2911 
2912 // is_synthetic_ptr - pre-checked for NULL
2913 jvmtiError
2914 JvmtiEnv::IsFieldSynthetic(fieldDescriptor* fdesc_ptr, jboolean* is_synthetic_ptr) {
2915   *is_synthetic_ptr = fdesc_ptr->is_synthetic();
2916   return JVMTI_ERROR_NONE;
2917 } /* end IsFieldSynthetic */
2918 
2919 
2920   //
2921   // Method functions
2922   //
2923 
2924 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2925 // name_ptr - NULL is a valid value, must be checked
2926 // signature_ptr - NULL is a valid value, must be checked
2927 // generic_ptr - NULL is a valid value, must be checked
2928 jvmtiError
2929 JvmtiEnv::GetMethodName(Method* method_oop, char** name_ptr, char** signature_ptr, char** generic_ptr) {
2930   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2931   JavaThread* current_thread  = JavaThread::current();
2932 
2933   ResourceMark rm(current_thread); // get the utf8 name and signature
2934   if (name_ptr == NULL) {
2935     // just don't return the name
2936   } else {
2937     const char* utf8_name = (const char *) method_oop->name()->as_utf8();
2938     *name_ptr = (char *) jvmtiMalloc(strlen(utf8_name)+1);
2939     strcpy(*name_ptr, utf8_name);
2940   }
2941   if (signature_ptr == NULL) {
2942     // just don't return the signature
2943   } else {
2944     const char* utf8_signature = (const char *) method_oop->signature()->as_utf8();
2945     *signature_ptr = (char *) jvmtiMalloc(strlen(utf8_signature) + 1);
2946     strcpy(*signature_ptr, utf8_signature);
2947   }
2948 
2949   if (generic_ptr != NULL) {
2950     *generic_ptr = NULL;
2951     Symbol* soop = method_oop->generic_signature();
2952     if (soop != NULL) {
2953       const char* gen_sig = soop->as_C_string();
2954       if (gen_sig != NULL) {
2955         jvmtiError err = allocate(strlen(gen_sig) + 1, (unsigned char **)generic_ptr);
2956         if (err != JVMTI_ERROR_NONE) {
2957           return err;
2958         }
2959         strcpy(*generic_ptr, gen_sig);
2960       }
2961     }
2962   }
2963   return JVMTI_ERROR_NONE;
2964 } /* end GetMethodName */
2965 
2966 
2967 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2968 // declaring_class_ptr - pre-checked for NULL
2969 jvmtiError
2970 JvmtiEnv::GetMethodDeclaringClass(Method* method_oop, jclass* declaring_class_ptr) {
2971   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2972   (*declaring_class_ptr) = get_jni_class_non_null(method_oop->method_holder());
2973   return JVMTI_ERROR_NONE;
2974 } /* end GetMethodDeclaringClass */
2975 
2976 
2977 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2978 // modifiers_ptr - pre-checked for NULL
2979 jvmtiError
2980 JvmtiEnv::GetMethodModifiers(Method* method_oop, jint* modifiers_ptr) {
2981   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2982   (*modifiers_ptr) = method_oop->access_flags().as_int() & JVM_RECOGNIZED_METHOD_MODIFIERS;
2983   return JVMTI_ERROR_NONE;
2984 } /* end GetMethodModifiers */
2985 
2986 
2987 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2988 // max_ptr - pre-checked for NULL
2989 jvmtiError
2990 JvmtiEnv::GetMaxLocals(Method* method_oop, jint* max_ptr) {
2991   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
2992   // get max stack
2993   (*max_ptr) = method_oop->max_locals();
2994   return JVMTI_ERROR_NONE;
2995 } /* end GetMaxLocals */
2996 
2997 
2998 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
2999 // size_ptr - pre-checked for NULL
3000 jvmtiError
3001 JvmtiEnv::GetArgumentsSize(Method* method_oop, jint* size_ptr) {
3002   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3003   // get size of arguments
3004 
3005   (*size_ptr) = method_oop->size_of_parameters();
3006   return JVMTI_ERROR_NONE;
3007 } /* end GetArgumentsSize */
3008 
3009 
3010 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3011 // entry_count_ptr - pre-checked for NULL
3012 // table_ptr - pre-checked for NULL
3013 jvmtiError
3014 JvmtiEnv::GetLineNumberTable(Method* method_oop, jint* entry_count_ptr, jvmtiLineNumberEntry** table_ptr) {
3015   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3016   if (!method_oop->has_linenumber_table()) {
3017     return (JVMTI_ERROR_ABSENT_INFORMATION);
3018   }
3019 
3020   // The line number table is compressed so we don't know how big it is until decompressed.
3021   // Decompression is really fast so we just do it twice.
3022 
3023   // Compute size of table
3024   jint num_entries = 0;
3025   CompressedLineNumberReadStream stream(method_oop->compressed_linenumber_table());
3026   while (stream.read_pair()) {
3027     num_entries++;
3028   }
3029   jvmtiLineNumberEntry *jvmti_table =
3030             (jvmtiLineNumberEntry *)jvmtiMalloc(num_entries * (sizeof(jvmtiLineNumberEntry)));
3031 
3032   // Fill jvmti table
3033   if (num_entries > 0) {
3034     int index = 0;
3035     CompressedLineNumberReadStream stream(method_oop->compressed_linenumber_table());
3036     while (stream.read_pair()) {
3037       jvmti_table[index].start_location = (jlocation) stream.bci();
3038       jvmti_table[index].line_number = (jint) stream.line();
3039       index++;
3040     }
3041     assert(index == num_entries, "sanity check");
3042   }
3043 
3044   // Set up results
3045   (*entry_count_ptr) = num_entries;
3046   (*table_ptr) = jvmti_table;
3047 
3048   return JVMTI_ERROR_NONE;
3049 } /* end GetLineNumberTable */
3050 
3051 
3052 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3053 // start_location_ptr - pre-checked for NULL
3054 // end_location_ptr - pre-checked for NULL
3055 jvmtiError
3056 JvmtiEnv::GetMethodLocation(Method* method_oop, jlocation* start_location_ptr, jlocation* end_location_ptr) {
3057 
3058   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3059   // get start and end location
3060   (*end_location_ptr) = (jlocation) (method_oop->code_size() - 1);
3061   if (method_oop->code_size() == 0) {
3062     // there is no code so there is no start location
3063     (*start_location_ptr) = (jlocation)(-1);
3064   } else {
3065     (*start_location_ptr) = (jlocation)(0);
3066   }
3067 
3068   return JVMTI_ERROR_NONE;
3069 } /* end GetMethodLocation */
3070 
3071 
3072 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3073 // entry_count_ptr - pre-checked for NULL
3074 // table_ptr - pre-checked for NULL
3075 jvmtiError
3076 JvmtiEnv::GetLocalVariableTable(Method* method_oop, jint* entry_count_ptr, jvmtiLocalVariableEntry** table_ptr) {
3077 
3078   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3079   JavaThread* current_thread  = JavaThread::current();
3080 
3081   // does the klass have any local variable information?
3082   InstanceKlass* ik = method_oop->method_holder();
3083   if (!ik->access_flags().has_localvariable_table()) {
3084     return (JVMTI_ERROR_ABSENT_INFORMATION);
3085   }
3086 
3087   ConstantPool* constants = method_oop->constants();
3088   NULL_CHECK(constants, JVMTI_ERROR_ABSENT_INFORMATION);
3089 
3090   // in the vm localvariable table representation, 6 consecutive elements in the table
3091   // represent a 6-tuple of shorts
3092   // [start_pc, length, name_index, descriptor_index, signature_index, index]
3093   jint num_entries = method_oop->localvariable_table_length();
3094   jvmtiLocalVariableEntry *jvmti_table = (jvmtiLocalVariableEntry *)
3095                 jvmtiMalloc(num_entries * (sizeof(jvmtiLocalVariableEntry)));
3096 
3097   if (num_entries > 0) {
3098     LocalVariableTableElement* table = method_oop->localvariable_table_start();
3099     for (int i = 0; i < num_entries; i++) {
3100       // get the 5 tuple information from the vm table
3101       jlocation start_location = (jlocation) table[i].start_bci;
3102       jint length = (jint) table[i].length;
3103       int name_index = (int) table[i].name_cp_index;
3104       int signature_index = (int) table[i].descriptor_cp_index;
3105       int generic_signature_index = (int) table[i].signature_cp_index;
3106       jint slot = (jint) table[i].slot;
3107 
3108       // get utf8 name and signature
3109       char *name_buf = NULL;
3110       char *sig_buf = NULL;
3111       char *gen_sig_buf = NULL;
3112       {
3113         ResourceMark rm(current_thread);
3114 
3115         const char *utf8_name = (const char *) constants->symbol_at(name_index)->as_utf8();
3116         name_buf = (char *) jvmtiMalloc(strlen(utf8_name)+1);
3117         strcpy(name_buf, utf8_name);
3118 
3119         const char *utf8_signature = (const char *) constants->symbol_at(signature_index)->as_utf8();
3120         sig_buf = (char *) jvmtiMalloc(strlen(utf8_signature)+1);
3121         strcpy(sig_buf, utf8_signature);
3122 
3123         if (generic_signature_index > 0) {
3124           const char *utf8_gen_sign = (const char *)
3125                                        constants->symbol_at(generic_signature_index)->as_utf8();
3126           gen_sig_buf = (char *) jvmtiMalloc(strlen(utf8_gen_sign)+1);
3127           strcpy(gen_sig_buf, utf8_gen_sign);
3128         }
3129       }
3130 
3131       // fill in the jvmti local variable table
3132       jvmti_table[i].start_location = start_location;
3133       jvmti_table[i].length = length;
3134       jvmti_table[i].name = name_buf;
3135       jvmti_table[i].signature = sig_buf;
3136       jvmti_table[i].generic_signature = gen_sig_buf;
3137       jvmti_table[i].slot = slot;
3138     }
3139   }
3140 
3141   // set results
3142   (*entry_count_ptr) = num_entries;
3143   (*table_ptr) = jvmti_table;
3144 
3145   return JVMTI_ERROR_NONE;
3146 } /* end GetLocalVariableTable */
3147 
3148 
3149 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3150 // bytecode_count_ptr - pre-checked for NULL
3151 // bytecodes_ptr - pre-checked for NULL
3152 jvmtiError
3153 JvmtiEnv::GetBytecodes(Method* method_oop, jint* bytecode_count_ptr, unsigned char** bytecodes_ptr) {
3154   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3155 
3156   HandleMark hm;
3157   methodHandle method(method_oop);
3158   jint size = (jint)method->code_size();
3159   jvmtiError err = allocate(size, bytecodes_ptr);
3160   if (err != JVMTI_ERROR_NONE) {
3161     return err;
3162   }
3163 
3164   (*bytecode_count_ptr) = size;
3165   // get byte codes
3166   JvmtiClassFileReconstituter::copy_bytecodes(method, *bytecodes_ptr);
3167 
3168   return JVMTI_ERROR_NONE;
3169 } /* end GetBytecodes */
3170 
3171 
3172 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3173 // is_native_ptr - pre-checked for NULL
3174 jvmtiError
3175 JvmtiEnv::IsMethodNative(Method* method_oop, jboolean* is_native_ptr) {
3176   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3177   (*is_native_ptr) = method_oop->is_native();
3178   return JVMTI_ERROR_NONE;
3179 } /* end IsMethodNative */
3180 
3181 
3182 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3183 // is_synthetic_ptr - pre-checked for NULL
3184 jvmtiError
3185 JvmtiEnv::IsMethodSynthetic(Method* method_oop, jboolean* is_synthetic_ptr) {
3186   NULL_CHECK(method_oop, JVMTI_ERROR_INVALID_METHODID);
3187   (*is_synthetic_ptr) = method_oop->is_synthetic();
3188   return JVMTI_ERROR_NONE;
3189 } /* end IsMethodSynthetic */
3190 
3191 
3192 // method_oop - pre-checked for validity, but may be NULL meaning obsolete method
3193 // is_obsolete_ptr - pre-checked for NULL
3194 jvmtiError
3195 JvmtiEnv::IsMethodObsolete(Method* method_oop, jboolean* is_obsolete_ptr) {
3196   if (use_version_1_0_semantics() &&
3197       get_capabilities()->can_redefine_classes == 0) {
3198     // This JvmtiEnv requested version 1.0 semantics and this function
3199     // requires the can_redefine_classes capability in version 1.0 so
3200     // we need to return an error here.
3201     return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
3202   }
3203 
3204   if (method_oop == NULL || method_oop->is_obsolete()) {
3205     *is_obsolete_ptr = true;
3206   } else {
3207     *is_obsolete_ptr = false;
3208   }
3209   return JVMTI_ERROR_NONE;
3210 } /* end IsMethodObsolete */
3211 
3212   //
3213   // Raw Monitor functions
3214   //
3215 
3216 // name - pre-checked for NULL
3217 // monitor_ptr - pre-checked for NULL
3218 jvmtiError
3219 JvmtiEnv::CreateRawMonitor(const char* name, jrawMonitorID* monitor_ptr) {
3220   JvmtiRawMonitor* rmonitor = new JvmtiRawMonitor(name);
3221   NULL_CHECK(rmonitor, JVMTI_ERROR_OUT_OF_MEMORY);
3222 
3223   *monitor_ptr = (jrawMonitorID)rmonitor;
3224 
3225   return JVMTI_ERROR_NONE;
3226 } /* end CreateRawMonitor */
3227 
3228 
3229 // rmonitor - pre-checked for validity
3230 jvmtiError
3231 JvmtiEnv::DestroyRawMonitor(JvmtiRawMonitor * rmonitor) {
3232   if (Threads::number_of_threads() == 0) {
3233     // Remove this  monitor from pending raw monitors list
3234     // if it has entered in onload or start phase.
3235     JvmtiPendingMonitors::destroy(rmonitor);
3236   } else {
3237     Thread* thread  = Thread::current();
3238     if (rmonitor->is_entered(thread)) {
3239       // The caller owns this monitor which we are about to destroy.
3240       // We exit the underlying synchronization object so that the
3241       // "delete monitor" call below can work without an assertion
3242       // failure on systems that don't like destroying synchronization
3243       // objects that are locked.
3244       int r;
3245       intptr_t recursion = rmonitor->recursions();
3246       for (intptr_t i = 0; i <= recursion; i++) {
3247         r = rmonitor->raw_exit(thread);
3248         assert(r == ObjectMonitor::OM_OK, "raw_exit should have worked");
3249         if (r != ObjectMonitor::OM_OK) {  // robustness
3250           return JVMTI_ERROR_INTERNAL;
3251         }
3252       }
3253     }
3254     if (rmonitor->owner() != NULL) {
3255       // The caller is trying to destroy a monitor that is locked by
3256       // someone else. While this is not forbidden by the JVMTI
3257       // spec, it will cause an assertion failure on systems that don't
3258       // like destroying synchronization objects that are locked.
3259       // We indicate a problem with the error return (and leak the
3260       // monitor's memory).
3261       return JVMTI_ERROR_NOT_MONITOR_OWNER;
3262     }
3263   }
3264 
3265   delete rmonitor;
3266 
3267   return JVMTI_ERROR_NONE;
3268 } /* end DestroyRawMonitor */
3269 
3270 
3271 // rmonitor - pre-checked for validity
3272 jvmtiError
3273 JvmtiEnv::RawMonitorEnter(JvmtiRawMonitor * rmonitor) {
3274   if (Threads::number_of_threads() == 0) {
3275     // No JavaThreads exist so ObjectMonitor enter cannot be
3276     // used, add this raw monitor to the pending list.
3277     // The pending monitors will be actually entered when
3278     // the VM is setup.
3279     // See transition_pending_raw_monitors in create_vm()
3280     // in thread.cpp.
3281     JvmtiPendingMonitors::enter(rmonitor);
3282   } else {
3283     int r = 0;
3284     Thread* thread = Thread::current();
3285 
3286     if (thread->is_Java_thread()) {
3287       JavaThread* current_thread = (JavaThread*)thread;
3288 
3289 #ifdef PROPER_TRANSITIONS
3290       // Not really unknown but ThreadInVMfromNative does more than we want
3291       ThreadInVMfromUnknown __tiv;
3292       {
3293         ThreadBlockInVM __tbivm(current_thread);
3294         r = rmonitor->raw_enter(current_thread);
3295       }
3296 #else
3297       /* Transition to thread_blocked without entering vm state          */
3298       /* This is really evil. Normally you can't undo _thread_blocked    */
3299       /* transitions like this because it would cause us to miss a       */
3300       /* safepoint but since the thread was already in _thread_in_native */
3301       /* the thread is not leaving a safepoint safe state and it will    */
3302       /* block when it tries to return from native. We can't safepoint   */
3303       /* block in here because we could deadlock the vmthread. Blech.    */
3304 
3305       JavaThreadState state = current_thread->thread_state();
3306       assert(state == _thread_in_native, "Must be _thread_in_native");
3307       // frame should already be walkable since we are in native
3308       assert(!current_thread->has_last_Java_frame() ||
3309              current_thread->frame_anchor()->walkable(), "Must be walkable");
3310       current_thread->set_thread_state(_thread_blocked);
3311 
3312       r = rmonitor->raw_enter(current_thread);
3313       // restore state, still at a safepoint safe state
3314       current_thread->set_thread_state(state);
3315 
3316 #endif /* PROPER_TRANSITIONS */
3317       assert(r == ObjectMonitor::OM_OK, "raw_enter should have worked");
3318     } else {
3319       if (thread->is_Named_thread()) {
3320         r = rmonitor->raw_enter(thread);
3321       } else {
3322         ShouldNotReachHere();
3323       }
3324     }
3325 
3326     if (r != ObjectMonitor::OM_OK) {  // robustness
3327       return JVMTI_ERROR_INTERNAL;
3328     }
3329   }
3330   return JVMTI_ERROR_NONE;
3331 } /* end RawMonitorEnter */
3332 
3333 
3334 // rmonitor - pre-checked for validity
3335 jvmtiError
3336 JvmtiEnv::RawMonitorExit(JvmtiRawMonitor * rmonitor) {
3337   jvmtiError err = JVMTI_ERROR_NONE;
3338 
3339   if (Threads::number_of_threads() == 0) {
3340     // No JavaThreads exist so just remove this monitor from the pending list.
3341     // Bool value from exit is false if rmonitor is not in the list.
3342     if (!JvmtiPendingMonitors::exit(rmonitor)) {
3343       err = JVMTI_ERROR_NOT_MONITOR_OWNER;
3344     }
3345   } else {
3346     int r = 0;
3347     Thread* thread = Thread::current();
3348 
3349     if (thread->is_Java_thread()) {
3350       JavaThread* current_thread = (JavaThread*)thread;
3351 #ifdef PROPER_TRANSITIONS
3352       // Not really unknown but ThreadInVMfromNative does more than we want
3353       ThreadInVMfromUnknown __tiv;
3354 #endif /* PROPER_TRANSITIONS */
3355       r = rmonitor->raw_exit(current_thread);
3356     } else {
3357       if (thread->is_Named_thread()) {
3358         r = rmonitor->raw_exit(thread);
3359       } else {
3360         ShouldNotReachHere();
3361       }
3362     }
3363 
3364     if (r == ObjectMonitor::OM_ILLEGAL_MONITOR_STATE) {
3365       err = JVMTI_ERROR_NOT_MONITOR_OWNER;
3366     } else {
3367       assert(r == ObjectMonitor::OM_OK, "raw_exit should have worked");
3368       if (r != ObjectMonitor::OM_OK) {  // robustness
3369         err = JVMTI_ERROR_INTERNAL;
3370       }
3371     }
3372   }
3373   return err;
3374 } /* end RawMonitorExit */
3375 
3376 
3377 // rmonitor - pre-checked for validity
3378 jvmtiError
3379 JvmtiEnv::RawMonitorWait(JvmtiRawMonitor * rmonitor, jlong millis) {
3380   int r = 0;
3381   Thread* thread = Thread::current();
3382 
3383   if (thread->is_Java_thread()) {
3384     JavaThread* current_thread = (JavaThread*)thread;
3385 #ifdef PROPER_TRANSITIONS
3386     // Not really unknown but ThreadInVMfromNative does more than we want
3387     ThreadInVMfromUnknown __tiv;
3388     {
3389       ThreadBlockInVM __tbivm(current_thread);
3390       r = rmonitor->raw_wait(millis, true, current_thread);
3391     }
3392 #else
3393     /* Transition to thread_blocked without entering vm state          */
3394     /* This is really evil. Normally you can't undo _thread_blocked    */
3395     /* transitions like this because it would cause us to miss a       */
3396     /* safepoint but since the thread was already in _thread_in_native */
3397     /* the thread is not leaving a safepoint safe state and it will    */
3398     /* block when it tries to return from native. We can't safepoint   */
3399     /* block in here because we could deadlock the vmthread. Blech.    */
3400 
3401     JavaThreadState state = current_thread->thread_state();
3402     assert(state == _thread_in_native, "Must be _thread_in_native");
3403     // frame should already be walkable since we are in native
3404     assert(!current_thread->has_last_Java_frame() ||
3405            current_thread->frame_anchor()->walkable(), "Must be walkable");
3406     current_thread->set_thread_state(_thread_blocked);
3407 
3408     r = rmonitor->raw_wait(millis, true, current_thread);
3409     // restore state, still at a safepoint safe state
3410     current_thread->set_thread_state(state);
3411 
3412 #endif /* PROPER_TRANSITIONS */
3413   } else {
3414     if (thread->is_Named_thread()) {
3415       r = rmonitor->raw_wait(millis, false, thread);
3416     } else {
3417       ShouldNotReachHere();
3418     }
3419   }
3420 
3421   switch (r) {
3422   case ObjectMonitor::OM_INTERRUPTED:
3423     return JVMTI_ERROR_INTERRUPT;
3424   case ObjectMonitor::OM_ILLEGAL_MONITOR_STATE:
3425     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3426   }
3427   assert(r == ObjectMonitor::OM_OK, "raw_wait should have worked");
3428   if (r != ObjectMonitor::OM_OK) {  // robustness
3429     return JVMTI_ERROR_INTERNAL;
3430   }
3431 
3432   return JVMTI_ERROR_NONE;
3433 } /* end RawMonitorWait */
3434 
3435 
3436 // rmonitor - pre-checked for validity
3437 jvmtiError
3438 JvmtiEnv::RawMonitorNotify(JvmtiRawMonitor * rmonitor) {
3439   int r = 0;
3440   Thread* thread = Thread::current();
3441 
3442   if (thread->is_Java_thread()) {
3443     JavaThread* current_thread = (JavaThread*)thread;
3444     // Not really unknown but ThreadInVMfromNative does more than we want
3445     ThreadInVMfromUnknown __tiv;
3446     r = rmonitor->raw_notify(current_thread);
3447   } else {
3448     if (thread->is_Named_thread()) {
3449       r = rmonitor->raw_notify(thread);
3450     } else {
3451       ShouldNotReachHere();
3452     }
3453   }
3454 
3455   if (r == ObjectMonitor::OM_ILLEGAL_MONITOR_STATE) {
3456     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3457   }
3458   assert(r == ObjectMonitor::OM_OK, "raw_notify should have worked");
3459   if (r != ObjectMonitor::OM_OK) {  // robustness
3460     return JVMTI_ERROR_INTERNAL;
3461   }
3462 
3463   return JVMTI_ERROR_NONE;
3464 } /* end RawMonitorNotify */
3465 
3466 
3467 // rmonitor - pre-checked for validity
3468 jvmtiError
3469 JvmtiEnv::RawMonitorNotifyAll(JvmtiRawMonitor * rmonitor) {
3470   int r = 0;
3471   Thread* thread = Thread::current();
3472 
3473   if (thread->is_Java_thread()) {
3474     JavaThread* current_thread = (JavaThread*)thread;
3475     ThreadInVMfromUnknown __tiv;
3476     r = rmonitor->raw_notifyAll(current_thread);
3477   } else {
3478     if (thread->is_Named_thread()) {
3479       r = rmonitor->raw_notifyAll(thread);
3480     } else {
3481       ShouldNotReachHere();
3482     }
3483   }
3484 
3485   if (r == ObjectMonitor::OM_ILLEGAL_MONITOR_STATE) {
3486     return JVMTI_ERROR_NOT_MONITOR_OWNER;
3487   }
3488   assert(r == ObjectMonitor::OM_OK, "raw_notifyAll should have worked");
3489   if (r != ObjectMonitor::OM_OK) {  // robustness
3490     return JVMTI_ERROR_INTERNAL;
3491   }
3492 
3493   return JVMTI_ERROR_NONE;
3494 } /* end RawMonitorNotifyAll */
3495 
3496 
3497   //
3498   // JNI Function Interception functions
3499   //
3500 
3501 
3502 // function_table - pre-checked for NULL
3503 jvmtiError
3504 JvmtiEnv::SetJNIFunctionTable(const jniNativeInterface* function_table) {
3505   // Copy jni function table at safepoint.
3506   VM_JNIFunctionTableCopier copier(function_table);
3507   VMThread::execute(&copier);
3508 
3509   return JVMTI_ERROR_NONE;
3510 } /* end SetJNIFunctionTable */
3511 
3512 
3513 // function_table - pre-checked for NULL
3514 jvmtiError
3515 JvmtiEnv::GetJNIFunctionTable(jniNativeInterface** function_table) {
3516   *function_table=(jniNativeInterface*)jvmtiMalloc(sizeof(jniNativeInterface));
3517   if (*function_table == NULL)
3518     return JVMTI_ERROR_OUT_OF_MEMORY;
3519   memcpy(*function_table,(JavaThread::current())->get_jni_functions(),sizeof(jniNativeInterface));
3520   return JVMTI_ERROR_NONE;
3521 } /* end GetJNIFunctionTable */
3522 
3523 
3524   //
3525   // Event Management functions
3526   //
3527 
3528 jvmtiError
3529 JvmtiEnv::GenerateEvents(jvmtiEvent event_type) {
3530   // can only generate two event types
3531   if (event_type != JVMTI_EVENT_COMPILED_METHOD_LOAD &&
3532       event_type != JVMTI_EVENT_DYNAMIC_CODE_GENERATED) {
3533     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
3534   }
3535 
3536   // for compiled_method_load events we must check that the environment
3537   // has the can_generate_compiled_method_load_events capability.
3538   if (event_type == JVMTI_EVENT_COMPILED_METHOD_LOAD) {
3539     if (get_capabilities()->can_generate_compiled_method_load_events == 0) {
3540       return JVMTI_ERROR_MUST_POSSESS_CAPABILITY;
3541     }
3542     return JvmtiCodeBlobEvents::generate_compiled_method_load_events(this);
3543   } else {
3544     return JvmtiCodeBlobEvents::generate_dynamic_code_events(this);
3545   }
3546 
3547 } /* end GenerateEvents */
3548 
3549 
3550   //
3551   // Extension Mechanism functions
3552   //
3553 
3554 // extension_count_ptr - pre-checked for NULL
3555 // extensions - pre-checked for NULL
3556 jvmtiError
3557 JvmtiEnv::GetExtensionFunctions(jint* extension_count_ptr, jvmtiExtensionFunctionInfo** extensions) {
3558   return JvmtiExtensions::get_functions(this, extension_count_ptr, extensions);
3559 } /* end GetExtensionFunctions */
3560 
3561 
3562 // extension_count_ptr - pre-checked for NULL
3563 // extensions - pre-checked for NULL
3564 jvmtiError
3565 JvmtiEnv::GetExtensionEvents(jint* extension_count_ptr, jvmtiExtensionEventInfo** extensions) {
3566   return JvmtiExtensions::get_events(this, extension_count_ptr, extensions);
3567 } /* end GetExtensionEvents */
3568 
3569 
3570 // callback - NULL is a valid value, must be checked
3571 jvmtiError
3572 JvmtiEnv::SetExtensionEventCallback(jint extension_event_index, jvmtiExtensionEvent callback) {
3573   return JvmtiExtensions::set_event_callback(this, extension_event_index, callback);
3574 } /* end SetExtensionEventCallback */
3575 
3576   //
3577   // Timers functions
3578   //
3579 
3580 // info_ptr - pre-checked for NULL
3581 jvmtiError
3582 JvmtiEnv::GetCurrentThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {
3583   os::current_thread_cpu_time_info(info_ptr);
3584   return JVMTI_ERROR_NONE;
3585 } /* end GetCurrentThreadCpuTimerInfo */
3586 
3587 
3588 // nanos_ptr - pre-checked for NULL
3589 jvmtiError
3590 JvmtiEnv::GetCurrentThreadCpuTime(jlong* nanos_ptr) {
3591   *nanos_ptr = os::current_thread_cpu_time();
3592   return JVMTI_ERROR_NONE;
3593 } /* end GetCurrentThreadCpuTime */
3594 
3595 
3596 // info_ptr - pre-checked for NULL
3597 jvmtiError
3598 JvmtiEnv::GetThreadCpuTimerInfo(jvmtiTimerInfo* info_ptr) {
3599   os::thread_cpu_time_info(info_ptr);
3600   return JVMTI_ERROR_NONE;
3601 } /* end GetThreadCpuTimerInfo */
3602 
3603 
3604 // Threads_lock NOT held, java_thread not protected by lock
3605 // java_thread - pre-checked
3606 // nanos_ptr - pre-checked for NULL
3607 jvmtiError
3608 JvmtiEnv::GetThreadCpuTime(JavaThread* java_thread, jlong* nanos_ptr) {
3609   *nanos_ptr = os::thread_cpu_time(java_thread);
3610   return JVMTI_ERROR_NONE;
3611 } /* end GetThreadCpuTime */
3612 
3613 
3614 // info_ptr - pre-checked for NULL
3615 jvmtiError
3616 JvmtiEnv::GetTimerInfo(jvmtiTimerInfo* info_ptr) {
3617   os::javaTimeNanos_info(info_ptr);
3618   return JVMTI_ERROR_NONE;
3619 } /* end GetTimerInfo */
3620 
3621 
3622 // nanos_ptr - pre-checked for NULL
3623 jvmtiError
3624 JvmtiEnv::GetTime(jlong* nanos_ptr) {
3625   *nanos_ptr = os::javaTimeNanos();
3626   return JVMTI_ERROR_NONE;
3627 } /* end GetTime */
3628 
3629 
3630 // processor_count_ptr - pre-checked for NULL
3631 jvmtiError
3632 JvmtiEnv::GetAvailableProcessors(jint* processor_count_ptr) {
3633   *processor_count_ptr = os::active_processor_count();
3634   return JVMTI_ERROR_NONE;
3635 } /* end GetAvailableProcessors */
3636 
3637 jvmtiError
3638 JvmtiEnv::SetHeapSamplingInterval(jint sampling_interval) {
3639   if (sampling_interval < 0) {
3640     return JVMTI_ERROR_ILLEGAL_ARGUMENT;
3641   }
3642   ThreadHeapSampler::set_sampling_interval(sampling_interval);
3643   return JVMTI_ERROR_NONE;
3644 } /* end SetHeapSamplingInterval */
3645 
3646   //
3647   // System Properties functions
3648   //
3649 
3650 // count_ptr - pre-checked for NULL
3651 // property_ptr - pre-checked for NULL
3652 jvmtiError
3653 JvmtiEnv::GetSystemProperties(jint* count_ptr, char*** property_ptr) {
3654   jvmtiError err = JVMTI_ERROR_NONE;
3655 
3656   // Get the number of readable properties.
3657   *count_ptr = Arguments::PropertyList_readable_count(Arguments::system_properties());
3658 
3659   // Allocate memory to hold the exact number of readable properties.
3660   err = allocate(*count_ptr * sizeof(char *), (unsigned char **)property_ptr);
3661   if (err != JVMTI_ERROR_NONE) {
3662     return err;
3663   }
3664   int readable_count = 0;
3665   // Loop through the system properties until all the readable properties are found.
3666   for (SystemProperty* p = Arguments::system_properties(); p != NULL && readable_count < *count_ptr; p = p->next()) {
3667     if (p->is_readable()) {
3668       const char *key = p->key();
3669       char **tmp_value = *property_ptr+readable_count;
3670       readable_count++;
3671       err = allocate((strlen(key)+1) * sizeof(char), (unsigned char**)tmp_value);
3672       if (err == JVMTI_ERROR_NONE) {
3673         strcpy(*tmp_value, key);
3674       } else {
3675         // clean up previously allocated memory.
3676         for (int j = 0; j < readable_count; j++) {
3677           Deallocate((unsigned char*)*property_ptr+j);
3678         }
3679         Deallocate((unsigned char*)property_ptr);
3680         break;
3681       }
3682     }
3683   }
3684   assert(err != JVMTI_ERROR_NONE || readable_count == *count_ptr, "Bad readable property count");
3685   return err;
3686 } /* end GetSystemProperties */
3687 
3688 
3689 // property - pre-checked for NULL
3690 // value_ptr - pre-checked for NULL
3691 jvmtiError
3692 JvmtiEnv::GetSystemProperty(const char* property, char** value_ptr) {
3693   jvmtiError err = JVMTI_ERROR_NONE;
3694   const char *value;
3695 
3696   // Return JVMTI_ERROR_NOT_AVAILABLE if property is not readable or doesn't exist.
3697   value = Arguments::PropertyList_get_readable_value(Arguments::system_properties(), property);
3698   if (value == NULL) {
3699     err =  JVMTI_ERROR_NOT_AVAILABLE;
3700   } else {
3701     err = allocate((strlen(value)+1) * sizeof(char), (unsigned char **)value_ptr);
3702     if (err == JVMTI_ERROR_NONE) {
3703       strcpy(*value_ptr, value);
3704     }
3705   }
3706   return err;
3707 } /* end GetSystemProperty */
3708 
3709 
3710 // property - pre-checked for NULL
3711 // value - NULL is a valid value, must be checked
3712 jvmtiError
3713 JvmtiEnv::SetSystemProperty(const char* property, const char* value_ptr) {
3714   jvmtiError err =JVMTI_ERROR_NOT_AVAILABLE;
3715 
3716   for (SystemProperty* p = Arguments::system_properties(); p != NULL; p = p->next()) {
3717     if (strcmp(property, p->key()) == 0) {
3718       if (p->set_writeable_value(value_ptr)) {
3719         err =  JVMTI_ERROR_NONE;
3720       }
3721     }
3722   }
3723   return err;
3724 } /* end SetSystemProperty */