* src/vm/jit/trap.cpp: Finally switched s390 to the new trap decoding method.
[cacao.git] / src / vm / jit / trap.cpp
1 /* src/vm/jit/trap.cpp - hardware traps
2
3    Copyright (C) 2008, 2009, 2010
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 #if defined(__S390__)
59 #include "vm/jit/s390/codegen.h"
60 #else
61 #define N_PV_OFFSET 0
62 #endif
63
64 #ifdef __cplusplus
65 extern "C" {
66 #endif
67
68 /**
69  * Mmap the first memory page to support hardware exceptions and check
70  * the maximum hardware trap displacement on the architectures where
71  * it is required (TRAP_INSTRUCTION_IS_LOAD defined to 1).
72  */
73 void trap_init(void)
74 {
75         TRACESUBSYSTEMINITIALIZATION("trap_init");
76
77         /* If requested we mmap a memory page at address 0x0,
78            so our hardware-exceptions work. */
79
80         if (opt_AlwaysMmapFirstPage) {
81                 int pagesize = os::getpagesize();
82                 (void) os::mmap_anonymous(NULL, pagesize, PROT_NONE, MAP_PRIVATE | MAP_FIXED);
83         }
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 #if !defined(NDEBUG)
113         // Sanity checking the XPC.
114         if (xpc == NULL)
115                 vm_abort("trap_handle: The program counter is NULL!");
116 #endif
117
118 #if defined(__ALPHA__) || defined(__ARM__) || defined(__I386__) || defined(__MIPS__) || defined(__POWERPC__) || defined(__POWERPC64__) || defined(__S390__) || defined(__X86_64__)
119 # if !defined(NDEBUG)
120         /* Perform a sanity check on our execution state functions. */
121
122         executionstate_sanity_check(context);
123 # endif
124
125         /* Read execution state from current context. */
126
127         es.code = NULL;
128         md_executionstate_read(&es, context);
129
130 //# define TRAP_TRACE_VERBOSE
131 # if !defined(NDEBUG) && defined(TRAP_TRACE_VERBOSE)
132         /* Dump contents of execution state */
133
134         if (opt_TraceTraps) {
135                 log_println("[trap_handle: dumping execution state BEFORE ...]");
136                 executionstate_println(&es);
137         }
138 # endif
139 #endif
140
141         // Extract information from executionstate
142         void* pv = es.pv;  // Maybe null, resolved during stackframeinfo creation.
143         void* sp = es.sp;
144 #if defined(__I386__) || defined(__X86_64__)
145         void* ra = xpc;  // Return address is equal to XPC.
146 #else
147         void* ra = es.ra;  // This is correct for leafs.
148 #endif
149
150         // Decode machine-dependent trap instruction.
151         bool decode_result = md_trap_decode(&trp, sig, xpc, &es);
152
153         // Check if the trap instruction is valid and was decoded
154         // successfully.
155         if (!decode_result) {
156                 // Check if the PC has been patched during our way to this
157                 // trap handler (see PR85).
158                 // NOTE: Some archs use SIGILL for other traps too, but it's OK to
159                 // do this check anyway because it will fail.
160                 if (patcher_is_patched_at(xpc) == true) {
161                         if (opt_PrintWarnings)
162                                 log_println("trap_handle: Detected patcher race condition (PR85) at %p", xpc);
163                         return;
164                 }
165
166                 // We have a problem...
167                 vm_abort_disassemble(xpc, 1, "trap_handle: Unknown trap instruction at %p", xpc);
168         }
169
170         // For convenience only.
171         int      type = trp.type;
172         intptr_t val  = trp.value;
173
174         /* Do some preparations before we enter the nativeworld. */
175         /* BEFORE: creating stackframeinfo */
176
177         // Prevent compiler warnings.
178         int32_t        index = 0;
179         java_handle_t* o     = NULL;
180         methodinfo*    m     = NULL;
181
182         switch (type) {
183         case TRAP_ArrayIndexOutOfBoundsException:
184                 /* Get the index into the array causing the exception. */
185
186                 index = (int32_t) val;
187                 break;
188
189         case TRAP_ClassCastException:
190                 /* Wrap the value into a handle, as it is a reference. */
191
192                 o = LLNI_WRAP((java_object_t *) val);
193                 break;
194
195         case TRAP_COMPILER:
196                 /* We need to fixup the XPC, SP and RA here because they
197                    all might point into the compiler stub instead of the
198                    calling method. */
199
200                 MD_TRAP_COMPILER_FIXUP(xpc, ra, sp, pv);
201
202                 /* In this case the passed PV points to the compiler stub.  We
203                    get the methodinfo pointer here and set PV to NULL so
204                    stacktrace_stackframeinfo_add determines the PV for the
205                    parent Java method. */
206
207                 m  = code_get_methodinfo_for_pv(pv);
208                 pv = NULL;
209
210                 break;
211
212         default:
213                 /* do nothing */
214                 break;
215         }
216
217 #if !defined(NDEBUG)
218         // Trace this trap.
219         if (opt_TraceTraps)
220                 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);
221 #endif
222
223 #if defined(ENABLE_VMLOG)
224         vmlog_cacao_signl_type(type);
225 #endif
226
227         /* Fill and add a stackframeinfo. */
228
229         stacktrace_stackframeinfo_add(&sfi, pv, sp, ra, xpc);
230
231         /* Get resulting exception (or pointer to compiled method). */
232
233         java_handle_t* p;
234         void*          entry;
235         bool           was_patched;
236 #if defined(ENABLE_REPLACEMENT)
237         bool           was_replaced;
238 #endif
239
240         switch (type) {
241         case TRAP_NullPointerException:
242                 p = exceptions_new_nullpointerexception();
243                 break;
244
245         case TRAP_ArithmeticException:
246                 p = exceptions_new_arithmeticexception();
247                 break;
248
249         case TRAP_ArrayIndexOutOfBoundsException:
250                 p = exceptions_new_arrayindexoutofboundsexception(index);
251                 break;
252
253         case TRAP_ArrayStoreException:
254                 p = exceptions_new_arraystoreexception();
255                 break;
256
257         case TRAP_ClassCastException:
258                 p = exceptions_new_classcastexception(o);
259                 break;
260
261         case TRAP_CHECK_EXCEPTION:
262                 p = exceptions_fillinstacktrace();
263                 break;
264
265         case TRAP_PATCHER:
266                 p = NULL;
267 #if defined(ENABLE_REPLACEMENT)
268                 was_replaced = replace_handler((uint8_t*) xpc, &es);
269                 if (was_replaced)
270                         break;
271 #endif
272                 was_patched = patcher_handler((uint8_t*) xpc);
273                 break;
274
275         case TRAP_COMPILER:
276                 p = NULL;
277                 entry = jit_compile_handle(m, sfi.pv, ra, (void*) val);
278                 break;
279
280 #if defined(__I386__) && defined(ENABLE_REPLACEMENT)
281 # warning Port the below stuff to use the patching subsystem.
282         case TRAP_COUNTDOWN:
283                 p = NULL;
284                 (void) replace_handler((uint8_t*) xpc - 13, &es);
285                 break;
286 #endif
287
288         default:
289                 /* Let's try to get a backtrace. */
290
291                 (void) methodtree_find(xpc);
292
293                 /* If that does not work, print more debug info. */
294
295                 vm_abort_disassemble(xpc, 1, "trap_handle: Unknown hardware exception type %d", type);
296
297                 /* keep compiler happy */
298
299                 p = NULL;
300         }
301
302         /* Remove stackframeinfo. */
303
304         stacktrace_stackframeinfo_remove(&sfi);
305
306 #if defined(__ALPHA__) || defined(__ARM__) || defined(__I386__) || defined(__MIPS__) || defined(__POWERPC__) || defined(__POWERPC64__) || defined(__S390__) || defined(__X86_64__)
307         /* Update execution state and set registers. */
308         /* AFTER: removing stackframeinfo */
309
310         switch (type) {
311         case TRAP_COMPILER:
312                 // The normal case for a compiler trap is to jump directly to
313                 // the newly compiled method.
314
315                 if (entry != NULL) {
316                         es.pc = (uint8_t *) (uintptr_t) entry;
317                         // The s390 executionstate offsets pv, so we need to
318                         // compensate here.
319                         es.pv = (uint8_t *) (uintptr_t) entry - N_PV_OFFSET;
320                         break;
321                 }
322
323                 // In case of an exception during JIT compilation, we fetch
324                 // the exception here and proceed with exception handling.
325
326                 p = exceptions_get_and_clear_exception();
327                 assert(p != NULL);
328
329                 // Remove RA from stack on some archs.
330
331                 es.sp = (uint8_t*) sp;
332
333                 // Get and set the PV from the parent Java method.
334
335                 es.pv = (uint8_t*) md_codegen_get_pv_from_pc(ra) - N_PV_OFFSET;
336
337                 // Now fall-through to default exception handling.
338
339                 goto trap_handle_exception;
340
341         case TRAP_PATCHER:
342 #if defined(ENABLE_REPLACEMENT)
343                 // If on-stack-replacement suceeded, we are not allowed to touch
344                 // the execution state. We assume that there was no exception.
345
346                 if (was_replaced) {
347                         assert(exceptions_get_exception() == NULL);
348                         break;
349                 }
350 #endif
351
352                 // The normal case for a patcher trap is to continue execution at
353                 // the trap instruction. On some archs the PC may point after the
354                 // trap instruction, so we reset it here.
355
356                 if (was_patched) {
357                         assert(exceptions_get_exception() == NULL);
358                         es.pc = (uint8_t *) (uintptr_t) xpc;
359                         break;
360                 }
361
362                 // In case patching was not successful, we try to fetch the pending
363                 // exception here.
364
365                 p = exceptions_get_and_clear_exception();
366
367                 // If there is no pending exception, we continue execution behind
368                 // the position still in need of patching. Normally this would
369                 // indicate an error in the patching subsystem, but others might
370                 // want to piggyback patchers and we want to be able to provide
371                 // "reusable trap points" and avoid inifinite loops here. This is
372                 // especially useful to implement breakpoints or profiling points
373                 // of any kind. So before changing the trap logic, think about
374                 // utilizing the patching subsystem on your quest. :)
375
376                 if (p == NULL) {
377 #if !defined(NDEBUG)
378                         if (opt_PrintWarnings)
379                                 log_println("trap_handle: Detected reusable trap at %p", xpc);
380 #endif
381                         es.pc = (uint8_t *) (uintptr_t) xpc;
382                         es.pc += REPLACEMENT_PATCH_SIZE;
383                         break;
384                 }
385
386                 // Fall-through to default exception handling.
387
388         trap_handle_exception:
389         default:
390                 if (p != NULL) {
391 #if defined(__ALPHA__) || defined(__I386__) || defined(__X86_64__)
392                         // Perform stack unwinding for exceptions on execution state.
393                         es.pc = (uint8_t *) (uintptr_t) xpc;
394                         es.pv = (uint8_t *) (uintptr_t) sfi.pv;
395                         executionstate_unwind_exception(&es, p);
396
397                         // Pass the exception object to the exception handler.
398                         es.intregs[REG_ITMP1_XPTR] = (uintptr_t) LLNI_DIRECT(p);
399 #else
400                         es.intregs[REG_ITMP1_XPTR] = (uintptr_t) LLNI_DIRECT(p);
401                         es.intregs[REG_ITMP2_XPC]  = (uintptr_t) xpc;
402                         es.pc                      = (uint8_t *) (uintptr_t) asm_handle_exception;
403 #endif
404                 }
405         }
406
407         /* Write back execution state to current context. */
408
409         md_executionstate_write(&es, context);
410
411 # if !defined(NDEBUG) && defined(TRAP_TRACE_VERBOSE)
412         /* Dump contents of execution state */
413
414         if (opt_TraceTraps) {
415                 log_println("[trap_handle: dumping execution state AFTER ...]");
416                 executionstate_println(&es);
417         }
418 # endif
419 #endif
420 }
421
422 #ifdef __cplusplus
423 }
424 #endif
425
426
427 /*
428  * These are local overrides for various environment variables in Emacs.
429  * Please do not remove this and leave it at the end of the file, where
430  * Emacs will automagically detect them.
431  * ---------------------------------------------------------------------
432  * Local variables:
433  * mode: c++
434  * indent-tabs-mode: t
435  * c-basic-offset: 4
436  * tab-width: 4
437  * End:
438  * vim:noexpandtab:sw=4:ts=4:
439  */