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