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