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