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