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