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