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