+some other %fs access instructions emulation
[captive.git] / src / libcaptive / ps / signal.c
1 /* $Id$
2  * UNIX signal handling for processor emulation for support of ntoskrnl of libcaptive
3  * Copyright (C) 2002 Jan Kratochvil <project-captive@jankratochvil.net>
4  * 
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; exactly version 2 of June 1991 is required
8  * 
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  * 
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17  */
18
19
20 #define _GNU_SOURCE 1   /* for sys/ucontext.h for REG_* */
21
22 #include "config.h"
23
24 #include "captive/signal.h"     /* self */
25 #include <glib/gtypes.h>
26 #include <glib/gmessages.h>
27 #include <signal.h>
28 #include "captive/macros.h"
29 #include <sys/ucontext.h>       /* for struct ucontext */
30 #include "captive/mm.h" /* for captive_mmap_map_get() */
31 #include <sys/mman.h>
32 #include "reactos/internal/mm.h"  /* for PAGE_SIZE */
33 #include "captive/ldr.h"        /* for captive_ModuleList_patchpoint_find() */
34 #include "captive/ldr_exports.h"        /* for struct captive_ModuleList_patchpoint */
35
36
37 /**
38  * _abnormal_termination:
39  *
40  * This call can be also accessed as AbnormalTermination() or abnormal_termination().
41  *
42  * Returns whether some exception occured (FIXME: in what scope?).
43  * Exception handlers are registered from W32 binary in stack frames stored in "fs:[0x00000000]"
44  * value which gets mapped by libcaptive/ps/signal.c to #fs_KPCR_ExceptionList
45  * variable.
46  *
47  * libcaptive currently does not raise any exceptions therefore this call always returns value %0.
48  * See RtlpDispatchException().
49  *
50  * Returns: non-zero if some exception is now registered and pending.
51  */
52 int _abnormal_termination(void)
53 {
54         return 0;
55 }
56
57
58 #if 0
59
60 /**
61  * RtlpDispatchException:
62  * @ExceptionRecord: Ignored by libcaptive.
63  * @Context: Ignored by libcaptive.
64  *
65  * Function definition to prevent inclusion of real RtlpDispatchException() implementation.
66  * Currently libcaptive never raises any exception - fix _abnormal_termination() if it changes.
67  *
68  * Returns: Never returns. Value %0 if it returns although it is impossible.
69  */
70 ULONG RtlpDispatchException(IN PEXCEPTION_RECORD ExceptionRecord,IN PCONTEXT Context)
71 {
72         g_assert_not_reached();
73         g_return_val_if_reached(0);
74 }
75
76 #endif
77
78
79 /* =='KeGetCurrentKPCR()->ExceptionList';
80  * libcaptive has reduced KPCR (named 'captive_KPCR') which
81  * does not contain this field
82  */
83 greg_t fs_KPCR_ExceptionList=(greg_t)-1;
84
85 /* FIXME */
86 static greg_t fs_KPCR_Unknown638=0;
87
88
89 static gboolean instr_mov_greg_to_fsmem(int greg,const void *fsmem,struct ucontext *ucontext)
90 {
91         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
92                 /* moving from %esp is required to pass! */
93                 fs_KPCR_ExceptionList=ucontext->uc_mcontext.gregs[greg];
94                 return TRUE;
95                 }
96         g_return_val_if_reached(FALSE);
97 }
98
99 static gboolean instr_mov_immed_to_fsmem(greg_t immed,const void *fsmem,struct ucontext *ucontext)
100 {
101         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
102                 fs_KPCR_ExceptionList=immed;
103                 return TRUE;
104                 }
105         g_return_val_if_reached(FALSE);
106 }
107
108 static gboolean instr_mov_fsmem_to_greg(const void *fsmem,int greg,struct ucontext *ucontext)
109 {
110         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
111                 /* moving to %esp is required to pass! */
112                 ucontext->uc_mcontext.gregs[greg]=fs_KPCR_ExceptionList;
113                 return TRUE;
114                 }
115         if (fsmem==(const void *)0x00000051) {  /* =='KeGetCurrentKPCR()->Number' */
116                 g_return_val_if_fail(greg!=REG_ESP,FALSE);
117                 ucontext->uc_mcontext.gregs[greg]=(greg_t)0;    /* ==libcaptive version of KeGetCurrentProcessorNumber() */
118                 return TRUE;
119                 }
120         if (fsmem==(const void *)0x00000124) {  /* =='KeGetCurrentKPCR()->CurrentThread' */
121                 g_return_val_if_fail(greg!=REG_ESP,FALSE);
122                 ucontext->uc_mcontext.gregs[greg]=(greg_t)captive_KeGetCurrentKPCR()->CurrentThread;
123                 return TRUE;
124                 }
125         g_return_val_if_reached(FALSE);
126 }
127
128 static gboolean instr_push_fsmem(const void *fsmem,struct ucontext *ucontext)
129 {
130         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
131                 ucontext->uc_mcontext.gregs[REG_ESP]-=4;
132                 *(greg_t *)ucontext->uc_mcontext.gregs[REG_ESP]=fs_KPCR_ExceptionList;
133                 return TRUE;
134                 }
135         g_return_val_if_reached(FALSE);
136 }
137
138 static gboolean instr_pop_fsmem(const void *fsmem,struct ucontext *ucontext)
139 {
140         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
141                 fs_KPCR_ExceptionList=*(greg_t *)ucontext->uc_mcontext.gregs[REG_ESP];
142                 ucontext->uc_mcontext.gregs[REG_ESP]+=4;
143                 return TRUE;
144                 }
145         g_return_val_if_reached(FALSE);
146 }
147
148 static gboolean instr_incl_fsmem(const void *fsmem,struct ucontext *ucontext)
149 {
150         if (fsmem==(const void *)0x00000638) {  /* Unknown638 */
151                 fs_KPCR_Unknown638++;
152                 return TRUE;
153                 }
154         g_return_val_if_reached(FALSE);
155 }
156
157 static int op_regcode_to_greg(guint8 regcode)
158 {
159         switch (regcode) {
160                 case 0x00: return REG_EAX;
161                 case 0x01: return REG_ECX;
162                 case 0x02: return REG_EDX;
163                 case 0x03: return REG_EBX;
164                 case 0x04: return REG_ESP;
165                 case 0x05: return REG_EBP;
166                 case 0x06: return REG_ESI;
167                 case 0x07: return REG_EDI;
168                 }
169         g_return_val_if_reached(REG_EAX);
170 }
171
172 static void sigaction_SIGSEGV(int signo,siginfo_t *siginfo,struct ucontext *ucontext)
173 {
174 guint8 *reg_eip;
175 const void *reg_eip_aligned;
176
177         g_return_if_fail(signo==SIGSEGV);
178         g_return_if_fail(siginfo->si_signo==SIGSEGV);
179         /* siginfo->si_code is weird, seen to have value 128 */
180
181         reg_eip=(void *)ucontext->uc_mcontext.gregs[REG_EIP];
182
183         /* 'reg_eip' is not yet PAGE_SIZE-aligned but we need the aligned ptr for captive_mmap_map_get().
184          * glib NOTE: YOU MAY NOT STORE POINTERS IN INTEGERS.
185          */
186         reg_eip_aligned=(const void *)(((char *)reg_eip)-(GPOINTER_TO_UINT(reg_eip)&(PAGE_SIZE-1)));
187         g_assert(reg_eip_aligned!=NULL);
188         g_return_if_fail(!(captive_mmap_map_get(reg_eip_aligned)&PROT_EXEC));
189         
190         /* all instruction notation comments are written in AT&T 'instr src,dest' syntax! */
191         if (*reg_eip==0x64) {   /* prefix '%fs:' */
192                 reg_eip++;
193                 /* TODO:thread; %fs: is CPU-dependent */
194                 if (*reg_eip==0x0F) {   /* two-byte opcode */
195                         reg_eip++;
196                         if (*reg_eip==0xB6) {   /* ??? */
197                                 reg_eip++;
198                                 if (*reg_eip==0x05) {   /* movzbl %fs:{reg_eip[1..4]},%eax */
199                                         reg_eip++;
200                                         if (instr_mov_fsmem_to_greg(*(const void **)reg_eip,REG_EAX,ucontext)) {
201                                                 reg_eip+=4;
202                                                 goto ok;
203                                                 }
204                                         g_assert_not_reached();
205                                         }
206                                 g_assert_not_reached();
207                                 }
208                         g_assert_not_reached();
209                         }
210                 if (*reg_eip==0xA3) {   /* 'mov %eax,%fs:{reg_eip[1..4]}' */
211                         reg_eip++;
212                         if (instr_mov_greg_to_fsmem(REG_EAX,*(const void **)reg_eip,ucontext)) {
213                                 reg_eip+=4;
214                                 goto ok;
215                                 }
216                         g_assert_not_reached();
217                         }
218                 if (*reg_eip==0x89) {   /* prefix 0x89 */
219                         reg_eip++;
220                         if ((*reg_eip & ~0x38)==0x05)   { /* 'mov %{op_regcode_to_greg(*reg_eip[b3..b5])},%fs:{reg_eip[1..4]} */
221                                 reg_eip++;
222                                 if (instr_mov_greg_to_fsmem(op_regcode_to_greg(reg_eip[-1]>>3U),*(const void **)reg_eip,ucontext)) {
223                                         reg_eip+=4;
224                                         goto ok;
225                                         }
226                                 g_assert_not_reached();
227                                 }
228                         g_assert_not_reached();
229                         }
230                 if (*reg_eip==0xA1) {   /* 'mov %fs:{reg_eip[1..4]},%eax' */
231                         reg_eip++;
232                         if (instr_mov_fsmem_to_greg(*(const void **)reg_eip,REG_EAX,ucontext)) {
233                                 reg_eip+=4;
234                                 goto ok;
235                                 }
236                         g_assert_not_reached();
237                         }
238                 if (*reg_eip==0x8B) {   /* prefix 0x8B */
239                         reg_eip++;
240                         if ((*reg_eip & ~0x38)==0x05) { /* 'mov %fs:{reg_eip[1..4]},%{op_regcode_to_greg(*reg_eip[b3..b5])}' */
241                                 reg_eip++;
242                                 if (instr_mov_fsmem_to_greg(*(const void **)reg_eip,op_regcode_to_greg(reg_eip[-1]>>3U),ucontext)) {
243                                         reg_eip+=4;
244                                         goto ok;
245                                         }
246                                 g_assert_not_reached();
247                                 }
248                         g_assert_not_reached();
249                         }
250                 if (*reg_eip==0xFF) {   /* prefix 0xFF */
251                         reg_eip++;
252                         if (*reg_eip==0x05) {   /* 'incl %fs:{reg_eip[1..4]}' */
253                                 reg_eip++;
254                                 if (instr_incl_fsmem(*(const void **)reg_eip,ucontext)) {
255                                         reg_eip+=4;
256                                         goto ok;
257                                         }
258                                 g_assert_not_reached();
259                                 }
260                         if (*reg_eip==0x35) {   /* 'pushl %fs:{reg_eip[1..4]}' */
261                                 reg_eip++;
262                                 if (instr_push_fsmem(*(const void **)reg_eip,ucontext)) {
263                                         reg_eip+=4;
264                                         goto ok;
265                                         }
266                                 g_assert_not_reached();
267                                 }
268                         g_assert_not_reached();
269                         }
270                 if (*reg_eip==0x8F) {   /* prefix 0x0F */
271                         reg_eip++;
272                         if (*reg_eip==0x05) {   /* 'popl %fs:{reg_eip[1..4]}' */
273                                 reg_eip++;
274                                 if (instr_pop_fsmem(*(const void **)reg_eip,ucontext)) {
275                                         reg_eip+=4;
276                                         goto ok;
277                                         }
278                                 g_assert_not_reached();
279                                 }
280                         g_assert_not_reached();
281                         }
282                 if (*reg_eip==0xC7) {   /* prefix 0xC7 */
283                         reg_eip++;
284                         if (*reg_eip==0x05) {   /* 'movl ${reg_eip[5..8]},%fs:{reg_eip[1..4]}' */
285                                 reg_eip++;
286                                 if (instr_mov_immed_to_fsmem(((greg_t *)reg_eip)[1],*(const void **)reg_eip,ucontext)) {
287                                         reg_eip+=4+4;
288                                         goto ok;
289                                         }
290                                 g_assert_not_reached();
291                                 }
292                         g_assert_not_reached();
293                         }
294                 g_assert_not_reached();
295                 }
296
297         /* all instruction notation comments are written in AT&T 'instr src,dest' syntax! */
298         if (*reg_eip==0x66) {   /* prefix '%fs:' */
299                 reg_eip++;
300                 /* TODO:thread; %fs: is CPU-dependent */
301                 if (*reg_eip==0x8E) {   /* two-byte opcode */
302                         reg_eip++;
303                         if (*reg_eip==0xE3) {   /* 'mov %bx,%fs' */
304                                 reg_eip++;
305                                 g_assert(0x30==(0xFFFF&ucontext->uc_mcontext.gregs[REG_EBX]));
306                                 /* 'reload' of %fs can be ignored */
307                                 goto ok;
308                                 }
309                         g_assert_not_reached();
310                         }
311                 g_assert_not_reached();
312                 }
313
314         if (*reg_eip==0xF4) {   /* hlt; from captive_ModuleList_patch() */
315 struct captive_ModuleList_patchpoint *patchpoint;
316 const gchar *funcname_disabled;
317
318                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: reg_eip=%p; 0xF4 hit",G_STRLOC,reg_eip);
319
320                 if ((funcname_disabled=captive_ModuleList_function_disable_find(
321                                                 reg_eip)))      { /* ExportAddress */
322                         g_error("%s: Reached disabled W32 function: %s",G_STRLOC,funcname_disabled);
323                         g_assert_not_reached();
324                         }
325                 patchpoint=captive_ModuleList_patchpoint_find(
326                                 reg_eip);       /* ExportAddress */
327                 g_assert(patchpoint!=NULL);
328                 if (reg_eip==patchpoint->orig_w32_func) {
329                         g_assert(0xF4 /* hlt */ ==*patchpoint->orig_w32_func);
330                         g_assert(patchpoint->orig_w32_2ndinstr_byte ==*patchpoint->orig_w32_2ndinstr);
331                         if (patchpoint->through_w32_func) {
332                                 *patchpoint->orig_w32_func=patchpoint->orig_w32_func_byte;
333                                 *patchpoint->orig_w32_2ndinstr=0xF4;    /* hlt */
334                                 }
335                         else {  /* !patchpoint->through_w32_func */
336                                 reg_eip=(guint8 *)patchpoint->wrap_wrap_func;
337                                 }
338                         goto ok;
339                         }
340                 if (reg_eip==patchpoint->orig_w32_2ndinstr) {
341                         g_assert(patchpoint->orig_w32_func_byte ==*patchpoint->orig_w32_func);
342                         g_assert(0xF4 /* hlt */ ==*patchpoint->orig_w32_2ndinstr);
343                         g_assert(patchpoint->through_w32_func==TRUE);
344                         *patchpoint->orig_w32_func=0xF4;        /* hlt */
345                         *patchpoint->orig_w32_2ndinstr=patchpoint->orig_w32_2ndinstr_byte;
346                         patchpoint->through_w32_func=FALSE;
347                         goto ok;
348                         }
349                 g_assert_not_reached();
350                 }
351
352         if (*reg_eip==0xFA) {   /* cli */
353                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: reg_eip=%p; CLI neutralized",G_STRLOC,reg_eip);
354                 *reg_eip=0x90;  /* nop */
355                 goto ok;
356                 }
357
358         if (*reg_eip==0xFB) {   /* sti */
359                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: reg_eip=%p; STI neutralized",G_STRLOC,reg_eip);
360                 *reg_eip=0x90;  /* nop */
361                 goto ok;
362                 }
363
364         g_assert_not_reached();
365
366 ok:
367         ucontext->uc_mcontext.gregs[REG_EIP]=(greg_t)reg_eip;
368         /* success */
369 }
370
371 /**
372  * captive_signal_init:
373  *
374  * Initialize UNIX signal handling to be able to emulate foreign W32
375  * instructions. These instructions must be located inside address
376  * space of foreign W32 binary code which is identified by successful
377  * call to captive_mmap_map_get() returning #PROT_EXEC bit set.
378  * This bit should be set from MmAllocateSection() called from
379  * ntoskrnl/ldr/loader.c/LdrPEProcessModule().
380  *
381  * Currently emulated set is the access to %fs register offset %0
382  * where the exception stack top pointer is located.
383  *
384  * Returns: %TRUE if successful.
385  */
386 gboolean captive_signal_init(void)
387 {
388 gint errint;
389 struct sigaction sigaction_struct;
390 sigset_t sigset;
391
392         CAPTIVE_MEMZERO(&sigaction_struct);     /* this structure may have unpredictable fields */
393
394         /* Init 'sigaction_struct.sa_mask'. */
395         errint=sigemptyset(&sigaction_struct.sa_mask);
396         g_return_val_if_fail(errint==0,FALSE);
397         errint=sigaddset(&sigaction_struct.sa_mask,SIGSEGV);
398         g_return_val_if_fail(errint==0,FALSE);
399
400         /* Set the signal sigaction handler. */
401         sigaction_struct.sa_sigaction=(void (*)(int,siginfo_t *,void *))sigaction_SIGSEGV;
402         sigaction_struct.sa_flags=0
403                         |SA_SIGINFO;    /* Use 'sa_sigaction' (not 'sa_handler') */
404         errint=sigaction(SIGSEGV,
405                         &sigaction_struct,      /* act */
406                         NULL);  /* oldact */
407         g_return_val_if_fail(errint==0,FALSE);
408
409         /* Enable SIGSEGV signal (should be default). */
410         errint=sigemptyset(&sigset);
411         g_return_val_if_fail(errint==0,FALSE);
412         errint=sigaddset(&sigset,SIGSEGV);
413         g_return_val_if_fail(errint==0,FALSE);
414         errint=sigprocmask(SIG_UNBLOCK,
415                         &sigset,        /* set */
416                         NULL);  /* oldset */
417         g_return_val_if_fail(errint==0,FALSE);
418
419         return TRUE;
420 }