1 /*
  2  * Copyright (c) 1998, 2022, 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.hpp"
 27 #include "classfile/systemDictionary.hpp"
 28 #include "classfile/vmClasses.hpp"
 29 #include "classfile/vmSymbols.hpp"
 30 #include "compiler/compileBroker.hpp"
 31 #include "logging/log.hpp"
 32 #include "logging/logStream.hpp"
 33 #include "memory/resourceArea.hpp"
 34 #include "memory/universe.hpp"
 35 #include "oops/oop.inline.hpp"
 36 #include "runtime/handles.inline.hpp"
 37 #include "runtime/init.hpp"
 38 #include "runtime/java.hpp"
 39 #include "runtime/javaCalls.hpp"
 40 #include "runtime/javaThread.hpp"
 41 #include "runtime/os.hpp"
 42 #include "runtime/threadCritical.hpp"
 43 #include "runtime/atomic.hpp"
 44 #include "utilities/events.hpp"
 45 #include "utilities/exceptions.hpp"
 46 
 47 // Implementation of ThreadShadow
 48 void check_ThreadShadow() {
 49   const ByteSize offset1 = byte_offset_of(ThreadShadow, _pending_exception);
 50   const ByteSize offset2 = Thread::pending_exception_offset();
 51   if (offset1 != offset2) fatal("ThreadShadow::_pending_exception is not positioned correctly");
 52 }
 53 
 54 
 55 void ThreadShadow::set_pending_exception(oop exception, const char* file, int line) {
 56   assert(exception != NULL && oopDesc::is_oop(exception), "invalid exception oop");
 57   _pending_exception = exception;
 58   _exception_file    = file;
 59   _exception_line    = line;
 60 }
 61 
 62 void ThreadShadow::clear_pending_exception() {
 63   LogTarget(Debug, exceptions) lt;
 64   if (_pending_exception != NULL && lt.is_enabled()) {
 65     ResourceMark rm;
 66     LogStream ls(lt);
 67     ls.print("Thread::clear_pending_exception: cleared exception:");
 68     _pending_exception->print_on(&ls);
 69   }
 70   _pending_exception = NULL;
 71   _exception_file    = NULL;
 72   _exception_line    = 0;
 73 }
 74 
 75 void ThreadShadow::clear_pending_nonasync_exception() {
 76   // Do not clear probable async exceptions.
 77   if ((_pending_exception->klass() != vmClasses::InternalError_klass() ||
 78        java_lang_InternalError::during_unsafe_access(_pending_exception) != JNI_TRUE)) {
 79     clear_pending_exception();
 80   }
 81 }
 82 
 83 // Implementation of Exceptions
 84 
 85 bool Exceptions::special_exception(JavaThread* thread, const char* file, int line, Handle h_exception) {
 86   // bootstrapping check
 87   if (!Universe::is_fully_initialized()) {
 88    vm_exit_during_initialization(h_exception);
 89    ShouldNotReachHere();
 90   }
 91 
 92 #ifdef ASSERT
 93   // Check for trying to throw stack overflow before initialization is complete
 94   // to prevent infinite recursion trying to initialize stack overflow without
 95   // adequate stack space.
 96   // This can happen with stress testing a large value of StackShadowPages
 97   if (h_exception()->klass() == vmClasses::StackOverflowError_klass()) {
 98     InstanceKlass* ik = InstanceKlass::cast(h_exception->klass());
 99     assert(ik->is_initialized(),
100            "need to increase java_thread_min_stack_allowed calculation");
101   }
102 #endif // ASSERT
103 
104   if (!thread->can_call_java()) {
105     // We do not care what kind of exception we get for a thread which
106     // is compiling.  We just install a dummy exception object
107     thread->set_pending_exception(Universe::vm_exception(), file, line);
108     return true;
109   }
110 
111   return false;
112 }
113 
114 bool Exceptions::special_exception(JavaThread* thread, const char* file, int line, Symbol* h_name, const char* message) {
115   // bootstrapping check
116   if (!Universe::is_fully_initialized()) {
117     if (h_name == NULL) {
118       // at least an informative message.
119       vm_exit_during_initialization("Exception", message);
120     } else {
121       vm_exit_during_initialization(h_name, message);
122     }
123     ShouldNotReachHere();
124   }
125 
126   if (!thread->can_call_java()) {
127     // We do not care what kind of exception we get for a thread which
128     // is compiling.  We just install a dummy exception object
129     thread->set_pending_exception(Universe::vm_exception(), file, line);
130     return true;
131   }
132   return false;
133 }
134 
135 // This method should only be called from generated code,
136 // therefore the exception oop should be in the oopmap.
137 void Exceptions::_throw_oop(JavaThread* thread, const char* file, int line, oop exception) {
138   assert(exception != NULL, "exception should not be NULL");
139   Handle h_exception(thread, exception);
140   _throw(thread, file, line, h_exception);
141 }
142 
143 void Exceptions::_throw(JavaThread* thread, const char* file, int line, Handle h_exception, const char* message) {
144   ResourceMark rm(thread);
145   assert(h_exception() != NULL, "exception should not be NULL");
146 
147   // tracing (do this up front - so it works during boot strapping)
148   // Note, the print_value_string() argument is not called unless logging is enabled!
149   log_info(exceptions)("Exception <%s%s%s> (" PTR_FORMAT ") \n"
150                        "thrown [%s, line %d]\nfor thread " PTR_FORMAT,
151                        h_exception->print_value_string(),
152                        message ? ": " : "", message ? message : "",
153                        p2i(h_exception()), file, line, p2i(thread));
154 
155   // for AbortVMOnException flag
156   Exceptions::debug_check_abort(h_exception, message);
157 
158   // Check for special boot-strapping/compiler-thread handling
159   if (special_exception(thread, file, line, h_exception)) {
160     return;
161   }
162 
163   if (h_exception->is_a(vmClasses::OutOfMemoryError_klass())) {
164     count_out_of_memory_exceptions(h_exception);
165   }
166 
167   if (h_exception->is_a(vmClasses::LinkageError_klass())) {
168     Atomic::inc(&_linkage_errors, memory_order_relaxed);
169   }
170 
171   assert(h_exception->is_a(vmClasses::Throwable_klass()), "exception is not a subclass of java/lang/Throwable");
172 
173   // set the pending exception
174   thread->set_pending_exception(h_exception(), file, line);
175 
176   // vm log
177   Events::log_exception(thread, h_exception, message, file, line);
178 }
179 
180 
181 void Exceptions::_throw_msg(JavaThread* thread, const char* file, int line, Symbol* name, const char* message,
182                             Handle h_loader, Handle h_protection_domain) {
183   // Check for special boot-strapping/compiler-thread handling
184   if (special_exception(thread, file, line, name, message)) return;
185   // Create and throw exception
186   Handle h_cause(thread, NULL);
187   Handle h_exception = new_exception(thread, name, message, h_cause, h_loader, h_protection_domain);
188   _throw(thread, file, line, h_exception, message);
189 }
190 
191 void Exceptions::_throw_msg_cause(JavaThread* thread, const char* file, int line, Symbol* name, const char* message, Handle h_cause,
192                                   Handle h_loader, Handle h_protection_domain) {
193   // Check for special boot-strapping/compiler-thread handling
194   if (special_exception(thread, file, line, name, message)) return;
195   // Create and throw exception and init cause
196   Handle h_exception = new_exception(thread, name, message, h_cause, h_loader, h_protection_domain);
197   _throw(thread, file, line, h_exception, message);
198 }
199 
200 void Exceptions::_throw_cause(JavaThread* thread, const char* file, int line, Symbol* name, Handle h_cause,
201                               Handle h_loader, Handle h_protection_domain) {
202   // Check for special boot-strapping/compiler-thread handling
203   if (special_exception(thread, file, line, h_cause)) return;
204   // Create and throw exception
205   Handle h_exception = new_exception(thread, name, h_cause, h_loader, h_protection_domain);
206   _throw(thread, file, line, h_exception, NULL);
207 }
208 
209 void Exceptions::_throw_args(JavaThread* thread, const char* file, int line, Symbol* name, Symbol* signature, JavaCallArguments *args) {
210   // Check for special boot-strapping/compiler-thread handling
211   if (special_exception(thread, file, line, name, NULL)) return;
212   // Create and throw exception
213   Handle h_loader(thread, NULL);
214   Handle h_prot(thread, NULL);
215   Handle exception = new_exception(thread, name, signature, args, h_loader, h_prot);
216   _throw(thread, file, line, exception);
217 }
218 
219 
220 // Methods for default parameters.
221 // NOTE: These must be here (and not in the header file) because of include circularities.
222 void Exceptions::_throw_msg_cause(JavaThread* thread, const char* file, int line, Symbol* name, const char* message, Handle h_cause) {
223   _throw_msg_cause(thread, file, line, name, message, h_cause, Handle(thread, NULL), Handle(thread, NULL));
224 }
225 void Exceptions::_throw_msg(JavaThread* thread, const char* file, int line, Symbol* name, const char* message) {
226   _throw_msg(thread, file, line, name, message, Handle(thread, NULL), Handle(thread, NULL));
227 }
228 void Exceptions::_throw_cause(JavaThread* thread, const char* file, int line, Symbol* name, Handle h_cause) {
229   _throw_cause(thread, file, line, name, h_cause, Handle(thread, NULL), Handle(thread, NULL));
230 }
231 
232 
233 void Exceptions::throw_stack_overflow_exception(JavaThread* THREAD, const char* file, int line, const methodHandle& method) {
234   Handle exception;
235   if (!THREAD->has_pending_exception()) {
236     InstanceKlass* k = vmClasses::StackOverflowError_klass();
237     oop e = k->allocate_instance(CHECK);
238     exception = Handle(THREAD, e);  // fill_in_stack trace does gc
239     assert(k->is_initialized(), "need to increase java_thread_min_stack_allowed calculation");
240     if (StackTraceInThrowable) {
241       java_lang_Throwable::fill_in_stack_trace(exception, method);
242     }
243     // Increment counter for hs_err file reporting
244     Atomic::inc(&Exceptions::_stack_overflow_errors, memory_order_relaxed);
245   } else {
246     // if prior exception, throw that one instead
247     exception = Handle(THREAD, THREAD->pending_exception());
248   }
249   _throw(THREAD, file, line, exception);
250 }
251 
252 void Exceptions::fthrow(JavaThread* thread, const char* file, int line, Symbol* h_name, const char* format, ...) {
253   const int max_msg_size = 1024;
254   va_list ap;
255   va_start(ap, format);
256   char msg[max_msg_size];
257   os::vsnprintf(msg, max_msg_size, format, ap);
258   va_end(ap);
259   _throw_msg(thread, file, line, h_name, msg);
260 }
261 
262 
263 // Creates an exception oop, calls the <init> method with the given signature.
264 // and returns a Handle
265 Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
266                                  Symbol* signature, JavaCallArguments *args,
267                                  Handle h_loader, Handle h_protection_domain) {
268   assert(Universe::is_fully_initialized(),
269     "cannot be called during initialization");
270   assert(!thread->has_pending_exception(), "already has exception");
271 
272   Handle h_exception;
273 
274   // Resolve exception klass, and check for pending exception below.
275   Klass* klass = SystemDictionary::resolve_or_fail(name, h_loader, h_protection_domain, true, thread);
276 
277   if (!thread->has_pending_exception()) {
278     assert(klass != NULL, "klass must exist");
279     h_exception = JavaCalls::construct_new_instance(InstanceKlass::cast(klass),
280                                 signature,
281                                 args,
282                                 thread);
283   }
284 
285   // Check if another exception was thrown in the process, if so rethrow that one
286   if (thread->has_pending_exception()) {
287     h_exception = Handle(thread, thread->pending_exception());
288     thread->clear_pending_exception();
289   }
290   return h_exception;
291 }
292 
293 // Creates an exception oop, calls the <init> method with the given signature.
294 // and returns a Handle
295 // Initializes the cause if cause non-null
296 Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
297                                  Symbol* signature, JavaCallArguments *args,
298                                  Handle h_cause,
299                                  Handle h_loader, Handle h_protection_domain) {
300   Handle h_exception = new_exception(thread, name, signature, args, h_loader, h_protection_domain);
301 
302   // Future: object initializer should take a cause argument
303   if (h_cause.not_null()) {
304     assert(h_cause->is_a(vmClasses::Throwable_klass()),
305         "exception cause is not a subclass of java/lang/Throwable");
306     JavaValue result1(T_OBJECT);
307     JavaCallArguments args1;
308     args1.set_receiver(h_exception);
309     args1.push_oop(h_cause);
310     JavaCalls::call_virtual(&result1, h_exception->klass(),
311                                       vmSymbols::initCause_name(),
312                                       vmSymbols::throwable_throwable_signature(),
313                                       &args1,
314                                       thread);
315   }
316 
317   // Check if another exception was thrown in the process, if so rethrow that one
318   if (thread->has_pending_exception()) {
319     h_exception = Handle(thread, thread->pending_exception());
320     thread->clear_pending_exception();
321   }
322   return h_exception;
323 }
324 
325 // Convenience method. Calls either the <init>() or <init>(Throwable) method when
326 // creating a new exception
327 Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
328                                  Handle h_cause,
329                                  Handle h_loader, Handle h_protection_domain,
330                                  ExceptionMsgToUtf8Mode to_utf8_safe) {
331   JavaCallArguments args;
332   Symbol* signature = NULL;
333   if (h_cause.is_null()) {
334     signature = vmSymbols::void_method_signature();
335   } else {
336     signature = vmSymbols::throwable_void_signature();
337     args.push_oop(h_cause);
338   }
339   return new_exception(thread, name, signature, &args, h_loader, h_protection_domain);
340 }
341 
342 // Convenience method. Calls either the <init>() or <init>(String) method when
343 // creating a new exception
344 Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
345                                  const char* message, Handle h_cause,
346                                  Handle h_loader, Handle h_protection_domain,
347                                  ExceptionMsgToUtf8Mode to_utf8_safe) {
348   JavaCallArguments args;
349   Symbol* signature = NULL;
350   if (message == NULL) {
351     signature = vmSymbols::void_method_signature();
352   } else {
353     // There should be no pending exception. The caller is responsible for not calling
354     // this with a pending exception.
355     Handle incoming_exception;
356     if (thread->has_pending_exception()) {
357       incoming_exception = Handle(thread, thread->pending_exception());
358       thread->clear_pending_exception();
359       ResourceMark rm(thread);
360       assert(incoming_exception.is_null(), "Pending exception while throwing %s %s", name->as_C_string(), message);
361     }
362     Handle msg;
363     if (to_utf8_safe == safe_to_utf8) {
364       // Make a java UTF8 string.
365       msg = java_lang_String::create_from_str(message, thread);
366     } else {
367       // Make a java string keeping the encoding scheme of the original string.
368       msg = java_lang_String::create_from_platform_dependent_str(message, thread);
369     }
370     // If we get an exception from the allocation, prefer that to
371     // the exception we are trying to build, or the pending exception (in product mode)
372     if (thread->has_pending_exception()) {
373       Handle exception(thread, thread->pending_exception());
374       thread->clear_pending_exception();
375       return exception;
376     }
377     if (incoming_exception.not_null()) {
378       return incoming_exception;
379     }
380     args.push_oop(msg);
381     signature = vmSymbols::string_void_signature();
382   }
383   return new_exception(thread, name, signature, &args, h_cause, h_loader, h_protection_domain);
384 }
385 
386 // Another convenience method that creates handles for null class loaders and
387 // protection domains and null causes.
388 // If the last parameter 'to_utf8_mode' is safe_to_utf8,
389 // it means we can safely ignore the encoding scheme of the message string and
390 // convert it directly to a java UTF8 string. Otherwise, we need to take the
391 // encoding scheme of the string into account. One thing we should do at some
392 // point is to push this flag down to class java_lang_String since other
393 // classes may need similar functionalities.
394 Handle Exceptions::new_exception(JavaThread* thread, Symbol* name,
395                                  const char* message,
396                                  ExceptionMsgToUtf8Mode to_utf8_safe) {
397 
398   Handle       h_loader(thread, NULL);
399   Handle       h_prot(thread, NULL);
400   Handle       h_cause(thread, NULL);
401   return Exceptions::new_exception(thread, name, message, h_cause, h_loader,
402                                    h_prot, to_utf8_safe);
403 }
404 
405 // invokedynamic uses wrap_dynamic_exception for:
406 //    - bootstrap method resolution
407 //    - post call to MethodHandleNatives::linkCallSite
408 // dynamically computed constant uses wrap_dynamic_exception for:
409 //    - bootstrap method resolution
410 //    - post call to MethodHandleNatives::linkDynamicConstant
411 void Exceptions::wrap_dynamic_exception(bool is_indy, JavaThread* THREAD) {
412   if (THREAD->has_pending_exception()) {
413     bool log_indy = log_is_enabled(Debug, methodhandles, indy) && is_indy;
414     bool log_condy = log_is_enabled(Debug, methodhandles, condy) && !is_indy;
415     LogStreamHandle(Debug, methodhandles, indy) lsh_indy;
416     LogStreamHandle(Debug, methodhandles, condy) lsh_condy;
417     LogStream* ls = NULL;
418     if (log_indy) {
419       ls = &lsh_indy;
420     } else if (log_condy) {
421       ls = &lsh_condy;
422     }
423     oop exception = THREAD->pending_exception();
424 
425     // See the "Linking Exceptions" section for the invokedynamic instruction
426     // in JVMS 6.5.
427     if (exception->is_a(vmClasses::Error_klass())) {
428       // Pass through an Error, including BootstrapMethodError, any other form
429       // of linkage error, or say OutOfMemoryError
430       if (ls != NULL) {
431         ls->print_cr("bootstrap method invocation wraps BSME around " PTR_FORMAT, p2i(exception));
432         exception->print_on(ls);
433       }
434       return;
435     }
436 
437     // Otherwise wrap the exception in a BootstrapMethodError
438     if (ls != NULL) {
439       ls->print_cr("%s throws BSME for " PTR_FORMAT, is_indy ? "invokedynamic" : "dynamic constant", p2i(exception));
440       exception->print_on(ls);
441     }
442     Handle nested_exception(THREAD, exception);
443     THREAD->clear_pending_exception();
444     THROW_CAUSE(vmSymbols::java_lang_BootstrapMethodError(), nested_exception)
445   }
446 }
447 
448 // Exception counting for hs_err file
449 volatile int Exceptions::_stack_overflow_errors = 0;
450 volatile int Exceptions::_linkage_errors = 0;
451 volatile int Exceptions::_out_of_memory_error_java_heap_errors = 0;
452 volatile int Exceptions::_out_of_memory_error_metaspace_errors = 0;
453 volatile int Exceptions::_out_of_memory_error_class_metaspace_errors = 0;
454 
455 void Exceptions::count_out_of_memory_exceptions(Handle exception) {
456   if (Universe::is_out_of_memory_error_metaspace(exception())) {
457      Atomic::inc(&_out_of_memory_error_metaspace_errors, memory_order_relaxed);
458   } else if (Universe::is_out_of_memory_error_class_metaspace(exception())) {
459      Atomic::inc(&_out_of_memory_error_class_metaspace_errors, memory_order_relaxed);
460   } else {
461      // everything else reported as java heap OOM
462      Atomic::inc(&_out_of_memory_error_java_heap_errors, memory_order_relaxed);
463   }
464 }
465 
466 void print_oom_count(outputStream* st, const char *err, int count) {
467   if (count > 0) {
468     st->print_cr("OutOfMemoryError %s=%d", err, count);
469   }
470 }
471 
472 bool Exceptions::has_exception_counts() {
473   return (_stack_overflow_errors + _out_of_memory_error_java_heap_errors +
474          _out_of_memory_error_metaspace_errors + _out_of_memory_error_class_metaspace_errors) > 0;
475 }
476 
477 void Exceptions::print_exception_counts_on_error(outputStream* st) {
478   print_oom_count(st, "java_heap_errors", _out_of_memory_error_java_heap_errors);
479   print_oom_count(st, "metaspace_errors", _out_of_memory_error_metaspace_errors);
480   print_oom_count(st, "class_metaspace_errors", _out_of_memory_error_class_metaspace_errors);
481   if (_stack_overflow_errors > 0) {
482     st->print_cr("StackOverflowErrors=%d", _stack_overflow_errors);
483   }
484   if (_linkage_errors > 0) {
485     st->print_cr("LinkageErrors=%d", _linkage_errors);
486   }
487 }
488 
489 // Implementation of ExceptionMark
490 
491 ExceptionMark::ExceptionMark(JavaThread* thread) {
492   assert(thread == JavaThread::current(), "must be");
493   _thread  = thread;
494   check_no_pending_exception();
495 }
496 
497 ExceptionMark::ExceptionMark() {
498   _thread = JavaThread::current();
499   check_no_pending_exception();
500 }
501 
502 inline void ExceptionMark::check_no_pending_exception() {
503   if (_thread->has_pending_exception()) {
504     oop exception = _thread->pending_exception();
505     _thread->clear_pending_exception(); // Needed to avoid infinite recursion
506     exception->print();
507     fatal("ExceptionMark constructor expects no pending exceptions");
508   }
509 }
510 
511 
512 ExceptionMark::~ExceptionMark() {
513   if (_thread->has_pending_exception()) {
514     Handle exception(_thread, _thread->pending_exception());
515     _thread->clear_pending_exception(); // Needed to avoid infinite recursion
516     if (is_init_completed()) {
517       exception->print();
518       fatal("ExceptionMark destructor expects no pending exceptions");
519     } else {
520       vm_exit_during_initialization(exception);
521     }
522   }
523 }
524 
525 // ----------------------------------------------------------------------------------------
526 
527 // caller frees value_string if necessary
528 void Exceptions::debug_check_abort(const char *value_string, const char* message) {
529   if (AbortVMOnException != NULL && value_string != NULL &&
530       strstr(value_string, AbortVMOnException)) {
531     if (AbortVMOnExceptionMessage == NULL || (message != NULL &&
532         strstr(message, AbortVMOnExceptionMessage))) {
533       if (message == NULL) {
534         fatal("Saw %s, aborting", value_string);
535       } else {
536         fatal("Saw %s: %s, aborting", value_string, message);
537       }
538     }
539   }
540 }
541 
542 void Exceptions::debug_check_abort(Handle exception, const char* message) {
543   if (AbortVMOnException != NULL) {
544     debug_check_abort_helper(exception, message);
545   }
546 }
547 
548 void Exceptions::debug_check_abort_helper(Handle exception, const char* message) {
549   ResourceMark rm;
550   if (message == NULL && exception->is_a(vmClasses::Throwable_klass())) {
551     oop msg = java_lang_Throwable::message(exception());
552     if (msg != NULL) {
553       message = java_lang_String::as_utf8_string(msg);
554     }
555   }
556   debug_check_abort(exception()->klass()->external_name(), message);
557 }
558 
559 // for logging exceptions
560 void Exceptions::log_exception(Handle exception, const char* message) {
561   ResourceMark rm;
562   Symbol* detail_message = java_lang_Throwable::detail_message(exception());
563   if (detail_message != NULL) {
564     log_info(exceptions)("Exception <%s: %s>\n thrown in %s",
565                          exception->print_value_string(),
566                          detail_message->as_C_string(),
567                          message);
568   } else {
569     log_info(exceptions)("Exception <%s>\n thrown in %s",
570                          exception->print_value_string(),
571                          message);
572   }
573 }