e15a77a18c834c06bc8abceb34f00c5b962b86ff
[cacao.git] / src / vm / jit / trap.cpp
1 /* src/vm/jit/trap.cpp - hardware traps
2
3    Copyright (C) 2008, 2009
4    CACAOVM - Verein zur Foerderung der freien virtuellen Maschine CACAO
5    Copyright (C) 2009 Theobroma Systems Ltd.
6
7    This file is part of CACAO.
8
9    This program is free software; you can redistribute it and/or
10    modify it under the terms of the GNU General Public License as
11    published by the Free Software Foundation; either version 2, or (at
12    your option) any later version.
13
14    This program is distributed in the hope that it will be useful, but
15    WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17    General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22    02110-1301, USA.
23
24 */
25
26
27 #include "config.h"
28
29 #include <stdint.h>
30
31 /* Include machine dependent trap stuff. */
32
33 #include "md.h"
34 #include "md-trap.h"
35
36 #include "mm/memory.hpp"
37
38 #include "native/llni.h"
39
40 #include "toolbox/logging.hpp"
41
42 #include "vm/exceptions.hpp"
43 #include "vm/options.h"
44 #include "vm/os.hpp"
45 #include "vm/vm.hpp"
46
47 #include "vm/jit/asmpart.h"
48 #include "vm/jit/code.hpp"
49 #include "vm/jit/disass.h"
50 #include "vm/jit/executionstate.h"
51 #include "vm/jit/jit.hpp"
52 #include "vm/jit/methodtree.h"
53 #include "vm/jit/patcher-common.hpp"
54 #include "vm/jit/replace.hpp"
55 #include "vm/jit/stacktrace.hpp"
56 #include "vm/jit/trap.hpp"
57
58 #ifdef __cplusplus
59 extern "C" {
60 #endif
61
62 /**
63  * Mmap the first memory page to support hardware exceptions and check
64  * the maximum hardware trap displacement on the architectures where
65  * it is required (TRAP_INSTRUCTION_IS_LOAD defined to 1).
66  */
67 void trap_init(void)
68 {
69         TRACESUBSYSTEMINITIALIZATION("trap_init");
70
71         /* If requested we mmap a memory page at address 0x0,
72            so our hardware-exceptions work. */
73
74         if (opt_AlwaysMmapFirstPage) {
75                 int pagesize = os::getpagesize();
76                 (void) os::mmap_anonymous(NULL, pagesize, PROT_NONE, MAP_PRIVATE | MAP_FIXED);
77         }
78
79 #if !defined(TRAP_INSTRUCTION_IS_LOAD)
80 # error TRAP_INSTRUCTION_IS_LOAD is not defined in your md-trap.h
81 #endif
82
83 #if TRAP_INSTRUCTION_IS_LOAD == 1
84         /* Check if we get into trouble with our hardware-exceptions. */
85
86         if (TRAP_END > OFFSET(java_bytearray_t, data))
87                 vm_abort("trap_init: maximum hardware trap displacement is greater than the array-data offset: %d > %d", TRAP_END, OFFSET(java_bytearray_t, data));
88 #endif
89 }
90
91
92 /**
93  * Handles the signal which is generated by trap instructions, caught
94  * by a signal handler and calls the correct function.
95  *
96  * @param sig signal number
97  * @param xpc exception PC
98  * @param context pointer to OS dependent machine context
99  */
100 void trap_handle(int sig, void *xpc, void *context)
101 {
102         executionstate_t es;
103         stackframeinfo_t sfi;
104         trapinfo_t       trp;
105
106 #if !defined(NDEBUG)
107         // Sanity checking the XPC.
108         if (xpc == NULL)
109                 vm_abort("trap_handle: The program counter is NULL!");
110 #endif
111
112 #if defined(__ALPHA__) || defined(__ARM__) || defined(__I386__) || defined(__MIPS__) || defined(__POWERPC__) || defined(__POWERPC64__) || defined(__X86_64__)
113 # if !defined(NDEBUG)
114         /* Perform a sanity check on our execution state functions. */
115
116         executionstate_sanity_check(context);
117 # endif
118
119         /* Read execution state from current context. */
120
121         es.code = NULL;
122         md_executionstate_read(&es, context);
123
124 //# define TRAP_TRACE_VERBOSE
125 # if !defined(NDEBUG) && defined(TRAP_TRACE_VERBOSE)
126         /* Dump contents of execution state */
127
128         if (opt_TraceTraps) {
129                 log_println("[trap_handle: dumping execution state BEFORE ...]");
130                 executionstate_println(&es);
131         }
132 # endif
133 #endif
134
135         // Extract information from executionstate
136         void* pv = es.pv;  // Maybe null, resolved during stackframeinfo creation.
137         void* sp = es.sp;
138 #if defined(__I386__) || defined(__X86_64__)
139         void* ra = xpc;  // Return address is equal to XPC.
140 #else
141         void* ra = es.ra;  // This is correct for leafs.
142 #endif
143
144         // Decode machine-dependent trap instruction.
145         bool decode_result = md_trap_decode(&trp, sig, xpc, &es);
146
147         // Check if the trap instruction is valid and was decoded
148         // successfully.
149         if (!decode_result) {
150                 // Check if the PC has been patched during our way to this
151                 // trap handler (see PR85).
152                 // NOTE: Some archs use SIGILL for other traps too, but it's OK to
153                 // do this check anyway because it will fail.
154                 if (patcher_is_patched_at(xpc) == true) {
155                         if (opt_PrintWarnings)
156                                 log_println("trap_handle: Detected patcher race condition (PR85) at %p", xpc);
157                         return;
158                 }
159
160                 // We have a problem...
161                 vm_abort_disassemble(xpc, 1, "trap_handle: Unknown trap instruction at %p", xpc);
162         }
163
164         // For convenience only.
165         int      type = trp.type;
166         intptr_t val  = trp.value;
167
168         /* Do some preparations before we enter the nativeworld. */
169         /* BEFORE: creating stackframeinfo */
170
171         // Prevent compiler warnings.
172         int32_t        index = 0;
173         java_handle_t* o     = NULL;
174         methodinfo*    m     = NULL;
175
176         switch (type) {
177         case TRAP_ArrayIndexOutOfBoundsException:
178                 /* Get the index into the array causing the exception. */
179
180                 index = (int32_t) val;
181                 break;
182
183         case TRAP_ClassCastException:
184                 /* Wrap the value into a handle, as it is a reference. */
185
186                 o = LLNI_WRAP((java_object_t *) val);
187                 break;
188
189         case TRAP_COMPILER:
190                 /* We need to fixup the XPC, SP and RA here because they
191                    all might point into the compiler stub instead of the
192                    calling method. */
193
194                 MD_TRAP_COMPILER_FIXUP(xpc, ra, sp, pv);
195
196                 /* In this case the passed PV points to the compiler stub.  We
197                    get the methodinfo pointer here and set PV to NULL so
198                    stacktrace_stackframeinfo_add determines the PV for the
199                    parent Java method. */
200
201                 m  = code_get_methodinfo_for_pv(pv);
202                 pv = NULL;
203
204                 break;
205
206         default:
207                 /* do nothing */
208                 break;
209         }
210
211 #if !defined(NDEBUG)
212         // Trace this trap.
213         if (opt_TraceTraps)
214                 log_println("[trap_handle: sig=%d, type=%d, val=%p, pv=%p, sp=%p, ra=%p, xpc=%p]", sig, type, val, pv, sp, ra, xpc);
215 #endif
216
217 #if defined(ENABLE_VMLOG)
218         vmlog_cacao_signl_type(type);
219 #endif
220
221         /* Fill and add a stackframeinfo. */
222
223         stacktrace_stackframeinfo_add(&sfi, pv, sp, ra, xpc);
224
225         /* Get resulting exception (or pointer to compiled method). */
226
227         java_handle_t* p;
228         void*          entry;
229         bool           was_patched;
230 #if defined(ENABLE_REPLACEMENT)
231         bool           was_replaced;
232 #endif
233
234         switch (type) {
235         case TRAP_NullPointerException:
236                 p = exceptions_new_nullpointerexception();
237                 break;
238
239         case TRAP_ArithmeticException:
240                 p = exceptions_new_arithmeticexception();
241                 break;
242
243         case TRAP_ArrayIndexOutOfBoundsException:
244                 p = exceptions_new_arrayindexoutofboundsexception(index);
245                 break;
246
247         case TRAP_ArrayStoreException:
248                 p = exceptions_new_arraystoreexception();
249                 break;
250
251         case TRAP_ClassCastException:
252                 p = exceptions_new_classcastexception(o);
253                 break;
254
255         case TRAP_CHECK_EXCEPTION:
256                 p = exceptions_fillinstacktrace();
257                 break;
258
259         case TRAP_PATCHER:
260                 p = NULL;
261 #if defined(ENABLE_REPLACEMENT)
262                 was_replaced = replace_handler((uint8_t*) xpc, &es);
263                 if (was_replaced)
264                         break;
265 #endif
266                 was_patched = patcher_handler((uint8_t*) xpc);
267                 break;
268
269         case TRAP_COMPILER:
270                 p = NULL;
271                 entry = jit_compile_handle(m, sfi.pv, ra, (void*) val);
272                 break;
273
274 #if defined(__I386__) && defined(ENABLE_REPLACEMENT)
275 # warning Port the below stuff to use the patching subsystem.
276         case TRAP_COUNTDOWN:
277                 p = NULL;
278                 (void) replace_handler((uint8_t*) xpc - 13, &es);
279                 break;
280 #endif
281
282         default:
283                 /* Let's try to get a backtrace. */
284
285                 (void) methodtree_find(xpc);
286
287                 /* If that does not work, print more debug info. */
288
289                 vm_abort_disassemble(xpc, 1, "trap_handle: Unknown hardware exception type %d", type);
290
291                 /* keep compiler happy */
292
293                 p = NULL;
294         }
295
296         /* Remove stackframeinfo. */
297
298         stacktrace_stackframeinfo_remove(&sfi);
299
300 #if defined(__ALPHA__) || defined(__ARM__) || defined(__I386__) || defined(__MIPS__) || defined(__POWERPC__) || defined(__POWERPC64__) || defined(__X86_64__)
301         /* Update execution state and set registers. */
302         /* AFTER: removing stackframeinfo */
303
304         switch (type) {
305         case TRAP_COMPILER:
306                 // The normal case for a compiler trap is to jump directly to
307                 // the newly compiled method.
308
309                 if (entry != NULL) {
310                         es.pc = (uint8_t *) (uintptr_t) entry;
311                         es.pv = (uint8_t *) (uintptr_t) entry;
312                         break;
313                 }
314
315                 // In case of an exception during JIT compilation, we fetch
316                 // the exception here and proceed with exception handling.
317
318                 p = exceptions_get_and_clear_exception();
319                 assert(p != NULL);
320
321                 // Remove RA from stack on some archs.
322
323                 es.sp = (uint8_t*) sp;
324
325                 // Get and set the PV from the parent Java method.
326
327                 es.pv = (uint8_t*) md_codegen_get_pv_from_pc(ra);
328
329                 // Now fall-through to default exception handling.
330
331                 goto trap_handle_exception;
332
333         case TRAP_PATCHER:
334 #if defined(ENABLE_REPLACEMENT)
335                 // If on-stack-replacement suceeded, we are not allowed to touch
336                 // the execution state. We assume that there was no exception.
337
338                 if (was_replaced) {
339                         assert(exceptions_get_exception() == NULL);
340                         break;
341                 }
342 #endif
343
344                 // The normal case for a patcher trap is to continue execution at
345                 // the trap instruction. On some archs the PC may point after the
346                 // trap instruction, so we reset it here.
347
348                 if (was_patched) {
349                         assert(exceptions_get_exception() == NULL);
350                         es.pc = (uint8_t *) (uintptr_t) xpc;
351                         break;
352                 }
353
354                 // In case patching was not successful, we try to fetch the pending
355                 // exception here.
356
357                 p = exceptions_get_and_clear_exception();
358
359                 // If there is no pending exception, we continue execution behind
360                 // the position still in need of patching. Normally this would
361                 // indicate an error in the patching subsystem, but others might
362                 // want to piggyback patchers and we want to be able to provide
363                 // "reusable trap points" and avoid inifinite loops here. This is
364                 // especially useful to implement breakpoints or profiling points
365                 // of any kind. So before changing the trap logic, think about
366                 // utilizing the patching subsystem on your quest. :)
367
368                 if (p == NULL) {
369 #if !defined(NDEBUG)
370                         if (opt_PrintWarnings)
371                                 log_println("trap_handle: Detected reusable trap at %p", xpc);
372 #endif
373                         es.pc = (uint8_t *) (uintptr_t) xpc;
374                         es.pc += REPLACEMENT_PATCH_SIZE;
375                         break;
376                 }
377
378                 // Fall-through to default exception handling.
379
380         trap_handle_exception:
381         default:
382                 if (p != NULL) {
383 #if defined(__ALPHA__) || defined(__I386__) || defined(__X86_64__)
384                         // Perform stack unwinding for exceptions on execution state.
385                         es.pc = (uint8_t *) (uintptr_t) xpc;
386                         es.pv = (uint8_t *) (uintptr_t) sfi.pv;
387                         executionstate_unwind_exception(&es, p);
388
389                         // Pass the exception object to the exception handler.
390                         es.intregs[REG_ITMP1_XPTR] = (uintptr_t) LLNI_DIRECT(p);
391 #else
392                         es.intregs[REG_ITMP1_XPTR] = (uintptr_t) LLNI_DIRECT(p);
393                         es.intregs[REG_ITMP2_XPC]  = (uintptr_t) xpc;
394                         es.pc                      = (uint8_t *) (uintptr_t) asm_handle_exception;
395 #endif
396                 }
397         }
398
399         /* Write back execution state to current context. */
400
401         md_executionstate_write(&es, context);
402
403 # if !defined(NDEBUG) && defined(TRAP_TRACE_VERBOSE)
404         /* Dump contents of execution state */
405
406         if (opt_TraceTraps) {
407                 log_println("[trap_handle: dumping execution state AFTER ...]");
408                 executionstate_println(&es);
409         }
410 # endif
411 #endif
412 }
413
414 #ifdef __cplusplus
415 }
416 #endif
417
418
419 /*
420  * These are local overrides for various environment variables in Emacs.
421  * Please do not remove this and leave it at the end of the file, where
422  * Emacs will automagically detect them.
423  * ---------------------------------------------------------------------
424  * Local variables:
425  * mode: c++
426  * indent-tabs-mode: t
427  * c-basic-offset: 4
428  * tab-width: 4
429  * End:
430  * vim:noexpandtab:sw=4:ts=4:
431  */