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