1 /*
   2  * Copyright (c) 1998, 2011, 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 "oops/oop.inline.hpp"
  30 #include "runtime/init.hpp"
  31 #include "runtime/java.hpp"
  32 #include "runtime/javaCalls.hpp"
  33 #include "runtime/threadCritical.hpp"
  34 #include "utilities/events.hpp"
  35 #include "utilities/exceptions.hpp"
  36 #ifdef TARGET_OS_FAMILY_linux
  37 # include "thread_linux.inline.hpp"
  38 #endif
  39 #ifdef TARGET_OS_FAMILY_solaris
  40 # include "thread_solaris.inline.hpp"
  41 #endif
  42 #ifdef TARGET_OS_FAMILY_windows
  43 # include "thread_windows.inline.hpp"
  44 #endif
  45 #ifdef TARGET_OS_FAMILY_bsd
  46 # include "thread_bsd.inline.hpp"
  47 #endif
  48 
  49 
  50 // Implementation of ThreadShadow
  51 void check_ThreadShadow() {
  52   const ByteSize offset1 = byte_offset_of(ThreadShadow, _pending_exception);
  53   const ByteSize offset2 = Thread::pending_exception_offset();
  54   if (offset1 != offset2) fatal("ThreadShadow::_pending_exception is not positioned correctly");
  55 }
  56 
  57 
  58 void ThreadShadow::set_pending_exception(oop exception, const char* file, int line) {
  59   assert(exception != NULL && exception->is_oop(), "invalid exception oop");
  60   _pending_exception = exception;
  61   _exception_file    = file;
  62   _exception_line    = line;
  63 }
  64 
  65 void ThreadShadow::clear_pending_exception() {
  66   if (TraceClearedExceptions) {
  67     if (_pending_exception != NULL) {
  68       tty->print_cr("Thread::clear_pending_exception: cleared exception:");
  69       _pending_exception->print();
  70     }
  71   }
  72   _pending_exception = NULL;
  73   _exception_file    = NULL;
  74   _exception_line    = 0;
  75 }
  76 // Implementation of Exceptions
  77 
  78 bool Exceptions::special_exception(Thread* thread, const char* file, int line, Handle h_exception) {
  79   // bootstrapping check
  80   if (!Universe::is_fully_initialized()) {
  81    vm_exit_during_initialization(h_exception);
  82    ShouldNotReachHere();
  83   }
  84 
  85 #ifdef ASSERT
  86   // Check for trying to throw stack overflow before initialization is complete
  87   // to prevent infinite recursion trying to initialize stack overflow without
  88   // adequate stack space.
  89   // This can happen with stress testing a large value of StackShadowPages
  90   if (h_exception()->klass() == SystemDictionary::StackOverflowError_klass()) {
  91     instanceKlass* ik = instanceKlass::cast(h_exception->klass());
  92     assert(ik->is_initialized(),
  93            "need to increase min_stack_allowed calculation");
  94   }
  95 #endif // ASSERT
  96 
  97   if (thread->is_VM_thread()
  98       || thread->is_Compiler_thread() ) {
  99     // We do not care what kind of exception we get for the vm-thread or a thread which
 100     // is compiling.  We just install a dummy exception object
 101     thread->set_pending_exception(Universe::vm_exception(), file, line);
 102     return true;
 103   }
 104 
 105   return false;
 106 }
 107 
 108 bool Exceptions::special_exception(Thread* thread, const char* file, int line, Symbol* h_name, const char* message) {
 109   // bootstrapping check
 110   if (!Universe::is_fully_initialized()) {
 111     if (h_name == NULL) {
 112       // atleast an informative message.
 113       vm_exit_during_initialization("Exception", message);
 114     } else {
 115       vm_exit_during_initialization(h_name, message);
 116     }
 117     ShouldNotReachHere();
 118   }
 119 
 120   if (thread->is_VM_thread()
 121       || thread->is_Compiler_thread() ) {
 122     // We do not care what kind of exception we get for the vm-thread or a thread which
 123     // is compiling.  We just install a dummy exception object
 124     thread->set_pending_exception(Universe::vm_exception(), file, line);
 125     return true;
 126   }
 127   return false;
 128 }
 129 
 130 // This method should only be called from generated code,
 131 // therefore the exception oop should be in the oopmap.
 132 void Exceptions::_throw_oop(Thread* thread, const char* file, int line, oop exception) {
 133   assert(exception != NULL, "exception should not be NULL");
 134   Handle h_exception = Handle(thread, exception);
 135   _throw(thread, file, line, h_exception);
 136 }
 137 
 138 void Exceptions::_throw(Thread* thread, const char* file, int line, Handle h_exception, const char* message) {
 139   assert(h_exception() != NULL, "exception should not be NULL");
 140 
 141   // tracing (do this up front - so it works during boot strapping)
 142   if (TraceExceptions) {
 143     ttyLocker ttyl;
 144     ResourceMark rm;
 145     tty->print_cr("Exception <%s>%s%s (" INTPTR_FORMAT " ) \n"
 146                   "thrown [%s, line %d]\nfor thread " INTPTR_FORMAT,
 147                   h_exception->print_value_string(),
 148                   message ? ": " : "", message ? message : "",
 149                   (address)h_exception(), file, line, thread);
 150   }
 151   // for AbortVMOnException flag
 152   NOT_PRODUCT(Exceptions::debug_check_abort(h_exception, message));
 153 
 154   // Check for special boot-strapping/vm-thread handling
 155   if (special_exception(thread, file, line, h_exception)) return;
 156 
 157   assert(h_exception->is_a(SystemDictionary::Throwable_klass()), "exception is not a subclass of java/lang/Throwable");
 158 
 159   // set the pending exception
 160   thread->set_pending_exception(h_exception(), file, line);
 161 
 162   // vm log
 163   Events::log("throw_exception " INTPTR_FORMAT, (address)h_exception());
 164 }
 165 
 166 
 167 void Exceptions::_throw_msg(Thread* thread, const char* file, int line, Symbol* h_name, const char* message, Handle h_loader, Handle h_protection_domain) {
 168   // Check for special boot-strapping/vm-thread handling
 169   if (special_exception(thread, file, line, h_name, message)) return;
 170   // Create and throw exception
 171   Handle h_cause(thread, NULL);
 172   Handle h_exception = new_exception(thread, h_name, message, h_cause, h_loader, h_protection_domain);
 173   _throw(thread, file, line, h_exception, message);
 174 }
 175 
 176 // Throw an exception with a message and a cause
 177 void Exceptions::_throw_msg_cause(Thread* thread, const char* file, int line, Symbol* h_name, const char* message, Handle h_cause, Handle h_loader, Handle h_protection_domain) {
 178   // Check for special boot-strapping/vm-thread handling
 179   if (special_exception(thread, file, line, h_name, message)) return;
 180   // Create and throw exception and init cause
 181   Handle h_exception = new_exception(thread, h_name, message, h_cause, h_loader, h_protection_domain);
 182   _throw(thread, file, line, h_exception, message);
 183 }
 184 
 185 // This version already has a handle for name
 186 void Exceptions::_throw_msg(Thread* thread, const char* file, int line,
 187                             Symbol* name, const char* message) {
 188   Handle       h_loader(thread, NULL);
 189   Handle       h_protection_domain(thread, NULL);
 190   Exceptions::_throw_msg(thread, file, line, name, message, h_loader, h_protection_domain);
 191 }
 192 
 193 // This version already has a handle for name
 194 void Exceptions::_throw_msg_cause(Thread* thread, const char* file, int line,
 195                             Symbol* name, const char* message, Handle cause) {
 196   Handle       h_loader(thread, NULL);
 197   Handle       h_protection_domain(thread, NULL);
 198   Exceptions::_throw_msg_cause(thread, file, line, name, message, cause, h_loader, h_protection_domain);
 199 }
 200 
 201 void Exceptions::_throw_args(Thread* thread, const char* file, int line, Symbol* h_name, Symbol* h_signature, JavaCallArguments *args) {
 202   // Check for special boot-strapping/vm-thread handling
 203   if (special_exception(thread, file, line, h_name, NULL)) return;
 204   // Create and throw exception
 205   Handle h_loader(thread, NULL);
 206   Handle h_prot(thread, NULL);
 207   Handle h_cause(thread, NULL);
 208   Handle exception = new_exception(thread, h_name, h_signature, args, h_cause, h_loader, h_prot);
 209   _throw(thread, file, line, exception);
 210 }
 211 
 212 
 213 void Exceptions::throw_stack_overflow_exception(Thread* THREAD, const char* file, int line, methodHandle method) {
 214   Handle exception;
 215   if (!THREAD->has_pending_exception()) {
 216     klassOop k = SystemDictionary::StackOverflowError_klass();
 217     oop e = instanceKlass::cast(k)->allocate_instance(CHECK);
 218     exception = Handle(THREAD, e);  // fill_in_stack trace does gc
 219     assert(instanceKlass::cast(k)->is_initialized(), "need to increase min_stack_allowed calculation");
 220     if (StackTraceInThrowable) {
 221       java_lang_Throwable::fill_in_stack_trace(exception, method());
 222     }
 223   } else {
 224     // if prior exception, throw that one instead
 225     exception = Handle(THREAD, THREAD->pending_exception());
 226   }
 227   _throw(THREAD, file, line, exception);
 228 }
 229 
 230 void Exceptions::fthrow(Thread* thread, const char* file, int line, Symbol* h_name, const char* format, ...) {
 231   const int max_msg_size = 1024;
 232   va_list ap;
 233   va_start(ap, format);
 234   char msg[max_msg_size];
 235   vsnprintf(msg, max_msg_size, format, ap);
 236   msg[max_msg_size-1] = '\0';
 237   va_end(ap);
 238   _throw_msg(thread, file, line, h_name, msg);
 239 }
 240 
 241 // Creates an exception oop, calls the <init> method with the given signature.
 242 // and returns a Handle
 243 // Initializes the cause if cause non-null
 244 Handle Exceptions::new_exception(Thread *thread, Symbol* h_name,
 245                                  Symbol* signature,
 246                                  JavaCallArguments *args,
 247                                  Handle h_cause, Handle h_loader,
 248                                  Handle h_protection_domain) {
 249   assert(Universe::is_fully_initialized(),
 250     "cannot be called during initialization");
 251   assert(thread->is_Java_thread(), "can only be called by a Java thread");
 252   assert(!thread->has_pending_exception(), "already has exception");
 253 
 254   Handle h_exception;
 255 
 256   // Resolve exception klass
 257   klassOop ik = SystemDictionary::resolve_or_fail(h_name, h_loader, h_protection_domain, true, thread);
 258   instanceKlassHandle klass (thread, ik);
 259 
 260   if (!thread->has_pending_exception()) {
 261     assert(klass.not_null(), "klass must exist");
 262     // We are about to create an instance - so make sure that klass is initialized
 263     klass->initialize(thread);
 264     if (!thread->has_pending_exception()) {
 265       // Allocate new exception
 266       h_exception = klass->allocate_instance_handle(thread);
 267       if (!thread->has_pending_exception()) {
 268         JavaValue result(T_VOID);
 269         args->set_receiver(h_exception);
 270         // Call constructor
 271         JavaCalls::call_special(&result, klass,
 272                                          vmSymbols::object_initializer_name(),
 273                                          signature,
 274                                          args,
 275                                          thread);
 276 
 277       }
 278     }
 279 
 280     // Future: object initializer should take a cause argument
 281     if (h_cause() != NULL) {
 282       assert(h_cause->is_a(SystemDictionary::Throwable_klass()),
 283           "exception cause is not a subclass of java/lang/Throwable");
 284       JavaValue result1(T_OBJECT);
 285       JavaCallArguments args1;
 286       args1.set_receiver(h_exception);
 287       args1.push_oop(h_cause);
 288       JavaCalls::call_virtual(&result1, klass,
 289                                      vmSymbols::initCause_name(),
 290                                      vmSymbols::throwable_throwable_signature(),
 291                                      &args1,
 292                                      thread);
 293     }
 294   }
 295 
 296   // Check if another exception was thrown in the process, if so rethrow that one
 297   if (thread->has_pending_exception()) {
 298     h_exception = Handle(thread, thread->pending_exception());
 299     thread->clear_pending_exception();
 300   }
 301   return h_exception;
 302 }
 303 
 304 // Convenience method. Calls either the <init>() or <init>(String) method when
 305 // creating a new exception
 306 Handle Exceptions::new_exception(Thread* thread, Symbol* h_name,
 307                                  const char* message, Handle h_cause,
 308                                  Handle h_loader,
 309                                  Handle h_protection_domain,
 310                                  ExceptionMsgToUtf8Mode to_utf8_safe) {
 311   JavaCallArguments args;
 312   Symbol* signature = NULL;
 313   if (message == NULL) {
 314     signature = vmSymbols::void_method_signature();
 315   } else {
 316     // We want to allocate storage, but we can't do that if there's
 317     // a pending exception, so we preserve any pending exception
 318     // around the allocation.
 319     // If we get an exception from the allocation, prefer that to
 320     // the exception we are trying to build, or the pending exception.
 321     // This is sort of like what PRESERVE_EXCEPTION_MARK does, except
 322     // for the preferencing and the early returns.
 323     Handle incoming_exception (thread, NULL);
 324     if (thread->has_pending_exception()) {
 325       incoming_exception = Handle(thread, thread->pending_exception());
 326       thread->clear_pending_exception();
 327     }
 328     Handle msg;
 329     if (to_utf8_safe == safe_to_utf8) {
 330       // Make a java UTF8 string.
 331       msg = java_lang_String::create_from_str(message, thread);
 332     } else {
 333       // Make a java string keeping the encoding scheme of the original string.
 334       msg = java_lang_String::create_from_platform_dependent_str(message, thread);
 335     }
 336     if (thread->has_pending_exception()) {
 337       Handle exception(thread, thread->pending_exception());
 338       thread->clear_pending_exception();
 339       return exception;
 340     }
 341     if (incoming_exception.not_null()) {
 342       return incoming_exception;
 343     }
 344     args.push_oop(msg);
 345     signature = vmSymbols::string_void_signature();
 346   }
 347   return new_exception(thread, h_name, signature, &args, h_cause, h_loader, h_protection_domain);
 348 }
 349 
 350 // Another convenience method that creates handles for null class loaders and
 351 // protection domains and null causes.
 352 // If the last parameter 'to_utf8_mode' is safe_to_utf8,
 353 // it means we can safely ignore the encoding scheme of the message string and
 354 // convert it directly to a java UTF8 string. Otherwise, we need to take the
 355 // encoding scheme of the string into account. One thing we should do at some
 356 // point is to push this flag down to class java_lang_String since other
 357 // classes may need similar functionalities.
 358 Handle Exceptions::new_exception(Thread* thread,
 359                                  Symbol* name,
 360                                  const char* message,
 361                                  ExceptionMsgToUtf8Mode to_utf8_safe) {
 362 
 363   Handle       h_loader(thread, NULL);
 364   Handle       h_prot(thread, NULL);
 365   Handle       h_cause(thread, NULL);
 366   return Exceptions::new_exception(thread, name, message, h_cause, h_loader,
 367                                    h_prot, to_utf8_safe);
 368 }
 369 
 370 // Implementation of ExceptionMark
 371 
 372 ExceptionMark::ExceptionMark(Thread*& thread) {
 373   thread     = Thread::current();
 374   _thread    = thread;
 375   if (_thread->has_pending_exception()) {
 376     oop exception = _thread->pending_exception();
 377     _thread->clear_pending_exception(); // Needed to avoid infinite recursion
 378     exception->print();
 379     fatal("ExceptionMark constructor expects no pending exceptions");
 380   }
 381 }
 382 
 383 
 384 ExceptionMark::~ExceptionMark() {
 385   if (_thread->has_pending_exception()) {
 386     Handle exception(_thread, _thread->pending_exception());
 387     _thread->clear_pending_exception(); // Needed to avoid infinite recursion
 388     if (is_init_completed()) {
 389       exception->print();
 390       fatal("ExceptionMark destructor expects no pending exceptions");
 391     } else {
 392       vm_exit_during_initialization(exception);
 393     }
 394   }
 395 }
 396 
 397 // ----------------------------------------------------------------------------------------
 398 
 399 #ifndef PRODUCT
 400 // caller frees value_string if necessary
 401 void Exceptions::debug_check_abort(const char *value_string, const char* message) {
 402   if (AbortVMOnException != NULL && value_string != NULL &&
 403       strstr(value_string, AbortVMOnException)) {
 404     if (AbortVMOnExceptionMessage == NULL || message == NULL ||
 405         strcmp(message, AbortVMOnExceptionMessage) == 0) {
 406       fatal(err_msg("Saw %s, aborting", value_string));
 407     }
 408   }
 409 }
 410 
 411 void Exceptions::debug_check_abort(Handle exception, const char* message) {
 412   if (AbortVMOnException != NULL) {
 413     ResourceMark rm;
 414     if (message == NULL && exception->is_a(SystemDictionary::Throwable_klass())) {
 415       oop msg = java_lang_Throwable::message(exception);
 416       if (msg != NULL) {
 417         message = java_lang_String::as_utf8_string(msg);
 418       }
 419     }
 420     debug_check_abort(instanceKlass::cast(exception()->klass())->external_name(), message);
 421   }
 422 }
 423 #endif