1 /*
  2  * Copyright (c) 1998, 2026, 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 #ifndef SHARE_UTILITIES_EXCEPTIONS_HPP
 26 #define SHARE_UTILITIES_EXCEPTIONS_HPP
 27 
 28 #include "memory/allocation.hpp"
 29 #include "oops/oopsHierarchy.hpp"
 30 #include "runtime/atomic.hpp"
 31 #include "utilities/ostream.hpp"
 32 #include "utilities/sizes.hpp"
 33 
 34 // This file provides the basic support for exception handling in the VM.
 35 // Note: We do not use C++ exceptions to avoid compiler dependencies and
 36 // unpredictable performance.
 37 //
 38 // Scheme: Exceptions are stored with the thread. There is never more
 39 // than one pending exception per thread. All functions that can throw
 40 // an exception carry a THREAD argument (usually the last argument and
 41 // declared with the TRAPS macro). Throwing an exception means setting
 42 // a pending exception in the thread. Upon return from a function that
 43 // can throw an exception, we must check if an exception is pending.
 44 // The CHECK macros do this in a convenient way. Carrying around the
 45 // thread provides also convenient access to it (e.g. for Handle
 46 // creation, w/o the need for recomputation).
 47 
 48 
 49 
 50 // Forward declarations to be independent of the include structure.
 51 
 52 class JavaThread;
 53 class Handle;
 54 class Symbol;
 55 class JavaCallArguments;
 56 class methodHandle;
 57 
 58 // The ThreadShadow class is a helper class to access the _pending_exception
 59 // field of the Thread class w/o having access to the Thread's interface (for
 60 // include hierarchy reasons).
 61 
 62 class ThreadShadow: public CHeapObj<mtThread> {
 63   friend class VMStructs;
 64 
 65  protected:
 66   oop  _pending_exception;                       // Thread has gc actions.
 67   const char* _exception_file;                   // file information for exception (debugging only)
 68   int         _exception_line;                   // line information for exception (debugging only)
 69   friend void check_ThreadShadow();              // checks _pending_exception offset
 70 
 71   // The following virtual exists only to force creation of a vtable.
 72   // We need ThreadShadow to have a vtable, even in product builds,
 73   // so that its layout will start at an offset of zero relative to Thread.
 74   // Some C++ compilers are so "clever" that they put the ThreadShadow
 75   // base class at offset 4 in Thread (after Thread's vtable), if they
 76   // notice that Thread has a vtable but ThreadShadow does not.
 77   virtual void unused_initial_virtual() { }
 78 
 79  public:
 80   oop  pending_exception() const                 { return _pending_exception; }
 81   bool has_pending_exception() const             { return _pending_exception != nullptr; }
 82   const char* exception_file() const             { return _exception_file; }
 83   int  exception_line() const                    { return _exception_line; }
 84 
 85   // Code generation support
 86   static ByteSize pending_exception_offset()     { return byte_offset_of(ThreadShadow, _pending_exception); }
 87 
 88   // use THROW whenever possible!
 89   void set_pending_exception(oop exception, const char* file, int line);
 90 
 91   // use CLEAR_PENDING_EXCEPTION whenever possible!
 92   void clear_pending_exception();
 93 
 94   // use CLEAR_PENDING_NONASYNC_EXCEPTION to clear probable nonasync exception.
 95   void clear_pending_nonasync_exception();
 96 
 97   void set_pending_preempted_exception();
 98   void clear_pending_preempted_exception();
 99   void check_preempted_exception() NOT_DEBUG_RETURN;
100 
101   ThreadShadow() : _pending_exception(nullptr),
102                    _exception_file(nullptr), _exception_line(0) {}
103 };
104 
105 
106 // Exceptions is a helper class that encapsulates all operations
107 // that require access to the thread interface and which are
108 // relatively rare. The Exceptions operations should only be
109 // used directly if the macros below are insufficient.
110 
111 class Exceptions {
112   // Either `exception` or `symbol` must be non-null but not both.
113   static bool special_exception(JavaThread* thread, const char* file, int line, Handle exception, Symbol* name = nullptr, const char* message = nullptr);
114 
115   // Count out of memory errors that are interesting in error diagnosis
116   static Atomic<int> _out_of_memory_error_java_heap_errors;
117   static Atomic<int> _out_of_memory_error_metaspace_errors;
118   static Atomic<int> _out_of_memory_error_class_metaspace_errors;
119 
120   // Count linkage errors
121   static Atomic<int> _linkage_errors;
122 
123   // Count stack overflow errors.
124   static Atomic<int> _stack_overflow_errors;
125 
126  public:
127   // this enum is defined to indicate whether it is safe to
128   // ignore the encoding scheme of the original message string.
129   typedef enum {
130     safe_to_utf8 = 0,
131     unsafe_to_utf8 = 1
132   } ExceptionMsgToUtf8Mode;
133   // Throw exceptions: w/o message, w/ message & with formatted message.
134   static void _throw_oop(JavaThread* thread, const char* file, int line, oop exception);
135   static void _throw(JavaThread* thread, const char* file, int line, Handle exception, const char* msg = nullptr);
136 
137   static void _throw_msg(JavaThread* thread, const char* file, int line, Symbol* name, const char* message);
138   static void _throw_msg(JavaThread* thread, const char* file, int line, Symbol* name, const char* message,
139                          Handle loader);
140 
141   static void _throw_msg_cause(JavaThread* thread, const char* file, int line, Symbol* name, const char* message, Handle h_cause);
142   static void _throw_msg_cause(JavaThread* thread, const char* file, int line, Symbol* name, const char* message, Handle h_cause,
143                                Handle h_loader);
144 
145   static void _throw_cause(JavaThread* thread, const char* file, int line, Symbol* name, Handle h_cause);
146   static void _throw_cause(JavaThread* thread, const char* file, int line, Symbol* name, Handle h_cause,
147                            Handle h_loader);
148 
149   static void _throw_args(JavaThread* thread, const char* file, int line,
150                           Symbol* name, Symbol* signature,
151                           JavaCallArguments* args);
152 
153   // There is no THROW... macro for this method. Caller should remember
154   // to do a return after calling it.
155   static void fthrow(JavaThread* thread, const char* file, int line, Symbol* name,
156                      const char* format, ...) ATTRIBUTE_PRINTF(5, 6);
157 
158   // Create and initialize a new exception
159   static Handle new_exception(JavaThread* thread, Symbol* name,
160                               Symbol* signature, JavaCallArguments* args,
161                               Handle loader);
162 
163   static Handle new_exception(JavaThread* thread, Symbol* name,
164                               Symbol* signature, JavaCallArguments* args,
165                               Handle cause,
166                               Handle loader);
167 
168   static Handle new_exception(JavaThread* thread, Symbol* name,
169                               Handle cause,
170                               Handle loader,
171                               ExceptionMsgToUtf8Mode to_utf8_safe = safe_to_utf8);
172 
173   static Handle new_exception(JavaThread* thread, Symbol* name,
174                               const char* message, Handle cause,
175                               Handle loader,
176                               ExceptionMsgToUtf8Mode to_utf8_safe = safe_to_utf8);
177 
178   static Handle new_exception(JavaThread* thread, Symbol* name,
179                               const char* message,
180                               ExceptionMsgToUtf8Mode to_utf8_safe = safe_to_utf8);
181 
182   static void throw_stack_overflow_exception(JavaThread* thread, const char* file, int line, const methodHandle& method);
183 
184   static void wrap_dynamic_exception(bool is_indy, JavaThread* thread);
185 
186   // Exception counting of interesting exceptions that may have caused a
187   // problem for the JVM, for reporting in the hs_err file.
188   static void increment_stack_overflow_errors();
189   static bool has_exception_counts();
190   static void count_out_of_memory_exceptions(Handle exception);
191   static void print_exception_counts_on_error(outputStream* st);
192 
193   // for AbortVMOnException flag
194   static void debug_check_abort(Handle exception, const char* message = nullptr);
195   static void debug_check_abort_helper(Handle exception, const char* message = nullptr);
196   static void debug_check_abort(const char *value_string, const char* message = nullptr);
197 
198   // for logging exceptions
199   static void log_exception(Handle exception, const char* message);
200   static void log_exception_stacktrace(Handle exception);
201   static void log_exception_stacktrace(Handle exception, methodHandle method, int bci);
202 };
203 
204 
205 // The THREAD & TRAPS macros facilitate the declaration of functions that throw exceptions.
206 // Convention: Use the TRAPS macro as the last argument of such a function; e.g.:
207 //
208 // int this_function_may_trap(int x, float y, TRAPS)
209 
210 #define THREAD __the_thread__
211 #define TRAPS  JavaThread* THREAD
212 
213 
214 // The CHECK... macros should be used to pass along a THREAD reference and to check for pending
215 // exceptions. In special situations it is necessary to handle pending exceptions explicitly,
216 // in these cases the PENDING_EXCEPTION helper macros should be used.
217 //
218 // Macro naming conventions: Macros that end with _ require a result value to be returned. They
219 // are for functions with non-void result type. The result value is usually ignored because of
220 // the exception and is only needed for syntactic correctness. The _0 ending is a shortcut for
221 // _(0) since this is a frequent case. Example:
222 //
223 // int result = this_function_may_trap(x_arg, y_arg, CHECK_0);
224 //
225 // CAUTION: make sure that the function call using a CHECK macro is not the only statement of a
226 // conditional branch w/o enclosing {} braces, since the CHECK macros expand into several state-
227 // ments! Also make sure it is not used on a function call that is part of a return statement!
228 
229 #define PENDING_EXCEPTION                        (((ThreadShadow*)THREAD)->pending_exception())
230 #define HAS_PENDING_EXCEPTION                    (((ThreadShadow*)THREAD)->has_pending_exception())
231 #define CLEAR_PENDING_EXCEPTION                  (((ThreadShadow*)THREAD)->clear_pending_exception())
232 
233 #define CHECK                                    THREAD); if (HAS_PENDING_EXCEPTION) return       ; (void)(0
234 #define CHECK_(result)                           THREAD); if (HAS_PENDING_EXCEPTION) return result; (void)(0
235 #define CHECK_0                                  CHECK_(0)
236 #define CHECK_NH                                 CHECK_(Handle())
237 #define CHECK_NULL                               CHECK_(nullptr)
238 #define CHECK_false                              CHECK_(false)
239 #define CHECK_JNI_ERR                            CHECK_(JNI_ERR)
240 #define CHECK_PREEMPTABLE                        THREAD); if (HAS_PENDING_EXCEPTION) { THREAD->check_preempted_exception(); return;       } (void)(0
241 #define CHECK_PREEMPTABLE_false                  THREAD); if (HAS_PENDING_EXCEPTION) { THREAD->check_preempted_exception(); return false; } (void)(0
242 
243 // CAUTION: These macros clears all exceptions including async exceptions, use it with caution.
244 #define CHECK_AND_CLEAR                         THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_EXCEPTION; return;        } (void)(0
245 #define CHECK_AND_CLEAR_(result)                THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_EXCEPTION; return result; } (void)(0
246 #define CHECK_AND_CLEAR_0                       CHECK_AND_CLEAR_(0)
247 #define CHECK_AND_CLEAR_NH                      CHECK_AND_CLEAR_(Handle())
248 #define CHECK_AND_CLEAR_NULL                    CHECK_AND_CLEAR_(nullptr)
249 #define CHECK_AND_CLEAR_false                   CHECK_AND_CLEAR_(false)
250 
251 // CAUTION: These macros clears all exceptions except probable async exceptions j.l.InternalError.
252 // So use it with caution.
253 #define CLEAR_PENDING_NONASYNC_EXCEPTION        (((ThreadShadow*)THREAD)->clear_pending_nonasync_exception())
254 #define CHECK_AND_CLEAR_NONASYNC                THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_NONASYNC_EXCEPTION; return; } (void)(0
255 #define CHECK_AND_CLEAR_NONASYNC_(result)       THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_NONASYNC_EXCEPTION; return result; } (void)(0
256 #define CHECK_AND_CLEAR_NONASYNC_0              CHECK_AND_CLEAR_NONASYNC_(0)
257 #define CHECK_AND_CLEAR_NONASYNC_NH             CHECK_AND_CLEAR_NONASYNC_(Handle())
258 #define CHECK_AND_CLEAR_NONASYNC_NULL           CHECK_AND_CLEAR_NONASYNC_(nullptr)
259 #define CHECK_AND_CLEAR_NONASYNC_false          CHECK_AND_CLEAR_NONASYNC_(false)
260 
261 #define CLEAR_PENDING_PREEMPTED_EXCEPTION       (((ThreadShadow*)THREAD)->clear_pending_preempted_exception())
262 #define CHECK_AND_CLEAR_PREEMPTED               THREAD); if (HAS_PENDING_EXCEPTION) { CLEAR_PENDING_PREEMPTED_EXCEPTION; return; } (void)(0
263 
264 
265 // The THROW... macros should be used to throw an exception. They require a THREAD variable to be
266 // visible within the scope containing the THROW. Usually this is achieved by declaring the function
267 // with a TRAPS argument.
268 
269 #define THREAD_AND_LOCATION                      THREAD, __FILE__, __LINE__
270 
271 #define THROW_OOP(e)                                \
272   { Exceptions::_throw_oop(THREAD_AND_LOCATION, e);                             return;  }
273 
274 #define THROW_HANDLE(e)                                \
275   { Exceptions::_throw(THREAD_AND_LOCATION, e);                             return;  }
276 
277 #define THROW(name)                                 \
278   { Exceptions::_throw_msg(THREAD_AND_LOCATION, name, nullptr); return;  }
279 
280 #define THROW_MSG(name, message)                    \
281   { Exceptions::_throw_msg(THREAD_AND_LOCATION, name, message); return;  }
282 
283 #define THROW_CAUSE(name, cause)   \
284   { Exceptions::_throw_cause(THREAD_AND_LOCATION, name, cause); return; }
285 
286 #define THROW_MSG_LOADER(name, message, loader) \
287   { Exceptions::_throw_msg(THREAD_AND_LOCATION, name, message, loader); return;  }
288 
289 #define THROW_ARG(name, signature, args) \
290   { Exceptions::_throw_args(THREAD_AND_LOCATION, name, signature, args);   return; }
291 
292 #define THROW_OOP_(e, result)                       \
293   { Exceptions::_throw_oop(THREAD_AND_LOCATION, e);                           return result; }
294 
295 #define THROW_HANDLE_(e, result)                       \
296   { Exceptions::_throw(THREAD_AND_LOCATION, e);                           return result; }
297 
298 #define THROW_(name, result)                        \
299   { Exceptions::_throw_msg(THREAD_AND_LOCATION, name, nullptr); return result; }
300 
301 #define THROW_MSG_(name, message, result)           \
302   { Exceptions::_throw_msg(THREAD_AND_LOCATION, name, message); return result; }
303 
304 #define THROW_MSG_LOADER_(name, message, loader, result) \
305   { Exceptions::_throw_msg(THREAD_AND_LOCATION, name, message, loader); return result; }
306 
307 #define THROW_ARG_(name, signature, args, result) \
308   { Exceptions::_throw_args(THREAD_AND_LOCATION, name, signature, args); return result; }
309 
310 #define THROW_MSG_CAUSE(name, message, cause)   \
311   { Exceptions::_throw_msg_cause(THREAD_AND_LOCATION, name, message, cause); return; }
312 
313 #define THROW_MSG_CAUSE_(name, message, cause, result)   \
314   { Exceptions::_throw_msg_cause(THREAD_AND_LOCATION, name, message, cause); return result; }
315 
316 
317 #define THROW_OOP_0(e)                      THROW_OOP_(e, 0)
318 #define THROW_HANDLE_0(e)                   THROW_HANDLE_(e, 0)
319 #define THROW_0(name)                       THROW_(name, 0)
320 #define THROW_MSG_0(name, message)          THROW_MSG_(name, message, 0)
321 #define THROW_WRAPPED_0(name, oop_to_wrap)  THROW_WRAPPED_(name, oop_to_wrap, 0)
322 #define THROW_ARG_0(name, signature, arg)   THROW_ARG_(name, signature, arg, 0)
323 #define THROW_MSG_CAUSE_0(name, message, cause) THROW_MSG_CAUSE_(name, message, cause, 0)
324 #define THROW_MSG_CAUSE_NULL(name, message, cause) THROW_MSG_CAUSE_(name, message, cause, nullptr)
325 
326 #define THROW_NULL(name)                    THROW_(name, nullptr)
327 #define THROW_MSG_NULL(name, message)       THROW_MSG_(name, message, nullptr)
328 
329 #define THROW_HANDLE_NULL(e)                THROW_HANDLE_(e, nullptr)
330 #define THROW_ARG_NULL(name, signature, arg) THROW_ARG_(name, signature, arg, nullptr)
331 
332 // The CATCH macro checks that no exception has been thrown by a function; it is used at
333 // call sites about which is statically known that the callee cannot throw an exception
334 // even though it is declared with TRAPS.
335 
336 #define CATCH                              \
337   THREAD); if (HAS_PENDING_EXCEPTION) {    \
338     oop ex = PENDING_EXCEPTION;            \
339     CLEAR_PENDING_EXCEPTION;               \
340     DEBUG_ONLY(ex->print();)               \
341     assert(false, "CATCH");                \
342   } (void)(0
343 
344 // ExceptionMark is a stack-allocated helper class for local exception handling.
345 // It is used with the EXCEPTION_MARK macro.
346 
347 class ExceptionMark {
348  private:
349   JavaThread* _thread;
350   inline void check_no_pending_exception();
351 
352  public:
353   ExceptionMark();
354   ExceptionMark(JavaThread* thread);
355   ~ExceptionMark();
356 
357   JavaThread* thread() {
358     return _thread;
359   }
360 };
361 
362 // Use an EXCEPTION_MARK for 'local' exceptions. EXCEPTION_MARK makes sure that no
363 // pending exception exists upon entering its scope and tests that no pending exception
364 // exists when leaving the scope.
365 
366 // See also preserveException.hpp for PreserveExceptionMark
367 // which preserves pre-existing exceptions and does not allow new
368 // exceptions.
369 
370 #define EXCEPTION_MARK                           ExceptionMark __em; JavaThread* THREAD = __em.thread();
371 
372 #endif // SHARE_UTILITIES_EXCEPTIONS_HPP