correct handling of saved host registers
[qemu] / cpu-exec.c
1 /*
2  *  i386 emulator main execution loop
3  * 
4  *  Copyright (c) 2003 Fabrice Bellard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20 #include "config.h"
21 #include "exec.h"
22 #include "disas.h"
23
24 #if !defined(CONFIG_SOFTMMU)
25 #undef EAX
26 #undef ECX
27 #undef EDX
28 #undef EBX
29 #undef ESP
30 #undef EBP
31 #undef ESI
32 #undef EDI
33 #undef EIP
34 #include <signal.h>
35 #include <sys/ucontext.h>
36 #endif
37
38 int tb_invalidated_flag;
39
40 //#define DEBUG_EXEC
41 //#define DEBUG_SIGNAL
42
43 #if defined(TARGET_ARM) || defined(TARGET_SPARC)
44 /* XXX: unify with i386 target */
45 void cpu_loop_exit(void)
46 {
47     longjmp(env->jmp_env, 1);
48 }
49 #endif
50
51 /* exit the current TB from a signal handler. The host registers are
52    restored in a state compatible with the CPU emulator
53  */
54 void cpu_resume_from_signal(CPUState *env1, void *puc) 
55 {
56 #if !defined(CONFIG_SOFTMMU)
57     struct ucontext *uc = puc;
58 #endif
59
60     env = env1;
61
62     /* XXX: restore cpu registers saved in host registers */
63
64 #if !defined(CONFIG_SOFTMMU)
65     if (puc) {
66         /* XXX: use siglongjmp ? */
67         sigprocmask(SIG_SETMASK, &uc->uc_sigmask, NULL);
68     }
69 #endif
70     longjmp(env->jmp_env, 1);
71 }
72
73 /* main execution loop */
74
75 int cpu_exec(CPUState *env1)
76 {
77     int saved_T0, saved_T1, saved_T2;
78     CPUState *saved_env;
79 #ifdef reg_EAX
80     int saved_EAX;
81 #endif
82 #ifdef reg_ECX
83     int saved_ECX;
84 #endif
85 #ifdef reg_EDX
86     int saved_EDX;
87 #endif
88 #ifdef reg_EBX
89     int saved_EBX;
90 #endif
91 #ifdef reg_ESP
92     int saved_ESP;
93 #endif
94 #ifdef reg_EBP
95     int saved_EBP;
96 #endif
97 #ifdef reg_ESI
98     int saved_ESI;
99 #endif
100 #ifdef reg_EDI
101     int saved_EDI;
102 #endif
103 #ifdef __sparc__
104     int saved_i7, tmp_T0;
105 #endif
106     int code_gen_size, ret, interrupt_request;
107     void (*gen_func)(void);
108     TranslationBlock *tb, **ptb;
109     uint8_t *tc_ptr, *cs_base, *pc;
110     unsigned int flags;
111
112     /* first we save global registers */
113     saved_T0 = T0;
114     saved_T1 = T1;
115     saved_T2 = T2;
116     saved_env = env;
117     env = env1;
118 #ifdef __sparc__
119     /* we also save i7 because longjmp may not restore it */
120     asm volatile ("mov %%i7, %0" : "=r" (saved_i7));
121 #endif
122
123 #if defined(TARGET_I386)
124 #ifdef reg_EAX
125     saved_EAX = EAX;
126 #endif
127 #ifdef reg_ECX
128     saved_ECX = ECX;
129 #endif
130 #ifdef reg_EDX
131     saved_EDX = EDX;
132 #endif
133 #ifdef reg_EBX
134     saved_EBX = EBX;
135 #endif
136 #ifdef reg_ESP
137     saved_ESP = ESP;
138 #endif
139 #ifdef reg_EBP
140     saved_EBP = EBP;
141 #endif
142 #ifdef reg_ESI
143     saved_ESI = ESI;
144 #endif
145 #ifdef reg_EDI
146     saved_EDI = EDI;
147 #endif
148
149     env_to_regs();
150     /* put eflags in CPU temporary format */
151     CC_SRC = env->eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);
152     DF = 1 - (2 * ((env->eflags >> 10) & 1));
153     CC_OP = CC_OP_EFLAGS;
154     env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);
155 #elif defined(TARGET_ARM)
156     {
157         unsigned int psr;
158         psr = env->cpsr;
159         env->CF = (psr >> 29) & 1;
160         env->NZF = (psr & 0xc0000000) ^ 0x40000000;
161         env->VF = (psr << 3) & 0x80000000;
162         env->cpsr = psr & ~0xf0000000;
163     }
164 #elif defined(TARGET_SPARC)
165 #elif defined(TARGET_PPC)
166 #else
167 #error unsupported target CPU
168 #endif
169     env->exception_index = -1;
170
171     /* prepare setjmp context for exception handling */
172     for(;;) {
173         if (setjmp(env->jmp_env) == 0) {
174             env->current_tb = NULL;
175             /* if an exception is pending, we execute it here */
176             if (env->exception_index >= 0) {
177                 if (env->exception_index >= EXCP_INTERRUPT) {
178                     /* exit request from the cpu execution loop */
179                     ret = env->exception_index;
180                     break;
181                 } else if (env->user_mode_only) {
182                     /* if user mode only, we simulate a fake exception
183                        which will be hanlded outside the cpu execution
184                        loop */
185 #if defined(TARGET_I386)
186                     do_interrupt_user(env->exception_index, 
187                                       env->exception_is_int, 
188                                       env->error_code, 
189                                       env->exception_next_eip);
190 #endif
191                     ret = env->exception_index;
192                     break;
193                 } else {
194 #if defined(TARGET_I386)
195                     /* simulate a real cpu exception. On i386, it can
196                        trigger new exceptions, but we do not handle
197                        double or triple faults yet. */
198                     do_interrupt(env->exception_index, 
199                                  env->exception_is_int, 
200                                  env->error_code, 
201                                  env->exception_next_eip, 0);
202 #elif defined(TARGET_PPC)
203                     do_interrupt(env);
204 #elif defined(TARGET_SPARC)
205                     do_interrupt(env->exception_index, 
206                                  0,
207                                  env->error_code, 
208                                  env->exception_next_pc, 0);
209 #endif
210                 }
211                 env->exception_index = -1;
212             }
213             T0 = 0; /* force lookup of first TB */
214             for(;;) {
215 #ifdef __sparc__
216                 /* g1 can be modified by some libc? functions */ 
217                 tmp_T0 = T0;
218 #endif      
219                 interrupt_request = env->interrupt_request;
220                 if (__builtin_expect(interrupt_request, 0)) {
221 #if defined(TARGET_I386)
222                     /* if hardware interrupt pending, we execute it */
223                     if ((interrupt_request & CPU_INTERRUPT_HARD) &&
224                         (env->eflags & IF_MASK) && 
225                         !(env->hflags & HF_INHIBIT_IRQ_MASK)) {
226                         int intno;
227                         env->interrupt_request &= ~CPU_INTERRUPT_HARD;
228                         intno = cpu_get_pic_interrupt(env);
229                         if (loglevel & CPU_LOG_TB_IN_ASM) {
230                             fprintf(logfile, "Servicing hardware INT=0x%02x\n", intno);
231                         }
232                         do_interrupt(intno, 0, 0, 0, 1);
233                         /* ensure that no TB jump will be modified as
234                            the program flow was changed */
235 #ifdef __sparc__
236                         tmp_T0 = 0;
237 #else
238                         T0 = 0;
239 #endif
240                     }
241 #elif defined(TARGET_PPC)
242 #if 0
243                     if ((interrupt_request & CPU_INTERRUPT_RESET)) {
244                         cpu_ppc_reset(env);
245                     }
246 #endif
247                     if (msr_ee != 0) {
248                     if ((interrupt_request & CPU_INTERRUPT_HARD)) {
249                             /* Raise it */
250                             env->exception_index = EXCP_EXTERNAL;
251                             env->error_code = 0;
252                             do_interrupt(env);
253                         env->interrupt_request &= ~CPU_INTERRUPT_HARD;
254                         } else if ((interrupt_request & CPU_INTERRUPT_TIMER)) {
255                             /* Raise it */
256                             env->exception_index = EXCP_DECR;
257                             env->error_code = 0;
258                             do_interrupt(env);
259                             env->interrupt_request &= ~CPU_INTERRUPT_TIMER;
260                         }
261                     }
262 #elif defined(TARGET_SPARC)
263                     if (interrupt_request & CPU_INTERRUPT_HARD) {
264                         do_interrupt(0, 0, 0, 0, 0);
265                         env->interrupt_request &= ~CPU_INTERRUPT_HARD;
266                     } else if (interrupt_request & CPU_INTERRUPT_TIMER) {
267                         //do_interrupt(0, 0, 0, 0, 0);
268                         env->interrupt_request &= ~CPU_INTERRUPT_TIMER;
269                     }
270 #endif
271                     if (interrupt_request & CPU_INTERRUPT_EXITTB) {
272                         env->interrupt_request &= ~CPU_INTERRUPT_EXITTB;
273                         /* ensure that no TB jump will be modified as
274                            the program flow was changed */
275 #ifdef __sparc__
276                         tmp_T0 = 0;
277 #else
278                         T0 = 0;
279 #endif
280                     }
281                     if (interrupt_request & CPU_INTERRUPT_EXIT) {
282                         env->interrupt_request &= ~CPU_INTERRUPT_EXIT;
283                         env->exception_index = EXCP_INTERRUPT;
284                         cpu_loop_exit();
285                     }
286                 }
287 #ifdef DEBUG_EXEC
288                 if (loglevel & CPU_LOG_EXEC) {
289 #if defined(TARGET_I386)
290                     /* restore flags in standard format */
291                     env->regs[R_EAX] = EAX;
292                     env->regs[R_EBX] = EBX;
293                     env->regs[R_ECX] = ECX;
294                     env->regs[R_EDX] = EDX;
295                     env->regs[R_ESI] = ESI;
296                     env->regs[R_EDI] = EDI;
297                     env->regs[R_EBP] = EBP;
298                     env->regs[R_ESP] = ESP;
299                     env->eflags = env->eflags | cc_table[CC_OP].compute_all() | (DF & DF_MASK);
300                     cpu_dump_state(env, logfile, fprintf, X86_DUMP_CCOP);
301                     env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);
302 #elif defined(TARGET_ARM)
303                     env->cpsr = compute_cpsr();
304                     cpu_dump_state(env, logfile, fprintf, 0);
305                     env->cpsr &= ~0xf0000000;
306 #elif defined(TARGET_SPARC)
307                     cpu_dump_state (env, logfile, fprintf, 0);
308 #elif defined(TARGET_PPC)
309                     cpu_dump_state(env, logfile, fprintf, 0);
310 #else
311 #error unsupported target CPU 
312 #endif
313                 }
314 #endif
315                 /* we record a subset of the CPU state. It will
316                    always be the same before a given translated block
317                    is executed. */
318 #if defined(TARGET_I386)
319                 flags = env->hflags;
320                 flags |= (env->eflags & (IOPL_MASK | TF_MASK | VM_MASK));
321                 cs_base = env->segs[R_CS].base;
322                 pc = cs_base + env->eip;
323 #elif defined(TARGET_ARM)
324                 flags = 0;
325                 cs_base = 0;
326                 pc = (uint8_t *)env->regs[15];
327 #elif defined(TARGET_SPARC)
328                 flags = 0;
329                 cs_base = (uint8_t *)env->npc;
330                 pc = (uint8_t *) env->pc;
331 #elif defined(TARGET_PPC)
332                 flags = 0;
333                 cs_base = 0;
334                 pc = (uint8_t *)env->nip;
335 #else
336 #error unsupported CPU
337 #endif
338                 tb = tb_find(&ptb, (unsigned long)pc, (unsigned long)cs_base, 
339                              flags);
340                 if (!tb) {
341                     TranslationBlock **ptb1;
342                     unsigned int h;
343                     target_ulong phys_pc, phys_page1, phys_page2, virt_page2;
344                     
345                     
346                     spin_lock(&tb_lock);
347
348                     tb_invalidated_flag = 0;
349                     
350                     regs_to_env(); /* XXX: do it just before cpu_gen_code() */
351
352                     /* find translated block using physical mappings */
353                     phys_pc = get_phys_addr_code(env, (unsigned long)pc);
354                     phys_page1 = phys_pc & TARGET_PAGE_MASK;
355                     phys_page2 = -1;
356                     h = tb_phys_hash_func(phys_pc);
357                     ptb1 = &tb_phys_hash[h];
358                     for(;;) {
359                         tb = *ptb1;
360                         if (!tb)
361                             goto not_found;
362                         if (tb->pc == (unsigned long)pc && 
363                             tb->page_addr[0] == phys_page1 &&
364                             tb->cs_base == (unsigned long)cs_base && 
365                             tb->flags == flags) {
366                             /* check next page if needed */
367                             if (tb->page_addr[1] != -1) {
368                                 virt_page2 = ((unsigned long)pc & TARGET_PAGE_MASK) + 
369                                     TARGET_PAGE_SIZE;
370                                 phys_page2 = get_phys_addr_code(env, virt_page2);
371                                 if (tb->page_addr[1] == phys_page2)
372                                     goto found;
373                             } else {
374                                 goto found;
375                             }
376                         }
377                         ptb1 = &tb->phys_hash_next;
378                     }
379                 not_found:
380                     /* if no translated code available, then translate it now */
381                     tb = tb_alloc((unsigned long)pc);
382                     if (!tb) {
383                         /* flush must be done */
384                         tb_flush(env);
385                         /* cannot fail at this point */
386                         tb = tb_alloc((unsigned long)pc);
387                         /* don't forget to invalidate previous TB info */
388                         ptb = &tb_hash[tb_hash_func((unsigned long)pc)];
389                         T0 = 0;
390                     }
391                     tc_ptr = code_gen_ptr;
392                     tb->tc_ptr = tc_ptr;
393                     tb->cs_base = (unsigned long)cs_base;
394                     tb->flags = flags;
395                     cpu_gen_code(env, tb, CODE_GEN_MAX_SIZE, &code_gen_size);
396                     code_gen_ptr = (void *)(((unsigned long)code_gen_ptr + code_gen_size + CODE_GEN_ALIGN - 1) & ~(CODE_GEN_ALIGN - 1));
397                     
398                     /* check next page if needed */
399                     virt_page2 = ((unsigned long)pc + tb->size - 1) & TARGET_PAGE_MASK;
400                     phys_page2 = -1;
401                     if (((unsigned long)pc & TARGET_PAGE_MASK) != virt_page2) {
402                         phys_page2 = get_phys_addr_code(env, virt_page2);
403                     }
404                     tb_link_phys(tb, phys_pc, phys_page2);
405
406                 found:
407                     if (tb_invalidated_flag) {
408                         /* as some TB could have been invalidated because
409                            of memory exceptions while generating the code, we
410                            must recompute the hash index here */
411                         ptb = &tb_hash[tb_hash_func((unsigned long)pc)];
412                         while (*ptb != NULL)
413                             ptb = &(*ptb)->hash_next;
414                         T0 = 0;
415                     }
416                     /* we add the TB in the virtual pc hash table */
417                     *ptb = tb;
418                     tb->hash_next = NULL;
419                     tb_link(tb);
420                     spin_unlock(&tb_lock);
421                 }
422 #ifdef DEBUG_EXEC
423                 if (loglevel & CPU_LOG_EXEC) {
424                     fprintf(logfile, "Trace 0x%08lx [0x%08lx] %s\n",
425                             (long)tb->tc_ptr, (long)tb->pc,
426                             lookup_symbol((void *)tb->pc));
427                 }
428 #endif
429 #ifdef __sparc__
430                 T0 = tmp_T0;
431 #endif      
432                 /* see if we can patch the calling TB. */
433                 if (T0 != 0
434 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
435                     && (tb->cflags & CF_CODE_COPY) == 
436                     (((TranslationBlock *)(T0 & ~3))->cflags & CF_CODE_COPY)
437 #endif
438                     ) {
439                     spin_lock(&tb_lock);
440                     tb_add_jump((TranslationBlock *)(T0 & ~3), T0 & 3, tb);
441 #if defined(USE_CODE_COPY)
442                     /* propagates the FP use info */
443                     ((TranslationBlock *)(T0 & ~3))->cflags |= 
444                         (tb->cflags & CF_FP_USED);
445 #endif
446                     spin_unlock(&tb_lock);
447                 }
448                 tc_ptr = tb->tc_ptr;
449                 env->current_tb = tb;
450                 /* execute the generated code */
451                 gen_func = (void *)tc_ptr;
452 #if defined(__sparc__)
453                 __asm__ __volatile__("call      %0\n\t"
454                                      "mov       %%o7,%%i0"
455                                      : /* no outputs */
456                                      : "r" (gen_func) 
457                                      : "i0", "i1", "i2", "i3", "i4", "i5");
458 #elif defined(__arm__)
459                 asm volatile ("mov pc, %0\n\t"
460                               ".global exec_loop\n\t"
461                               "exec_loop:\n\t"
462                               : /* no outputs */
463                               : "r" (gen_func)
464                               : "r1", "r2", "r3", "r8", "r9", "r10", "r12", "r14");
465 #elif defined(TARGET_I386) && defined(USE_CODE_COPY)
466 {
467     if (!(tb->cflags & CF_CODE_COPY)) {
468         if ((tb->cflags & CF_FP_USED) && env->native_fp_regs) {
469             save_native_fp_state(env);
470         }
471         gen_func();
472     } else {
473         if ((tb->cflags & CF_FP_USED) && !env->native_fp_regs) {
474             restore_native_fp_state(env);
475         }
476         /* we work with native eflags */
477         CC_SRC = cc_table[CC_OP].compute_all();
478         CC_OP = CC_OP_EFLAGS;
479         asm(".globl exec_loop\n"
480             "\n"
481             "debug1:\n"
482             "    pushl %%ebp\n"
483             "    fs movl %10, %9\n"
484             "    fs movl %11, %%eax\n"
485             "    andl $0x400, %%eax\n"
486             "    fs orl %8, %%eax\n"
487             "    pushl %%eax\n"
488             "    popf\n"
489             "    fs movl %%esp, %12\n"
490             "    fs movl %0, %%eax\n"
491             "    fs movl %1, %%ecx\n"
492             "    fs movl %2, %%edx\n"
493             "    fs movl %3, %%ebx\n"
494             "    fs movl %4, %%esp\n"
495             "    fs movl %5, %%ebp\n"
496             "    fs movl %6, %%esi\n"
497             "    fs movl %7, %%edi\n"
498             "    fs jmp *%9\n"
499             "exec_loop:\n"
500             "    fs movl %%esp, %4\n"
501             "    fs movl %12, %%esp\n"
502             "    fs movl %%eax, %0\n"
503             "    fs movl %%ecx, %1\n"
504             "    fs movl %%edx, %2\n"
505             "    fs movl %%ebx, %3\n"
506             "    fs movl %%ebp, %5\n"
507             "    fs movl %%esi, %6\n"
508             "    fs movl %%edi, %7\n"
509             "    pushf\n"
510             "    popl %%eax\n"
511             "    movl %%eax, %%ecx\n"
512             "    andl $0x400, %%ecx\n"
513             "    shrl $9, %%ecx\n"
514             "    andl $0x8d5, %%eax\n"
515             "    fs movl %%eax, %8\n"
516             "    movl $1, %%eax\n"
517             "    subl %%ecx, %%eax\n"
518             "    fs movl %%eax, %11\n"
519             "    fs movl %9, %%ebx\n" /* get T0 value */
520             "    popl %%ebp\n"
521             :
522             : "m" (*(uint8_t *)offsetof(CPUState, regs[0])),
523             "m" (*(uint8_t *)offsetof(CPUState, regs[1])),
524             "m" (*(uint8_t *)offsetof(CPUState, regs[2])),
525             "m" (*(uint8_t *)offsetof(CPUState, regs[3])),
526             "m" (*(uint8_t *)offsetof(CPUState, regs[4])),
527             "m" (*(uint8_t *)offsetof(CPUState, regs[5])),
528             "m" (*(uint8_t *)offsetof(CPUState, regs[6])),
529             "m" (*(uint8_t *)offsetof(CPUState, regs[7])),
530             "m" (*(uint8_t *)offsetof(CPUState, cc_src)),
531             "m" (*(uint8_t *)offsetof(CPUState, tmp0)),
532             "a" (gen_func),
533             "m" (*(uint8_t *)offsetof(CPUState, df)),
534             "m" (*(uint8_t *)offsetof(CPUState, saved_esp))
535             : "%ecx", "%edx"
536             );
537     }
538 }
539 #else
540                 gen_func();
541 #endif
542                 env->current_tb = NULL;
543                 /* reset soft MMU for next block (it can currently
544                    only be set by a memory fault) */
545 #if defined(TARGET_I386) && !defined(CONFIG_SOFTMMU)
546                 if (env->hflags & HF_SOFTMMU_MASK) {
547                     env->hflags &= ~HF_SOFTMMU_MASK;
548                     /* do not allow linking to another block */
549                     T0 = 0;
550                 }
551 #endif
552             }
553         } else {
554             env_to_regs();
555         }
556     } /* for(;;) */
557
558
559 #if defined(TARGET_I386)
560 #if defined(USE_CODE_COPY)
561     if (env->native_fp_regs) {
562         save_native_fp_state(env);
563     }
564 #endif
565     /* restore flags in standard format */
566     env->eflags = env->eflags | cc_table[CC_OP].compute_all() | (DF & DF_MASK);
567
568     /* restore global registers */
569 #ifdef reg_EAX
570     EAX = saved_EAX;
571 #endif
572 #ifdef reg_ECX
573     ECX = saved_ECX;
574 #endif
575 #ifdef reg_EDX
576     EDX = saved_EDX;
577 #endif
578 #ifdef reg_EBX
579     EBX = saved_EBX;
580 #endif
581 #ifdef reg_ESP
582     ESP = saved_ESP;
583 #endif
584 #ifdef reg_EBP
585     EBP = saved_EBP;
586 #endif
587 #ifdef reg_ESI
588     ESI = saved_ESI;
589 #endif
590 #ifdef reg_EDI
591     EDI = saved_EDI;
592 #endif
593 #elif defined(TARGET_ARM)
594     env->cpsr = compute_cpsr();
595 #elif defined(TARGET_SPARC)
596 #elif defined(TARGET_PPC)
597 #else
598 #error unsupported target CPU
599 #endif
600 #ifdef __sparc__
601     asm volatile ("mov %0, %%i7" : : "r" (saved_i7));
602 #endif
603     T0 = saved_T0;
604     T1 = saved_T1;
605     T2 = saved_T2;
606     env = saved_env;
607     return ret;
608 }
609
610 /* must only be called from the generated code as an exception can be
611    generated */
612 void tb_invalidate_page_range(target_ulong start, target_ulong end)
613 {
614     /* XXX: cannot enable it yet because it yields to MMU exception
615        where NIP != read address on PowerPC */
616 #if 0
617     target_ulong phys_addr;
618     phys_addr = get_phys_addr_code(env, start);
619     tb_invalidate_phys_page_range(phys_addr, phys_addr + end - start, 0);
620 #endif
621 }
622
623 #if defined(TARGET_I386) && defined(CONFIG_USER_ONLY)
624
625 void cpu_x86_load_seg(CPUX86State *s, int seg_reg, int selector)
626 {
627     CPUX86State *saved_env;
628
629     saved_env = env;
630     env = s;
631     if (!(env->cr[0] & CR0_PE_MASK) || (env->eflags & VM_MASK)) {
632         selector &= 0xffff;
633         cpu_x86_load_seg_cache(env, seg_reg, selector, 
634                                (uint8_t *)(selector << 4), 0xffff, 0);
635     } else {
636         load_seg(seg_reg, selector);
637     }
638     env = saved_env;
639 }
640
641 void cpu_x86_fsave(CPUX86State *s, uint8_t *ptr, int data32)
642 {
643     CPUX86State *saved_env;
644
645     saved_env = env;
646     env = s;
647     
648     helper_fsave(ptr, data32);
649
650     env = saved_env;
651 }
652
653 void cpu_x86_frstor(CPUX86State *s, uint8_t *ptr, int data32)
654 {
655     CPUX86State *saved_env;
656
657     saved_env = env;
658     env = s;
659     
660     helper_frstor(ptr, data32);
661
662     env = saved_env;
663 }
664
665 #endif /* TARGET_I386 */
666
667 #if !defined(CONFIG_SOFTMMU)
668
669 #if defined(TARGET_I386)
670
671 /* 'pc' is the host PC at which the exception was raised. 'address' is
672    the effective address of the memory exception. 'is_write' is 1 if a
673    write caused the exception and otherwise 0'. 'old_set' is the
674    signal set which should be restored */
675 static inline int handle_cpu_signal(unsigned long pc, unsigned long address,
676                                     int is_write, sigset_t *old_set, 
677                                     void *puc)
678 {
679     TranslationBlock *tb;
680     int ret;
681
682     if (cpu_single_env)
683         env = cpu_single_env; /* XXX: find a correct solution for multithread */
684 #if defined(DEBUG_SIGNAL)
685     qemu_printf("qemu: SIGSEGV pc=0x%08lx address=%08lx w=%d oldset=0x%08lx\n", 
686                 pc, address, is_write, *(unsigned long *)old_set);
687 #endif
688     /* XXX: locking issue */
689     if (is_write && page_unprotect(address, pc, puc)) {
690         return 1;
691     }
692
693     /* see if it is an MMU fault */
694     ret = cpu_x86_handle_mmu_fault(env, address, is_write, 
695                                    ((env->hflags & HF_CPL_MASK) == 3), 0);
696     if (ret < 0)
697         return 0; /* not an MMU fault */
698     if (ret == 0)
699         return 1; /* the MMU fault was handled without causing real CPU fault */
700     /* now we have a real cpu fault */
701     tb = tb_find_pc(pc);
702     if (tb) {
703         /* the PC is inside the translated code. It means that we have
704            a virtual CPU fault */
705         cpu_restore_state(tb, env, pc, puc);
706     }
707     if (ret == 1) {
708 #if 0
709         printf("PF exception: EIP=0x%08x CR2=0x%08x error=0x%x\n", 
710                env->eip, env->cr[2], env->error_code);
711 #endif
712         /* we restore the process signal mask as the sigreturn should
713            do it (XXX: use sigsetjmp) */
714         sigprocmask(SIG_SETMASK, old_set, NULL);
715         raise_exception_err(EXCP0E_PAGE, env->error_code);
716     } else {
717         /* activate soft MMU for this block */
718         env->hflags |= HF_SOFTMMU_MASK;
719         cpu_resume_from_signal(env, puc);
720     }
721     /* never comes here */
722     return 1;
723 }
724
725 #elif defined(TARGET_ARM)
726 static inline int handle_cpu_signal(unsigned long pc, unsigned long address,
727                                     int is_write, sigset_t *old_set,
728                                     void *puc)
729 {
730     /* XXX: do more */
731     return 0;
732 }
733 #elif defined(TARGET_SPARC)
734 static inline int handle_cpu_signal(unsigned long pc, unsigned long address,
735                                     int is_write, sigset_t *old_set,
736                                     void *puc)
737 {
738     /* XXX: locking issue */
739     if (is_write && page_unprotect(address, pc, puc)) {
740         return 1;
741     }
742     return 0;
743 }
744 #elif defined (TARGET_PPC)
745 static inline int handle_cpu_signal(unsigned long pc, unsigned long address,
746                                     int is_write, sigset_t *old_set,
747                                     void *puc)
748 {
749     TranslationBlock *tb;
750     int ret;
751     
752 #if 1
753     if (cpu_single_env)
754         env = cpu_single_env; /* XXX: find a correct solution for multithread */
755 #endif
756 #if defined(DEBUG_SIGNAL)
757     printf("qemu: SIGSEGV pc=0x%08lx address=%08lx w=%d oldset=0x%08lx\n", 
758            pc, address, is_write, *(unsigned long *)old_set);
759 #endif
760     /* XXX: locking issue */
761     if (is_write && page_unprotect(address, pc, puc)) {
762         return 1;
763     }
764
765     /* see if it is an MMU fault */
766     ret = cpu_ppc_handle_mmu_fault(env, address, is_write, msr_pr, 0);
767     if (ret < 0)
768         return 0; /* not an MMU fault */
769     if (ret == 0)
770         return 1; /* the MMU fault was handled without causing real CPU fault */
771
772     /* now we have a real cpu fault */
773     tb = tb_find_pc(pc);
774     if (tb) {
775         /* the PC is inside the translated code. It means that we have
776            a virtual CPU fault */
777         cpu_restore_state(tb, env, pc, puc);
778     }
779     if (ret == 1) {
780 #if 0
781         printf("PF exception: NIP=0x%08x error=0x%x %p\n", 
782                env->nip, env->error_code, tb);
783 #endif
784     /* we restore the process signal mask as the sigreturn should
785        do it (XXX: use sigsetjmp) */
786         sigprocmask(SIG_SETMASK, old_set, NULL);
787         do_raise_exception_err(env->exception_index, env->error_code);
788     } else {
789         /* activate soft MMU for this block */
790         cpu_resume_from_signal(env, puc);
791     }
792     /* never comes here */
793     return 1;
794 }
795 #else
796 #error unsupported target CPU
797 #endif
798
799 #if defined(__i386__)
800
801 #if defined(USE_CODE_COPY)
802 static void cpu_send_trap(unsigned long pc, int trap, 
803                           struct ucontext *uc)
804 {
805     TranslationBlock *tb;
806
807     if (cpu_single_env)
808         env = cpu_single_env; /* XXX: find a correct solution for multithread */
809     /* now we have a real cpu fault */
810     tb = tb_find_pc(pc);
811     if (tb) {
812         /* the PC is inside the translated code. It means that we have
813            a virtual CPU fault */
814         cpu_restore_state(tb, env, pc, uc);
815     }
816     sigprocmask(SIG_SETMASK, &uc->uc_sigmask, NULL);
817     raise_exception_err(trap, env->error_code);
818 }
819 #endif
820
821 int cpu_signal_handler(int host_signum, struct siginfo *info, 
822                        void *puc)
823 {
824     struct ucontext *uc = puc;
825     unsigned long pc;
826     int trapno;
827
828 #ifndef REG_EIP
829 /* for glibc 2.1 */
830 #define REG_EIP    EIP
831 #define REG_ERR    ERR
832 #define REG_TRAPNO TRAPNO
833 #endif
834     pc = uc->uc_mcontext.gregs[REG_EIP];
835     trapno = uc->uc_mcontext.gregs[REG_TRAPNO];
836 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
837     if (trapno == 0x00 || trapno == 0x05) {
838         /* send division by zero or bound exception */
839         cpu_send_trap(pc, trapno, uc);
840         return 1;
841     } else
842 #endif
843         return handle_cpu_signal(pc, (unsigned long)info->si_addr, 
844                                  trapno == 0xe ? 
845                                  (uc->uc_mcontext.gregs[REG_ERR] >> 1) & 1 : 0,
846                                  &uc->uc_sigmask, puc);
847 }
848
849 #elif defined(__x86_64__)
850
851 int cpu_signal_handler(int host_signum, struct siginfo *info,
852                        void *puc)
853 {
854     struct ucontext *uc = puc;
855     unsigned long pc;
856
857     pc = uc->uc_mcontext.gregs[REG_RIP];
858     return handle_cpu_signal(pc, (unsigned long)info->si_addr, 
859                              uc->uc_mcontext.gregs[REG_TRAPNO] == 0xe ? 
860                              (uc->uc_mcontext.gregs[REG_ERR] >> 1) & 1 : 0,
861                              &uc->uc_sigmask, puc);
862 }
863
864 #elif defined(__powerpc__)
865
866 /***********************************************************************
867  * signal context platform-specific definitions
868  * From Wine
869  */
870 #ifdef linux
871 /* All Registers access - only for local access */
872 # define REG_sig(reg_name, context)             ((context)->uc_mcontext.regs->reg_name)
873 /* Gpr Registers access  */
874 # define GPR_sig(reg_num, context)              REG_sig(gpr[reg_num], context)
875 # define IAR_sig(context)                       REG_sig(nip, context)   /* Program counter */
876 # define MSR_sig(context)                       REG_sig(msr, context)   /* Machine State Register (Supervisor) */
877 # define CTR_sig(context)                       REG_sig(ctr, context)   /* Count register */
878 # define XER_sig(context)                       REG_sig(xer, context) /* User's integer exception register */
879 # define LR_sig(context)                        REG_sig(link, context) /* Link register */
880 # define CR_sig(context)                        REG_sig(ccr, context) /* Condition register */
881 /* Float Registers access  */
882 # define FLOAT_sig(reg_num, context)            (((double*)((char*)((context)->uc_mcontext.regs+48*4)))[reg_num])
883 # define FPSCR_sig(context)                     (*(int*)((char*)((context)->uc_mcontext.regs+(48+32*2)*4)))
884 /* Exception Registers access */
885 # define DAR_sig(context)                       REG_sig(dar, context)
886 # define DSISR_sig(context)                     REG_sig(dsisr, context)
887 # define TRAP_sig(context)                      REG_sig(trap, context)
888 #endif /* linux */
889
890 #ifdef __APPLE__
891 # include <sys/ucontext.h>
892 typedef struct ucontext SIGCONTEXT;
893 /* All Registers access - only for local access */
894 # define REG_sig(reg_name, context)             ((context)->uc_mcontext->ss.reg_name)
895 # define FLOATREG_sig(reg_name, context)        ((context)->uc_mcontext->fs.reg_name)
896 # define EXCEPREG_sig(reg_name, context)        ((context)->uc_mcontext->es.reg_name)
897 # define VECREG_sig(reg_name, context)          ((context)->uc_mcontext->vs.reg_name)
898 /* Gpr Registers access */
899 # define GPR_sig(reg_num, context)              REG_sig(r##reg_num, context)
900 # define IAR_sig(context)                       REG_sig(srr0, context)  /* Program counter */
901 # define MSR_sig(context)                       REG_sig(srr1, context)  /* Machine State Register (Supervisor) */
902 # define CTR_sig(context)                       REG_sig(ctr, context)
903 # define XER_sig(context)                       REG_sig(xer, context) /* Link register */
904 # define LR_sig(context)                        REG_sig(lr, context)  /* User's integer exception register */
905 # define CR_sig(context)                        REG_sig(cr, context)  /* Condition register */
906 /* Float Registers access */
907 # define FLOAT_sig(reg_num, context)            FLOATREG_sig(fpregs[reg_num], context)
908 # define FPSCR_sig(context)                     ((double)FLOATREG_sig(fpscr, context))
909 /* Exception Registers access */
910 # define DAR_sig(context)                       EXCEPREG_sig(dar, context)     /* Fault registers for coredump */
911 # define DSISR_sig(context)                     EXCEPREG_sig(dsisr, context)
912 # define TRAP_sig(context)                      EXCEPREG_sig(exception, context) /* number of powerpc exception taken */
913 #endif /* __APPLE__ */
914
915 int cpu_signal_handler(int host_signum, struct siginfo *info, 
916                        void *puc)
917 {
918     struct ucontext *uc = puc;
919     unsigned long pc;
920     int is_write;
921
922     pc = IAR_sig(uc);
923     is_write = 0;
924 #if 0
925     /* ppc 4xx case */
926     if (DSISR_sig(uc) & 0x00800000)
927         is_write = 1;
928 #else
929     if (TRAP_sig(uc) != 0x400 && (DSISR_sig(uc) & 0x02000000))
930         is_write = 1;
931 #endif
932     return handle_cpu_signal(pc, (unsigned long)info->si_addr, 
933                              is_write, &uc->uc_sigmask, puc);
934 }
935
936 #elif defined(__alpha__)
937
938 int cpu_signal_handler(int host_signum, struct siginfo *info, 
939                            void *puc)
940 {
941     struct ucontext *uc = puc;
942     uint32_t *pc = uc->uc_mcontext.sc_pc;
943     uint32_t insn = *pc;
944     int is_write = 0;
945
946     /* XXX: need kernel patch to get write flag faster */
947     switch (insn >> 26) {
948     case 0x0d: // stw
949     case 0x0e: // stb
950     case 0x0f: // stq_u
951     case 0x24: // stf
952     case 0x25: // stg
953     case 0x26: // sts
954     case 0x27: // stt
955     case 0x2c: // stl
956     case 0x2d: // stq
957     case 0x2e: // stl_c
958     case 0x2f: // stq_c
959         is_write = 1;
960     }
961
962     return handle_cpu_signal(pc, (unsigned long)info->si_addr, 
963                              is_write, &uc->uc_sigmask, puc);
964 }
965 #elif defined(__sparc__)
966
967 int cpu_signal_handler(int host_signum, struct siginfo *info, 
968                        void *puc)
969 {
970     uint32_t *regs = (uint32_t *)(info + 1);
971     void *sigmask = (regs + 20);
972     unsigned long pc;
973     int is_write;
974     uint32_t insn;
975     
976     /* XXX: is there a standard glibc define ? */
977     pc = regs[1];
978     /* XXX: need kernel patch to get write flag faster */
979     is_write = 0;
980     insn = *(uint32_t *)pc;
981     if ((insn >> 30) == 3) {
982       switch((insn >> 19) & 0x3f) {
983       case 0x05: // stb
984       case 0x06: // sth
985       case 0x04: // st
986       case 0x07: // std
987       case 0x24: // stf
988       case 0x27: // stdf
989       case 0x25: // stfsr
990         is_write = 1;
991         break;
992       }
993     }
994     return handle_cpu_signal(pc, (unsigned long)info->si_addr, 
995                              is_write, sigmask, NULL);
996 }
997
998 #elif defined(__arm__)
999
1000 int cpu_signal_handler(int host_signum, struct siginfo *info, 
1001                        void *puc)
1002 {
1003     struct ucontext *uc = puc;
1004     unsigned long pc;
1005     int is_write;
1006     
1007     pc = uc->uc_mcontext.gregs[R15];
1008     /* XXX: compute is_write */
1009     is_write = 0;
1010     return handle_cpu_signal(pc, (unsigned long)info->si_addr, 
1011                              is_write,
1012                              &uc->uc_sigmask);
1013 }
1014
1015 #elif defined(__mc68000)
1016
1017 int cpu_signal_handler(int host_signum, struct siginfo *info, 
1018                        void *puc)
1019 {
1020     struct ucontext *uc = puc;
1021     unsigned long pc;
1022     int is_write;
1023     
1024     pc = uc->uc_mcontext.gregs[16];
1025     /* XXX: compute is_write */
1026     is_write = 0;
1027     return handle_cpu_signal(pc, (unsigned long)info->si_addr, 
1028                              is_write,
1029                              &uc->uc_sigmask, puc);
1030 }
1031
1032 #else
1033
1034 #error host CPU specific signal handler needed
1035
1036 #endif
1037
1038 #endif /* !defined(CONFIG_SOFTMMU) */