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