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