1 /*
  2  * Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #include "precompiled.hpp"
 26 #include "classfile/javaClasses.inline.hpp"
 27 #include "classfile/modules.hpp"
 28 #include "classfile/symbolTable.hpp"
 29 #include "classfile/vmClasses.hpp"
 30 #include "classfile/vmSymbols.hpp"
 31 #include "jfr/jni/jfrJavaCall.hpp"
 32 #include "jfr/jni/jfrJavaSupport.hpp"
 33 #include "jfr/support/jfrThreadId.hpp"
 34 #include "logging/log.hpp"
 35 #include "memory/resourceArea.hpp"
 36 #include "oops/instanceOop.hpp"
 37 #include "oops/klass.inline.hpp"
 38 #include "oops/oop.inline.hpp"
 39 #include "oops/objArrayKlass.hpp"
 40 #include "oops/objArrayOop.inline.hpp"
 41 #include "runtime/handles.inline.hpp"
 42 #include "runtime/fieldDescriptor.inline.hpp"
 43 #include "runtime/java.hpp"
 44 #include "runtime/jniHandles.inline.hpp"
 45 #include "runtime/semaphore.inline.hpp"
 46 #include "runtime/synchronizer.hpp"
 47 #include "runtime/thread.inline.hpp"
 48 #include "runtime/threadSMR.hpp"
 49 #include "utilities/growableArray.hpp"
 50 #include "classfile/vmSymbols.hpp"
 51 
 52 #ifdef ASSERT
 53 static void check_java_thread_state(JavaThread* t, JavaThreadState state) {
 54   assert(t != NULL, "invariant");
 55   assert(t->is_Java_thread(), "invariant");
 56   assert(t->thread_state() == state, "invariant");
 57 }
 58 
 59 void JfrJavaSupport::check_java_thread_in_vm(JavaThread* t) {
 60   check_java_thread_state(t, _thread_in_vm);
 61 }
 62 
 63 void JfrJavaSupport::check_java_thread_in_native(JavaThread* t) {
 64   check_java_thread_state(t, _thread_in_native);
 65 }
 66 
 67 void JfrJavaSupport::check_java_thread_in_java(JavaThread* t) {
 68   check_java_thread_state(t, _thread_in_Java);
 69 }
 70 
 71 static void check_new_unstarted_java_thread(JavaThread* jt, jobject vthread = NULL) {
 72   if (vthread != NULL) return;
 73   check_java_thread_state(jt, _thread_new);
 74 }
 75 #endif
 76 
 77 /*
 78  *  Handles and references
 79  */
 80 jobject JfrJavaSupport::local_jni_handle(const oop obj, JavaThread* t) {
 81   DEBUG_ONLY(check_java_thread_in_vm(t));
 82   return t->active_handles()->allocate_handle(obj);
 83 }
 84 
 85 jobject JfrJavaSupport::local_jni_handle(const jobject handle, JavaThread* t) {
 86   DEBUG_ONLY(check_java_thread_in_vm(t));
 87   const oop obj = JNIHandles::resolve(handle);
 88   return obj == NULL ? NULL : local_jni_handle(obj, t);
 89 }
 90 
 91 void JfrJavaSupport::destroy_local_jni_handle(jobject handle) {
 92   JNIHandles::destroy_local(handle);
 93 }
 94 
 95 jobject JfrJavaSupport::global_jni_handle(const oop obj, JavaThread* t) {
 96   DEBUG_ONLY(check_java_thread_in_vm(t));
 97   HandleMark hm(t);
 98   return JNIHandles::make_global(Handle(t, obj));
 99 }
100 
101 jobject JfrJavaSupport::global_jni_handle(const jobject handle, JavaThread* t) {
102   const oop obj = JNIHandles::resolve(handle);
103   return obj == NULL ? NULL : global_jni_handle(obj, t);
104 }
105 
106 void JfrJavaSupport::destroy_global_jni_handle(jobject handle) {
107   JNIHandles::destroy_global(handle);
108 }
109 
110 jweak JfrJavaSupport::global_weak_jni_handle(const oop obj, JavaThread* t) {
111   DEBUG_ONLY(check_java_thread_in_vm(t));
112   HandleMark hm(t);
113   return JNIHandles::make_weak_global(Handle(t, obj));
114 }
115 
116 jweak JfrJavaSupport::global_weak_jni_handle(const jobject handle, JavaThread* t) {
117   const oop obj = JNIHandles::resolve(handle);
118   return obj == NULL ? NULL : global_weak_jni_handle(obj, t);
119 }
120 
121 void JfrJavaSupport::destroy_global_weak_jni_handle(jweak handle) {
122   JNIHandles::destroy_weak_global(handle);
123 }
124 
125 oop JfrJavaSupport::resolve_non_null(jobject obj) {
126   return JNIHandles::resolve_non_null(obj);
127 }
128 
129 /*
130  *  Method invocation
131  */
132 void JfrJavaSupport::call_static(JfrJavaArguments* args, TRAPS) {
133   JfrJavaCall::call_static(args, THREAD);
134 }
135 
136 void JfrJavaSupport::call_special(JfrJavaArguments* args, TRAPS) {
137   JfrJavaCall::call_special(args, THREAD);
138 }
139 
140 void JfrJavaSupport::call_virtual(JfrJavaArguments* args, TRAPS) {
141   JfrJavaCall::call_virtual(args, THREAD);
142 }
143 
144 void JfrJavaSupport::notify_all(jobject object, TRAPS) {
145   assert(object != NULL, "invariant");
146   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
147   HandleMark hm(THREAD);
148   Handle h_obj(THREAD, resolve_non_null(object));
149   assert(h_obj.not_null(), "invariant");
150   ObjectSynchronizer::jni_enter(h_obj, THREAD);
151   ObjectSynchronizer::notifyall(h_obj, THREAD);
152   ObjectSynchronizer::jni_exit(h_obj(), THREAD);
153   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
154 }
155 
156 /*
157  *  Object construction
158  */
159 static void object_construction(JfrJavaArguments* args, JavaValue* result, InstanceKlass* klass, TRAPS) {
160   assert(args != NULL, "invariant");
161   assert(result != NULL, "invariant");
162   assert(klass != NULL, "invariant");
163   assert(klass->is_initialized(), "invariant");
164 
165   HandleMark hm(THREAD);
166   instanceOop obj = klass->allocate_instance(CHECK);
167   instanceHandle h_obj(THREAD, obj);
168   assert(h_obj.not_null(), "invariant");
169   args->set_receiver(h_obj);
170   result->set_type(T_VOID); // constructor result type
171   JfrJavaSupport::call_special(args, CHECK);
172   result->set_type(T_OBJECT); // set back to original result type
173   result->set_oop(h_obj());
174 }
175 
176 static void array_construction(JfrJavaArguments* args, JavaValue* result, InstanceKlass* klass, int array_length, TRAPS) {
177   assert(args != NULL, "invariant");
178   assert(result != NULL, "invariant");
179   assert(klass != NULL, "invariant");
180   assert(klass->is_initialized(), "invariant");
181 
182   Klass* const ak = klass->array_klass(THREAD);
183   ObjArrayKlass::cast(ak)->initialize(THREAD);
184   HandleMark hm(THREAD);
185   objArrayOop arr = ObjArrayKlass::cast(ak)->allocate(array_length, CHECK);
186   result->set_oop(arr);
187 }
188 
189 static void create_object(JfrJavaArguments* args, JavaValue* result, TRAPS) {
190   assert(args != NULL, "invariant");
191   assert(result != NULL, "invariant");
192   assert(result->get_type() == T_OBJECT, "invariant");
193   DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(THREAD));
194 
195   InstanceKlass* const klass = static_cast<InstanceKlass*>(args->klass());
196   klass->initialize(CHECK);
197 
198   const int array_length = args->array_length();
199 
200   if (array_length >= 0) {
201     array_construction(args, result, klass, array_length, CHECK);
202   } else {
203     object_construction(args, result, klass, THREAD);
204   }
205 }
206 
207 static void handle_result(JavaValue* result, bool global_ref, JavaThread* t) {
208   assert(result != NULL, "invariant");
209   DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(t));
210   const oop result_oop = result->get_oop();
211   if (result_oop == NULL) {
212     return;
213   }
214   result->set_jobject(global_ref ?
215                       JfrJavaSupport::global_jni_handle(result_oop, t) :
216                       JfrJavaSupport::local_jni_handle(result_oop, t));
217 }
218 
219 void JfrJavaSupport::new_object(JfrJavaArguments* args, TRAPS) {
220   assert(args != NULL, "invariant");
221   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
222   create_object(args, args->result(), THREAD);
223 }
224 
225 void JfrJavaSupport::new_object_local_ref(JfrJavaArguments* args, TRAPS) {
226   assert(args != NULL, "invariant");
227   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
228   JavaValue* const result = args->result();
229   assert(result != NULL, "invariant");
230   create_object(args, result, CHECK);
231   handle_result(result, false, THREAD);
232 }
233 
234 void JfrJavaSupport::new_object_global_ref(JfrJavaArguments* args, TRAPS) {
235   assert(args != NULL, "invariant");
236   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
237   JavaValue* const result = args->result();
238   assert(result != NULL, "invariant");
239   create_object(args, result, CHECK);
240   handle_result(result, true, THREAD);
241 }
242 
243 jstring JfrJavaSupport::new_string(const char* c_str, TRAPS) {
244   assert(c_str != NULL, "invariant");
245   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
246   const oop result = java_lang_String::create_oop_from_str(c_str, THREAD);
247   return (jstring)local_jni_handle(result, THREAD);
248 }
249 
250 jobjectArray JfrJavaSupport::new_string_array(int length, TRAPS) {
251   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
252   JavaValue result(T_OBJECT);
253   JfrJavaArguments args(&result, "java/lang/String", "<init>", "()V", CHECK_NULL);
254   args.set_array_length(length);
255   new_object_local_ref(&args, THREAD);
256   return (jobjectArray)args.result()->get_jobject();
257 }
258 
259 jobject JfrJavaSupport::new_java_lang_Boolean(bool value, TRAPS) {
260   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
261   JavaValue result(T_OBJECT);
262   JfrJavaArguments args(&result, "java/lang/Boolean", "<init>", "(Z)V", CHECK_NULL);
263   args.push_int(value ? (jint)JNI_TRUE : (jint)JNI_FALSE);
264   new_object_local_ref(&args, THREAD);
265   return args.result()->get_jobject();
266 }
267 
268 jobject JfrJavaSupport::new_java_lang_Integer(jint value, TRAPS) {
269   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
270   JavaValue result(T_OBJECT);
271   JfrJavaArguments args(&result, "java/lang/Integer", "<init>", "(I)V", CHECK_NULL);
272   args.push_int(value);
273   new_object_local_ref(&args, THREAD);
274   return args.result()->get_jobject();
275 }
276 
277 jobject JfrJavaSupport::new_java_lang_Long(jlong value, TRAPS) {
278   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
279   JavaValue result(T_OBJECT);
280   JfrJavaArguments args(&result, "java/lang/Long", "<init>", "(J)V", CHECK_NULL);
281   args.push_long(value);
282   new_object_local_ref(&args, THREAD);
283   return args.result()->get_jobject();
284 }
285 
286 void JfrJavaSupport::set_array_element(jobjectArray arr, jobject element, int index, JavaThread* t) {
287   assert(arr != NULL, "invariant");
288   DEBUG_ONLY(check_java_thread_in_vm(t));
289   HandleMark hm(t);
290   objArrayHandle a(t, (objArrayOop)resolve_non_null(arr));
291   a->obj_at_put(index, resolve_non_null(element));
292 }
293 
294 /*
295  *  Field access
296  */
297 static void write_int_field(const Handle& h_oop, fieldDescriptor* fd, jint value) {
298   assert(h_oop.not_null(), "invariant");
299   assert(fd != NULL, "invariant");
300   h_oop->int_field_put(fd->offset(), value);
301 }
302 
303 static void write_float_field(const Handle& h_oop, fieldDescriptor* fd, jfloat value) {
304   assert(h_oop.not_null(), "invariant");
305   assert(fd != NULL, "invariant");
306   h_oop->float_field_put(fd->offset(), value);
307 }
308 
309 static void write_double_field(const Handle& h_oop, fieldDescriptor* fd, jdouble value) {
310   assert(h_oop.not_null(), "invariant");
311   assert(fd != NULL, "invariant");
312   h_oop->double_field_put(fd->offset(), value);
313 }
314 
315 static void write_long_field(const Handle& h_oop, fieldDescriptor* fd, jlong value) {
316   assert(h_oop.not_null(), "invariant");
317   assert(fd != NULL, "invariant");
318   h_oop->long_field_put(fd->offset(), value);
319 }
320 
321 static void write_oop_field(const Handle& h_oop, fieldDescriptor* fd, const oop value) {
322   assert(h_oop.not_null(), "invariant");
323   assert(fd != NULL, "invariant");
324   h_oop->obj_field_put(fd->offset(), value);
325 }
326 
327 static void write_specialized_field(JfrJavaArguments* args, const Handle& h_oop, fieldDescriptor* fd, bool static_field) {
328   assert(args != NULL, "invariant");
329   assert(h_oop.not_null(), "invariant");
330   assert(fd != NULL, "invariant");
331   assert(fd->offset() > 0, "invariant");
332   assert(args->length() >= 1, "invariant");
333 
334   // attempt must set a real value
335   assert(args->param(1).get_type() != T_VOID, "invariant");
336 
337   switch(fd->field_type()) {
338     case T_BOOLEAN:
339     case T_CHAR:
340     case T_SHORT:
341     case T_INT:
342       write_int_field(h_oop, fd, args->param(1).get_jint());
343       break;
344     case T_FLOAT:
345       write_float_field(h_oop, fd, args->param(1).get_jfloat());
346       break;
347     case T_DOUBLE:
348       write_double_field(h_oop, fd, args->param(1).get_jdouble());
349       break;
350     case T_LONG:
351       write_long_field(h_oop, fd, args->param(1).get_jlong());
352       break;
353     case T_OBJECT:
354       write_oop_field(h_oop, fd, args->param(1).get_oop());
355       break;
356     case T_ADDRESS:
357       write_oop_field(h_oop, fd, JfrJavaSupport::resolve_non_null(args->param(1).get_jobject()));
358       break;
359     default:
360       ShouldNotReachHere();
361   }
362 }
363 
364 static void read_specialized_field(JavaValue* result, const Handle& h_oop, fieldDescriptor* fd) {
365   assert(result != NULL, "invariant");
366   assert(h_oop.not_null(), "invariant");
367   assert(fd != NULL, "invariant");
368   assert(fd->offset() > 0, "invariant");
369 
370   switch(fd->field_type()) {
371     case T_BOOLEAN:
372     case T_CHAR:
373     case T_SHORT:
374     case T_INT:
375       result->set_jint(h_oop->int_field(fd->offset()));
376       break;
377     case T_FLOAT:
378       result->set_jfloat(h_oop->float_field(fd->offset()));
379       break;
380     case T_DOUBLE:
381       result->set_jdouble(h_oop->double_field(fd->offset()));
382       break;
383     case T_LONG:
384       result->set_jlong(h_oop->long_field(fd->offset()));
385       break;
386     case T_OBJECT:
387       result->set_oop(h_oop->obj_field(fd->offset()));
388       break;
389     default:
390       ShouldNotReachHere();
391   }
392 }
393 
394 static bool find_field(InstanceKlass* ik,
395                        Symbol* name_symbol,
396                        Symbol* signature_symbol,
397                        fieldDescriptor* fd,
398                        bool is_static = false,
399                        bool allow_super = false) {
400   if (allow_super || is_static) {
401     return ik->find_field(name_symbol, signature_symbol, is_static, fd) != NULL;
402   }
403   return ik->find_local_field(name_symbol, signature_symbol, fd);
404 }
405 
406 static void lookup_field(JfrJavaArguments* args, InstanceKlass* klass, fieldDescriptor* fd, bool static_field) {
407   assert(args != NULL, "invariant");
408   assert(klass != NULL, "invariant");
409   assert(klass->is_initialized(), "invariant");
410   assert(fd != NULL, "invariant");
411   find_field(klass, args->name(), args->signature(), fd, static_field, true);
412 }
413 
414 static void read_field(JfrJavaArguments* args, JavaValue* result, TRAPS) {
415   assert(args != NULL, "invariant");
416   assert(result != NULL, "invariant");
417   DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(THREAD));
418 
419   InstanceKlass* const klass = static_cast<InstanceKlass*>(args->klass());
420   klass->initialize(CHECK);
421   const bool static_field = !args->has_receiver();
422   fieldDescriptor fd;
423   lookup_field(args, klass, &fd, static_field);
424   assert(fd.offset() > 0, "invariant");
425 
426   HandleMark hm(THREAD);
427   Handle h_oop(static_field ? Handle(THREAD, klass->java_mirror()) : Handle(THREAD, args->receiver()));
428   read_specialized_field(result, h_oop, &fd);
429 }
430 
431 static void write_field(JfrJavaArguments* args, JavaValue* result, TRAPS) {
432   assert(args != NULL, "invariant");
433   assert(result != NULL, "invariant");
434   DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(THREAD));
435 
436   InstanceKlass* const klass = static_cast<InstanceKlass*>(args->klass());
437   klass->initialize(CHECK);
438 
439   const bool static_field = !args->has_receiver();
440   fieldDescriptor fd;
441   lookup_field(args, klass, &fd, static_field);
442   assert(fd.offset() > 0, "invariant");
443 
444   HandleMark hm(THREAD);
445   Handle h_oop(static_field ? Handle(THREAD, klass->java_mirror()) : Handle(THREAD, args->receiver()));
446   write_specialized_field(args, h_oop, &fd, static_field);
447 }
448 
449 void JfrJavaSupport::set_field(JfrJavaArguments* args, TRAPS) {
450   assert(args != NULL, "invariant");
451   write_field(args, args->result(), THREAD);
452 }
453 
454 void JfrJavaSupport::get_field(JfrJavaArguments* args, TRAPS) {
455   assert(args != NULL, "invariant");
456   read_field(args, args->result(), THREAD);
457 }
458 
459 void JfrJavaSupport::get_field_local_ref(JfrJavaArguments* args, TRAPS) {
460   assert(args != NULL, "invariant");
461   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
462 
463   JavaValue* const result = args->result();
464   assert(result != NULL, "invariant");
465   assert(result->get_type() == T_OBJECT, "invariant");
466 
467   read_field(args, result, CHECK);
468   const oop obj = result->get_oop();
469 
470   if (obj != NULL) {
471     result->set_jobject(local_jni_handle(obj, THREAD));
472   }
473 }
474 
475 void JfrJavaSupport::get_field_global_ref(JfrJavaArguments* args, TRAPS) {
476   assert(args != NULL, "invariant");
477   DEBUG_ONLY(check_java_thread_in_vm(THREAD));
478 
479   JavaValue* const result = args->result();
480   assert(result != NULL, "invariant");
481   assert(result->get_type() == T_OBJECT, "invariant");
482   read_field(args, result, CHECK);
483   const oop obj = result->get_oop();
484   if (obj != NULL) {
485     result->set_jobject(global_jni_handle(obj, THREAD));
486   }
487 }
488 
489 /*
490  *  Misc
491  */
492 Klass* JfrJavaSupport::klass(const jobject handle) {
493   const oop obj = resolve_non_null(handle);
494   assert(obj != NULL, "invariant");
495   return obj->klass();
496 }
497 
498 static char* allocate_string(bool c_heap, int length, JavaThread* jt) {
499   return c_heap ? NEW_C_HEAP_ARRAY(char, length, mtTracing) :
500                   NEW_RESOURCE_ARRAY_IN_THREAD(jt, char, length);
501 }
502 
503 const char* JfrJavaSupport::c_str(oop string, JavaThread* t, bool c_heap /* false */) {
504   DEBUG_ONLY(check_java_thread_in_vm(t));
505   char* str = NULL;
506   const typeArrayOop value = java_lang_String::value(string);
507   if (value != NULL) {
508     const int length = java_lang_String::utf8_length(string, value);
509     str = allocate_string(c_heap, length + 1, t);
510     if (str == NULL) {
511       JfrJavaSupport::throw_out_of_memory_error("Unable to allocate native memory", t);
512       return NULL;
513     }
514     java_lang_String::as_utf8_string(string, value, str, length + 1);
515   }
516   return str;
517 }
518 
519 const char* JfrJavaSupport::c_str(jstring string, JavaThread* t, bool c_heap /* false */) {
520   DEBUG_ONLY(check_java_thread_in_vm(t));
521   return string != NULL ? c_str(resolve_non_null(string), t, c_heap) : NULL;
522 }
523 
524 /*
525  *  Exceptions and errors
526  */
527 static void create_and_throw(Symbol* name, const char* message, TRAPS) {
528   assert(name != NULL, "invariant");
529   DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(THREAD));
530   assert(!HAS_PENDING_EXCEPTION, "invariant");
531   THROW_MSG(name, message);
532 }
533 
534 void JfrJavaSupport::throw_illegal_state_exception(const char* message, TRAPS) {
535   create_and_throw(vmSymbols::java_lang_IllegalStateException(), message, THREAD);
536 }
537 
538 void JfrJavaSupport::throw_internal_error(const char* message, TRAPS) {
539   create_and_throw(vmSymbols::java_lang_InternalError(), message, THREAD);
540 }
541 
542 void JfrJavaSupport::throw_illegal_argument_exception(const char* message, TRAPS) {
543   create_and_throw(vmSymbols::java_lang_IllegalArgumentException(), message, THREAD);
544 }
545 
546 void JfrJavaSupport::throw_out_of_memory_error(const char* message, TRAPS) {
547   create_and_throw(vmSymbols::java_lang_OutOfMemoryError(), message, THREAD);
548 }
549 
550 void JfrJavaSupport::throw_class_format_error(const char* message, TRAPS) {
551   create_and_throw(vmSymbols::java_lang_ClassFormatError(), message, THREAD);
552 }
553 
554 void JfrJavaSupport::throw_runtime_exception(const char* message, TRAPS) {
555   create_and_throw(vmSymbols::java_lang_RuntimeException(), message, THREAD);
556 }
557 
558 void JfrJavaSupport::abort(jstring errorMsg, JavaThread* t) {
559   DEBUG_ONLY(check_java_thread_in_vm(t));
560 
561   ResourceMark rm(t);
562   const char* const error_msg = c_str(errorMsg, t);
563   if (error_msg != NULL) {
564     log_error(jfr, system)("%s",error_msg);
565   }
566   log_error(jfr, system)("%s", "An irrecoverable error in Jfr. Shutting down VM...");
567   vm_abort();
568 }
569 
570 JfrJavaSupport::CAUSE JfrJavaSupport::_cause = JfrJavaSupport::VM_ERROR;
571 void JfrJavaSupport::set_cause(jthrowable throwable, JavaThread* t) {
572   DEBUG_ONLY(check_java_thread_in_vm(t));
573 
574   HandleMark hm(t);
575   Handle ex(t, JNIHandles::resolve_external_guard(throwable));
576 
577   if (ex.is_null()) {
578     return;
579   }
580 
581   if (ex->is_a(vmClasses::OutOfMemoryError_klass())) {
582     _cause = OUT_OF_MEMORY;
583     return;
584   }
585   if (ex->is_a(vmClasses::StackOverflowError_klass())) {
586     _cause = STACK_OVERFLOW;
587     return;
588   }
589   if (ex->is_a(vmClasses::Error_klass())) {
590     _cause = VM_ERROR;
591     return;
592   }
593   if (ex->is_a(vmClasses::RuntimeException_klass())) {
594     _cause = RUNTIME_EXCEPTION;
595     return;
596   }
597   if (ex->is_a(vmClasses::Exception_klass())) {
598     _cause = UNKNOWN;
599     return;
600   }
601 }
602 
603 void JfrJavaSupport::uncaught_exception(jthrowable throwable, JavaThread* t) {
604   DEBUG_ONLY(check_java_thread_in_vm(t));
605   assert(throwable != NULL, "invariant");
606   set_cause(throwable, t);
607 }
608 
609 JfrJavaSupport::CAUSE JfrJavaSupport::cause() {
610   return _cause;
611 }
612 
613 const char* const JDK_JFR_MODULE_NAME = "jdk.jfr";
614 const char* const JDK_JFR_PACKAGE_NAME = "jdk/jfr";
615 
616 static bool is_jdk_jfr_module_in_readability_graph() {
617   // take one of the packages in the module to be located and query for its definition.
618   TempNewSymbol pkg_sym = SymbolTable::new_symbol(JDK_JFR_PACKAGE_NAME);
619   return Modules::is_package_defined(pkg_sym, Handle());
620 }
621 
622 static void print_module_resolution_error(outputStream* stream) {
623   assert(stream != NULL, "invariant");
624   stream->print_cr("Module %s not found.", JDK_JFR_MODULE_NAME);
625   stream->print_cr("Flight Recorder can not be enabled.");
626 }
627 
628 bool JfrJavaSupport::is_jdk_jfr_module_available() {
629   return is_jdk_jfr_module_in_readability_graph();
630 }
631 
632 bool JfrJavaSupport::is_jdk_jfr_module_available(outputStream* stream, TRAPS) {
633   if (!JfrJavaSupport::is_jdk_jfr_module_available()) {
634     if (stream != NULL) {
635       print_module_resolution_error(stream);
636     }
637     return false;
638   }
639   return true;
640 }
641 
642 class ThreadExclusionListAccess : public StackObj {
643  private:
644   static Semaphore _mutex_semaphore;
645  public:
646   ThreadExclusionListAccess() { _mutex_semaphore.wait(); }
647   ~ThreadExclusionListAccess() { _mutex_semaphore.signal(); }
648 };
649 
650 Semaphore ThreadExclusionListAccess::_mutex_semaphore(1);
651 static GrowableArray<jweak>* exclusion_list = NULL;
652 
653 static bool equals(const jweak excluded_thread, Handle target_thread) {
654   return JfrJavaSupport::resolve_non_null(excluded_thread) == target_thread();
655 }
656 
657 static int find_exclusion_thread_idx(Handle thread) {
658   if (exclusion_list != NULL) {
659     for (int i = 0; i < exclusion_list->length(); ++i) {
660       if (equals(exclusion_list->at(i), thread)) {
661         return i;
662       }
663     }
664   }
665   return -1;
666 }
667 
668 static Handle as_handle(jobject thread) {
669   return Handle(Thread::current(), JfrJavaSupport::resolve_non_null(thread));
670 }
671 
672 static bool thread_is_not_excluded(Handle thread) {
673   return -1 == find_exclusion_thread_idx(thread);
674 }
675 
676 static bool thread_is_not_excluded(jobject thread) {
677   return thread_is_not_excluded(as_handle(thread));
678 }
679 
680 static bool is_thread_excluded(jobject thread) {
681   return !thread_is_not_excluded(thread);
682 }
683 
684 #ifdef ASSERT
685 static bool is_thread_excluded(Handle thread) {
686   return !thread_is_not_excluded(thread);
687 }
688 #endif // ASSERT
689 
690 static int add_thread_to_exclusion_list(jobject thread) {
691   ThreadExclusionListAccess lock;
692   if (exclusion_list == NULL) {
693     exclusion_list = new (ResourceObj::C_HEAP, mtTracing) GrowableArray<jweak>(10, mtTracing);
694   }
695   assert(exclusion_list != NULL, "invariant");
696   assert(thread_is_not_excluded(thread), "invariant");
697   jweak ref = JfrJavaSupport::global_weak_jni_handle(thread, JavaThread::current());
698   const int idx = exclusion_list->append(ref);
699   assert(is_thread_excluded(thread), "invariant");
700   return idx;
701 }
702 
703 static void remove_thread_from_exclusion_list(Handle thread) {
704   assert(exclusion_list != NULL, "invariant");
705   assert(is_thread_excluded(thread), "invariant");
706   assert(exclusion_list != NULL, "invariant");
707   const int idx = find_exclusion_thread_idx(thread);
708   assert(idx >= 0, "invariant");
709   assert(idx < exclusion_list->length(), "invariant");
710   JfrJavaSupport::destroy_global_weak_jni_handle(exclusion_list->at(idx));
711   exclusion_list->delete_at(idx);
712   assert(thread_is_not_excluded(thread), "invariant");
713   if (0 == exclusion_list->length()) {
714     delete exclusion_list;
715     exclusion_list = NULL;
716   }
717 }
718 
719 static void remove_thread_from_exclusion_list(jobject thread) {
720   ThreadExclusionListAccess lock;
721   remove_thread_from_exclusion_list(as_handle(thread));
722 }
723 
724 // includes removal
725 static bool check_exclusion_state_on_thread_start(Handle h_threadObj) {
726   ThreadExclusionListAccess lock;
727   if (thread_is_not_excluded(h_threadObj)) {
728     return false;
729   }
730   remove_thread_from_exclusion_list(h_threadObj);
731   return true;
732 }
733 
734 JavaThread* JfrJavaSupport::get_native(jobject thread) {
735   ThreadsListHandle tlh;
736   JavaThread* native_thread = NULL;
737   (void)tlh.cv_internal_thread_to_JavaThread(thread, &native_thread, NULL);
738   return native_thread;
739 }
740 
741 jlong JfrJavaSupport::jfr_thread_id(jobject thread) {
742   JavaThread* native_thread = get_native(thread);
743   return native_thread != NULL ? JFR_THREAD_ID(native_thread) : 0;
744 }
745 
746 void JfrJavaSupport::exclude(jobject thread) {
747   JavaThread* native_thread = get_native(thread);
748   if (native_thread != NULL) {
749     JfrThreadLocal::exclude(native_thread);
750   } else {
751     // not started yet, track the thread oop
752     add_thread_to_exclusion_list(thread);
753   }
754 }
755 
756 void JfrJavaSupport::include(jobject thread) {
757   JavaThread* native_thread = get_native(thread);
758   if (native_thread != NULL) {
759     JfrThreadLocal::include(native_thread);
760   } else {
761     // not started yet, untrack the thread oop
762     remove_thread_from_exclusion_list(thread);
763   }
764 }
765 
766 bool JfrJavaSupport::is_excluded(jobject thread) {
767   JavaThread* native_thread = get_native(thread);
768   return native_thread != NULL ? native_thread->jfr_thread_local()->is_excluded() : is_thread_excluded(thread);
769 }
770 
771 static const Klass* get_handler_field_descriptor(const Handle& h_mirror, fieldDescriptor* descriptor, TRAPS) {
772   assert(h_mirror.not_null(), "invariant");
773   assert(descriptor != NULL, "invariant");
774   Klass* const k = java_lang_Class::as_Klass(h_mirror());
775   assert(k->is_instance_klass(), "invariant");
776   InstanceKlass* const ik = InstanceKlass::cast(k);
777   if (ik->is_not_initialized()) {
778     ik->initialize(CHECK_NULL);
779   }
780   assert(ik->is_being_initialized() || ik->is_initialized(), "invariant");
781   const Klass* const typed_field_holder = ik->find_field(vmSymbols::eventHandler_name(),
782                                                          vmSymbols::jdk_jfr_internal_handlers_EventHandler_signature(),
783                                                          true,
784                                                          descriptor);
785   return typed_field_holder != NULL ? typed_field_holder : ik->find_field(vmSymbols::eventHandler_name(),
786                                                                           vmSymbols::object_signature(), // untyped
787                                                                           true,
788                                                                           descriptor);
789 }
790 
791 jobject JfrJavaSupport::get_handler(jobject clazz, TRAPS) {
792   DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(THREAD));
793   HandleMark hm(THREAD);
794   const Handle h_mirror(Handle(THREAD, JNIHandles::resolve(clazz)));
795   assert(h_mirror.not_null(), "invariant");
796   fieldDescriptor handler_field_descriptor;
797   const Klass* const field_holder = get_handler_field_descriptor(h_mirror, &handler_field_descriptor, THREAD);
798   if (field_holder == NULL) {
799     // The only reason should be that klass initialization failed.
800     return NULL;
801   }
802   assert(java_lang_Class::as_Klass(h_mirror()) == field_holder, "invariant");
803   oop handler_oop = h_mirror->obj_field(handler_field_descriptor.offset());
804   return handler_oop != NULL ? JfrJavaSupport::local_jni_handle(handler_oop, THREAD) : NULL;
805 }
806 
807 bool JfrJavaSupport::set_handler(jobject clazz, jobject handler, TRAPS) {
808   DEBUG_ONLY(JfrJavaSupport::check_java_thread_in_vm(THREAD));
809   HandleMark hm(THREAD);
810   const Handle h_mirror(Handle(THREAD, JNIHandles::resolve(clazz)));
811   assert(h_mirror.not_null(), "invariant");
812   fieldDescriptor handler_field_descriptor;
813   const Klass* const field_holder = get_handler_field_descriptor(h_mirror, &handler_field_descriptor, THREAD);
814   if (field_holder == NULL) {
815     // The only reason should be that klass initialization failed.
816     return false;
817   }
818   assert(java_lang_Class::as_Klass(h_mirror()) == field_holder, "invariant");
819   const oop handler_oop = JNIHandles::resolve(handler);
820   assert(handler_oop != NULL, "invariant");
821   h_mirror->obj_field_put(handler_field_descriptor.offset(), handler_oop);
822   return true;
823 }
824 
825 bool JfrJavaSupport::on_thread_start(JavaThread* jt, jobject vthread) {
826   assert(jt != NULL, "invariant");
827   assert(Thread::current() == jt, "invariant");
828   DEBUG_ONLY(check_new_unstarted_java_thread(jt, vthread);)
829   HandleMark hm(jt);
830   const oop threadObj = vthread != NULL ? resolve_non_null(vthread) : jt->threadObj();
831   Handle h_obj(jt, threadObj);
832   if (check_exclusion_state_on_thread_start(h_obj)) {
833     if (vthread != NULL) {
834       exclude(vthread);
835     } else {
836       JfrThreadLocal::exclude(jt);
837     }
838     return false;
839   }
840   return true;
841 }
842 
843 static bool find_field(const InstanceKlass* ik,
844                        Symbol* name_symbol,
845                        Symbol* signature_symbol,
846                        fieldDescriptor* fd,
847                        bool is_static = false,
848                        bool allow_super = false) {
849   assert(ik != NULL, "invariant");
850   if (allow_super || is_static) {
851     return ik->find_field(name_symbol, signature_symbol, is_static, fd) != NULL;
852   } else {
853     return ik->find_local_field(name_symbol, signature_symbol, fd);
854   }
855 }
856 
857 bool JfrJavaSupport::compute_field_offset(int &dest_offset,
858                                           Klass* klass,
859                                           Symbol* name_symbol,
860                                           Symbol* signature_symbol,
861                                           bool is_static,
862                                           bool allow_super) {
863   fieldDescriptor fd;
864   const InstanceKlass* const ik = InstanceKlass::cast(klass);
865   if (!find_field(ik, name_symbol, signature_symbol, &fd, is_static, allow_super)) {
866     return false;
867   }
868   dest_offset = fd.offset();
869   return true;
870 }