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