Merged with new-trap-decoding branch at rev a792088a3f04 (branch closed).
[cacao.git] / src / vm / jit / trap.cpp
1 /* src/vm/jit/trap.cpp - hardware traps
2
3    Copyright (C) 2008
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 #if !(defined(__ARM__) && defined(__LINUX__))
70         /* On arm-linux the first memory page can't be mmap'ed, as it
71            contains the exception vectors. */
72
73         int pagesize;
74
75         /* mmap a memory page at address 0x0, so our hardware-exceptions
76            work. */
77
78         pagesize = os::getpagesize();
79
80         (void) os::mmap_anonymous(NULL, pagesize, PROT_NONE, MAP_PRIVATE | MAP_FIXED);
81 #endif
82
83         TRACESUBSYSTEMINITIALIZATION("trap_init");
84
85 #if !defined(TRAP_INSTRUCTION_IS_LOAD)
86 # error TRAP_INSTRUCTION_IS_LOAD is not defined in your md-trap.h
87 #endif
88
89 #if TRAP_INSTRUCTION_IS_LOAD == 1
90         /* Check if we get into trouble with our hardware-exceptions. */
91
92         if (TRAP_END > OFFSET(java_bytearray_t, data))
93                 vm_abort("trap_init: maximum hardware trap displacement is greater than the array-data offset: %d > %d", TRAP_END, OFFSET(java_bytearray_t, data));
94 #endif
95 }
96
97
98 /**
99  * Handles the signal which is generated by trap instructions, caught
100  * by a signal handler and calls the correct function.
101  *
102  * @param sig signal number
103  * @param xpc exception PC
104  * @param context pointer to OS dependent machine context
105  */
106 void trap_handle(int sig, void *xpc, void *context)
107 {
108         executionstate_t es;
109         stackframeinfo_t sfi;
110         trapinfo_t       trp;
111
112         // Prevent compiler warnings.
113         java_handle_t* o = NULL;
114         methodinfo*    m = NULL;
115
116 #if !defined(NDEBUG)
117         // Sanity checking the XPC.
118         if (xpc == NULL)
119                 vm_abort("trap_handle: The program counter is NULL!");
120 #endif
121
122 #if defined(__ALPHA__) || defined(__ARM__) || defined(__I386__) || defined(__POWERPC__) || defined(__POWERPC64__) || defined(__X86_64__)
123 # if !defined(NDEBUG)
124         /* Perform a sanity check on our execution state functions. */
125
126         executionstate_sanity_check(context);
127 # endif
128
129         /* Read execution state from current context. */
130
131         es.code = NULL;
132         md_executionstate_read(&es, context);
133
134 //# define TRAP_TRACE_VERBOSE
135 # if !defined(NDEBUG) && defined(TRAP_TRACE_VERBOSE)
136         /* Dump contents of execution state */
137
138         if (opt_TraceTraps) {
139                 log_println("[trap_handle: dumping execution state BEFORE ...]");
140                 executionstate_println(&es);
141         }
142 # endif
143 #endif
144
145         // Extract information from executionstate
146         void* pv = es.pv;  // Maybe null, resolved during stackframeinfo creation.
147         void* sp = es.sp;
148 #if defined(__I386__) || defined(__X86_64__)
149         void* ra = xpc;  // Return address is equal to XPC.
150 #else
151         void* ra = es.ra;  // This is correct for leafs.
152 #endif
153
154         // Decode machine-dependent trap instruction.
155         bool decode_result = md_trap_decode(&trp, sig, xpc, &es);
156
157         // Check if the trap instruction is valid and was decoded
158         // successfully.
159         if (!decode_result) {
160                 // Check if the PC has been patched during our way to this
161                 // trap handler (see PR85).
162                 // NOTE: Some archs use SIGILL for other traps too, but it's OK to
163                 // do this check anyway because it will fail.
164                 if (patcher_is_patched_at(xpc) == true) {
165                         // XXX remove this debug output!
166                         log_println("trap_handle: Detected patcher race condition (PR85) at %p", xpc);
167                         return;
168                 }
169
170                 // We have a problem...
171                 vm_abort_disassemble(xpc, 1, "trap_handle: Unknown trap instruction at %p", xpc);
172         }
173
174         // For convenience only.
175         int      type = trp.type;
176         intptr_t val  = trp.value;
177
178         /* Do some preparations before we enter the nativeworld. */
179         /* BEFORE: creating stackframeinfo */
180
181         switch (type) {
182         case TRAP_ClassCastException:
183                 /* Wrap the value into a handle, as it is a reference. */
184
185                 o = LLNI_WRAP((java_object_t *) val);
186                 break;
187
188         case TRAP_COMPILER:
189                 /* We need to fixup the XPC, SP and RA here because they
190                    all might point into the compiler stub instead of the
191                    calling method. */
192
193                 MD_TRAP_COMPILER_FIXUP(xpc, ra, sp, pv);
194
195                 /* In this case the passed PV points to the compiler stub.  We
196                    get the methodinfo pointer here and set PV to NULL so
197                    stacktrace_stackframeinfo_add determines the PV for the
198                    parent Java method. */
199
200                 m  = code_get_methodinfo_for_pv(pv);
201                 pv = NULL;
202
203                 break;
204
205         default:
206                 /* do nothing */
207                 break;
208         }
209
210 #if !defined(NDEBUG)
211         // Trace this trap.
212         if (opt_TraceTraps)
213                 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);
214 #endif
215
216 #if defined(ENABLE_VMLOG)
217         vmlog_cacao_signl_type(type);
218 #endif
219
220         /* Fill and add a stackframeinfo. */
221
222         stacktrace_stackframeinfo_add(&sfi, pv, sp, ra, xpc);
223
224         /* Get resulting exception (or pointer to compiled method). */
225
226         int32_t        index;
227         java_handle_t* p;
228         void*          entry;
229
230         switch (type) {
231         case TRAP_NullPointerException:
232                 p = exceptions_new_nullpointerexception();
233                 break;
234
235         case TRAP_ArithmeticException:
236                 p = exceptions_new_arithmeticexception();
237                 break;
238
239         case TRAP_ArrayIndexOutOfBoundsException:
240                 index = (int32_t) val;
241                 p = exceptions_new_arrayindexoutofboundsexception(index);
242                 break;
243
244         case TRAP_ArrayStoreException:
245                 p = exceptions_new_arraystoreexception();
246                 break;
247
248         case TRAP_ClassCastException:
249                 p = exceptions_new_classcastexception(o);
250                 break;
251
252         case TRAP_CHECK_EXCEPTION:
253                 p = exceptions_fillinstacktrace();
254                 break;
255
256         case TRAP_PATCHER:
257 #if defined(ENABLE_REPLACEMENT)
258                 if (replace_me_wrapper((uint8_t*) xpc, context)) {
259                         p = NULL;
260                         break;
261                 }
262 #endif
263                 p = patcher_handler((uint8_t*) xpc);
264                 break;
265
266         case TRAP_COMPILER:
267                 entry = jit_compile_handle(m, sfi.pv, ra, (void*) val);
268                 p = NULL;
269                 break;
270
271 #if defined(ENABLE_REPLACEMENT)
272         case TRAP_COUNTDOWN:
273 # if defined(__I386__)
274                 replace_me_wrapper((uint8_t*) xpc - 13, context);
275 # endif
276                 p = NULL;
277                 break;
278 #endif
279
280         default:
281                 /* Let's try to get a backtrace. */
282
283                 (void) methodtree_find(xpc);
284
285                 /* If that does not work, print more debug info. */
286
287                 vm_abort_disassemble(xpc, 1, "trap_handle: Unknown hardware exception type %d", type);
288
289                 /* keep compiler happy */
290
291                 p = NULL;
292         }
293
294         /* Remove stackframeinfo. */
295
296         stacktrace_stackframeinfo_remove(&sfi);
297
298 #if defined(__ALPHA__) || defined(__ARM__) || defined(__I386__) || defined(__POWERPC__) || defined(__POWERPC64__) || defined(__X86_64__)
299         /* Update execution state and set registers. */
300         /* AFTER: removing stackframeinfo */
301
302         switch (type) {
303         case TRAP_COMPILER:
304                 // The normal case for a compiler trap is to jump directly to
305                 // the newly compiled method.
306
307                 if (entry != NULL) {
308                         es.pc = (uint8_t *) (uintptr_t) entry;
309                         es.pv = (uint8_t *) (uintptr_t) entry;
310                         break;
311                 }
312
313                 // In case of an exception during JIT compilation, we fetch
314                 // the exception here and proceed with exception handling.
315
316                 p = exceptions_get_and_clear_exception();
317                 assert(p != NULL);
318
319                 // Remove RA from stack on some archs.
320
321                 es.sp = (uint8_t*) sp;
322
323                 // Get and set the PV from the parent Java method.
324
325                 es.pv = (uint8_t*) md_codegen_get_pv_from_pc(ra);
326
327                 // Now fall-through to default exception handling.
328
329                 goto trap_handle_exception;
330
331         case TRAP_PATCHER:
332                 // The normal case for a patcher trap is to continue execution at
333                 // the trap instruction. On some archs the PC may point after the
334                 // trap instruction, so we reset it here.
335
336                 if (p == NULL) {
337                         es.pc = (uint8_t *) (uintptr_t) xpc;
338                         break;
339                 }
340
341                 // Fall-through to default exception handling.
342
343         trap_handle_exception:
344         default:
345                 if (p != NULL) {
346                         es.intregs[REG_ITMP1_XPTR] = (uintptr_t) LLNI_DIRECT(p);
347                         es.intregs[REG_ITMP2_XPC]  = (uintptr_t) xpc;
348                         es.pc                      = (uint8_t *) (uintptr_t) asm_handle_exception;
349                 }
350         }
351
352         /* Write back execution state to current context. */
353
354         md_executionstate_write(&es, context);
355
356 # if !defined(NDEBUG) && defined(TRAP_TRACE_VERBOSE)
357         /* Dump contents of execution state */
358
359         if (opt_TraceTraps) {
360                 log_println("[trap_handle: dumping execution state AFTER ...]");
361                 executionstate_println(&es);
362         }
363 # endif
364 #endif
365 }
366
367 #ifdef __cplusplus
368 }
369 #endif
370
371
372 /*
373  * These are local overrides for various environment variables in Emacs.
374  * Please do not remove this and leave it at the end of the file, where
375  * Emacs will automagically detect them.
376  * ---------------------------------------------------------------------
377  * Local variables:
378  * mode: c++
379  * indent-tabs-mode: t
380  * c-basic-offset: 4
381  * tab-width: 4
382  * End:
383  */