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