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