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