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