Hotspot Native code异常的实现

最近看了Advanced Design and Implementation of Virtual Machines,里面说了Native code的异常是通过保存在线程里面的变量实现的,真正的异常实现源码今天才看,顺便记录下来。


异常实现的源码在/hotspot/src/share/vm/utilities/exceptions.hpp中,一段简介:

// This file provides the basic support for exception handling in the VM.
// Note: We do not use C++ exceptions to avoid compiler dependencies and
// unpredictable performance.
//
// Scheme: Exceptions are stored with the thread. There is never more
// than one pending exception per thread. All functions that can throw
// an exception carry a THREAD argument (usually the last argument and
// declared with the TRAPS macro). Throwing an exception means setting
// a pending exception in the thread. Upon return from a function that
// can throw an exception, we must check if an exception is pending.
// The CHECK macros do this in a convenient way. Carrying around the
// thread provides also convenient access to it (e.g. for Handle
// creation, w/o the need for recomputation).

不使用c++的异常机制是为了减少编译器的依赖和性能的考虑。异常被保存在线程的变量中,一个线程同时最多只能有一个异常。所有带有 THREAD 参数的函数都有可能抛异常, THREAD 是关于线程的宏,下面会讲到。抛出一个异常意味着把这个异常放到线程的变量中,在函数返回的时候我们可以通过 CHECK 宏检查有没有抛异常。


class ThreadShadow: public CHeapObj {
  friend class VMStructs;
  friend class JVMCIVMStructs;

 protected:
  oop  _pending_exception;                       // Thread has gc actions.
  const char* _exception_file;                   // file information for exception (debugging only)
  int         _exception_line;                   // line information for exception (debugging only)
  friend void check_ThreadShadow();              // checks _pending_exception offset

  // The following virtual exists only to force creation of a vtable.
  // We need ThreadShadow to have a vtable, even in product builds,
  // so that its layout will start at an offset of zero relative to Thread.
  // Some C++ compilers are so "clever" that they put the ThreadShadow
  // base class at offset 4 in Thread (after Thread's vtable), if they
  // notice that Thread has a vtable but ThreadShadow does not.
  virtual void unused_initial_virtual() { }

 public:
  oop  pending_exception() const                 { return _pending_exception; }
  bool has_pending_exception() const             { return _pending_exception != NULL; }
  const char* exception_file() const             { return _exception_file; }
  int  exception_line() const                    { return _exception_line; }

  // Code generation support
  static ByteSize pending_exception_offset()     { return byte_offset_of(ThreadShadow, _pending_exception); }

  // use THROW whenever possible!
  void set_pending_exception(oop exception, const char* file, int line);

  // use CLEAR_PENDING_EXCEPTION whenever possible!
  void clear_pending_exception();

  ThreadShadow() : _pending_exception(NULL),
                   _exception_file(NULL), _exception_line(0) {}
};

ThreadShadow 是 Thread 的父类,_pending_exception 保存了线程在运行过程中抛出的异常。


void ThreadShadow::set_pending_exception(oop exception, const char* file, int line) {
  assert(exception != NULL && exception->is_oop(), "invalid exception oop");
  _pending_exception = exception;
  _exception_file    = file;
  _exception_line    = line;
}

void ThreadShadow::clear_pending_exception() {
  if (_pending_exception != NULL && log_is_enabled(Debug, exceptions)) {
    ResourceMark rm;
    outputStream* logst = Log(exceptions)::debug_stream();
    logst->print("Thread::clear_pending_exception: cleared exception:");
    _pending_exception->print_on(logst);
  }
  _pending_exception = NULL;
  _exception_file    = NULL;
  _exception_line    = 0;
}

抛异常的时候会调用 set_pending_exception,Exceptions类提供了很多很方便抛异常的宏,比如:

#define THROW_HANDLE(e)  { Exceptions::_throw(THREAD_AND_LOCATION, e);                             return;  }

去掉无用代码后,可以看到 _throw 对当前线程设置了异常
void Exceptions::_throw(Thread* thread, const char* file, int line, Handle h_exception, const char* message) {
  // Check for special boot-strapping/vm-thread handling
  if (special_exception(thread, file, line, h_exception)) {
    return;
  }

  if (h_exception->is_a(SystemDictionary::OutOfMemoryError_klass())) {
    count_out_of_memory_exceptions(h_exception);
  }
  // set the pending exception
  thread->set_pending_exception(h_exception(), file, line);
}

Hotspot也提供了很多有用的宏帮助我们使用这些异常,比如:

// The THREAD & TRAPS macros facilitate the declaration of functions that throw exceptions.
// Convention: Use the TRAPS macro as the last argument of such a function; e.g.:
//
// int this_function_may_trap(int x, float y, TRAPS)
可以使用 TRAPS 宏来帮助我们友好的抛异常,使用 CHECK 宏来帮助我们检查异常。
#define THREAD __the_thread__
#define TRAPS  Thread* THREAD

#define PENDING_EXCEPTION                        (((ThreadShadow*)THREAD)->pending_exception())
#define HAS_PENDING_EXCEPTION                    (((ThreadShadow*)THREAD)->has_pending_exception())
#define CLEAR_PENDING_EXCEPTION                  (((ThreadShadow*)THREAD)->clear_pending_exception())

#define CHECK                                    THREAD); if (HAS_PENDING_EXCEPTION) return       ; (void)(0
#define CHECK_(result)                           THREAD); if (HAS_PENDING_EXCEPTION) return result; (void)(0
#define CHECK_0                                  CHECK_(0)
#define CHECK_NH                                 CHECK_(Handle())
#define CHECK_NULL                               CHECK_(NULL)
#define CHECK_false                              CHECK_(false)
#define CHECK_JNI_ERR                            CHECK_(JNI_ERR)

#define CHECK_AND_CLEAR                         THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_EXCEPTION; return;        } (void)(0
#define CHECK_AND_CLEAR_(result)                THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_EXCEPTION; return result; } (void)(0
#define CHECK_AND_CLEAR_0                       CHECK_AND_CLEAR_(0)
#define CHECK_AND_CLEAR_NH                      CHECK_AND_CLEAR_(Handle())
#define CHECK_AND_CLEAR_NULL                    CHECK_AND_CLEAR_(NULL)
#define CHECK_AND_CLEAR_false                   CHECK_AND_CLEAR_(false)

举个例子:

int result = this_function_may_trap(x_arg, y_arg, CHECK_0);

把CHECK_0 替换为 CHECK_(0) 后展开:

int result = this_function_may_trap(x_arg, y_arg, THREAD);
 if (HAS_PENDING_EXCEPTION) return 0; (void)(0);

可以很清楚的看到如果有异常不会执行接下来的代码,而是返回0。


以上就是整个 Native code 异常的实现,异常不会抛出而是存在线程的变量中,在调用方法的时候去检查这个变量,保证了整个异常机制的正常运作。

你可能感兴趣的:(Hotspot Native code异常的实现)