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