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