sigaction_SIGSEGV(): +PROT_EXEC sanity check caching for better performance.
[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 int _abnormal_termination_orig(void);
38 extern greg_t fs_KPCR_ExceptionList;
39
40 /**
41  * _abnormal_termination_wrap:
42  *
43  * This call can be also accessed as AbnormalTermination() or _abnormal_termination().
44  * It is a captive wrapper around _abnormal_termination() function.
45  *
46  * Returns whether some exception occured in the current #try block we are currently
47  * #finish -ing. Any functions called from current #finish block will be considered
48  * for returning zero back again. It is forbidden to call this function outside
49  * of #finish block, result of such call is undefined.
50  *
51  * Exception handlers are registered from W32 binary in stack frames stored in "fs:[0x00000000]"
52  * value which gets mapped by libcaptive/ps/signal.c to #fs_KPCR_ExceptionList
53  * variable.
54  *
55  * If no exception handler was registered yet this function returns zero.
56  *
57  * See also RtlpDispatchException().
58  *
59  * Returns: non-zero if some exception is now being handled as pending.
60  */
61 int _abnormal_termination_wrap(void)
62 {
63         /* No handler registered yet? ntoskrnl _abnormal_termination() does not handle it
64          * and I do not want to bother with registering toplevel handler.
65          */
66         if (fs_KPCR_ExceptionList==(greg_t)-1)
67                 return 0;
68
69         return _abnormal_termination_orig();
70 }
71
72
73 #if 0
74
75 /**
76  * RtlpDispatchException:
77  * @ExceptionRecord: Ignored by libcaptive.
78  * @Context: Ignored by libcaptive.
79  *
80  * Function definition to prevent inclusion of real RtlpDispatchException() implementation.
81  * Currently libcaptive never raises any exception - fix _abnormal_termination() if it changes.
82  *
83  * Returns: Never returns. Value %0 if it returns although it is impossible.
84  */
85 ULONG RtlpDispatchException(IN PEXCEPTION_RECORD ExceptionRecord,IN PCONTEXT Context)
86 {
87         g_assert_not_reached();
88         g_return_val_if_reached(0);
89 }
90
91 #endif
92
93
94 /* =='KeGetCurrentKPCR()->ExceptionList';
95  * libcaptive has reduced KPCR (named 'captive_KPCR') which
96  * does not contain this field
97  */
98 greg_t fs_KPCR_ExceptionList=(greg_t)-1;
99
100 /* FIXME */
101 static greg_t fs_KPCR_Unknown638=0;
102
103
104 static gboolean instr_mov_greg_to_fsmem(int greg,const void *fsmem,struct ucontext *ucontext)
105 {
106         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
107                 /* moving from %esp is required to pass! */
108                 fs_KPCR_ExceptionList=ucontext->uc_mcontext.gregs[greg];
109                 return TRUE;
110                 }
111         g_return_val_if_reached(FALSE);
112 }
113
114 static gboolean instr_mov_immed_to_fsmem(greg_t immed,const void *fsmem,struct ucontext *ucontext)
115 {
116         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
117                 fs_KPCR_ExceptionList=immed;
118                 return TRUE;
119                 }
120         g_return_val_if_reached(FALSE);
121 }
122
123 static gboolean instr_mov_fsmem_to_greg(const void *fsmem,int greg,struct ucontext *ucontext)
124 {
125         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
126                 /* moving to %esp is required to pass! */
127                 ucontext->uc_mcontext.gregs[greg]=fs_KPCR_ExceptionList;
128                 return TRUE;
129                 }
130         if (fsmem==(const void *)0x00000051) {  /* =='KeGetCurrentKPCR()->Number' */
131                 g_return_val_if_fail(greg!=REG_ESP,FALSE);
132                 ucontext->uc_mcontext.gregs[greg]=(greg_t)0;    /* ==libcaptive version of KeGetCurrentProcessorNumber() */
133                 return TRUE;
134                 }
135         if (fsmem==(const void *)0x00000124) {  /* =='KeGetCurrentKPCR()->CurrentThread' */
136                 g_return_val_if_fail(greg!=REG_ESP,FALSE);
137                 ucontext->uc_mcontext.gregs[greg]=(greg_t)captive_KeGetCurrentKPCR()->CurrentThread;
138                 return TRUE;
139                 }
140         g_return_val_if_reached(FALSE);
141 }
142
143 static gboolean instr_push_fsmem(const void *fsmem,struct ucontext *ucontext)
144 {
145         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
146                 ucontext->uc_mcontext.gregs[REG_ESP]-=4;
147                 *(greg_t *)ucontext->uc_mcontext.gregs[REG_ESP]=fs_KPCR_ExceptionList;
148                 return TRUE;
149                 }
150         g_return_val_if_reached(FALSE);
151 }
152
153 static gboolean instr_pop_fsmem(const void *fsmem,struct ucontext *ucontext)
154 {
155         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
156                 fs_KPCR_ExceptionList=*(greg_t *)ucontext->uc_mcontext.gregs[REG_ESP];
157                 ucontext->uc_mcontext.gregs[REG_ESP]+=4;
158                 return TRUE;
159                 }
160         g_return_val_if_reached(FALSE);
161 }
162
163 static gboolean instr_incl_fsmem(const void *fsmem,struct ucontext *ucontext)
164 {
165         if (fsmem==(const void *)0x00000638) {  /* Unknown638 */
166                 fs_KPCR_Unknown638++;
167                 return TRUE;
168                 }
169         g_return_val_if_reached(FALSE);
170 }
171
172 static int op_regcode_to_greg(guint8 regcode)
173 {
174         switch (regcode) {
175                 case 0x00: return REG_EAX;
176                 case 0x01: return REG_ECX;
177                 case 0x02: return REG_EDX;
178                 case 0x03: return REG_EBX;
179                 case 0x04: return REG_ESP;
180                 case 0x05: return REG_EBP;
181                 case 0x06: return REG_ESI;
182                 case 0x07: return REG_EDI;
183                 }
184         g_return_val_if_reached(REG_EAX);
185 }
186
187 static void sigaction_SIGSEGV(int signo,siginfo_t *siginfo,struct ucontext *ucontext)
188 {
189 guint8 *reg_eip;
190 const void *reg_eip_aligned;
191 static const void *reg_eip_aligned_last_valid=NULL;     /* performance cache */
192
193         g_return_if_fail(signo==SIGSEGV);
194         g_return_if_fail(siginfo->si_signo==SIGSEGV);
195         /* siginfo->si_code is weird, seen to have value 128 */
196
197         reg_eip=(void *)ucontext->uc_mcontext.gregs[REG_EIP];
198
199         /* 'reg_eip' is not yet PAGE_SIZE-aligned but we need the aligned ptr for captive_mmap_map_get().
200          * glib NOTE: YOU MAY NOT STORE POINTERS IN INTEGERS.
201          */
202         reg_eip_aligned=(const void *)(((char *)reg_eip)-(GPOINTER_TO_UINT(reg_eip)&(PAGE_SIZE-1)));
203         g_assert(reg_eip_aligned!=NULL);
204
205         /* We do not expect any pages can get un-PROT_EXEC-ed
206          * and therefore we never invalidate our cache 'reg_eip_aligned_last_valid'.
207          */
208         if (reg_eip_aligned_last_valid!=reg_eip_aligned) {
209                 g_return_if_fail(!(captive_mmap_map_get(reg_eip_aligned)&PROT_EXEC));
210                 reg_eip_aligned_last_valid=reg_eip_aligned;
211                 }
212         
213         /* all instruction notation comments are written in AT&T 'instr src,dest' syntax! */
214         if (*reg_eip==0x64) {   /* prefix '%fs:' */
215                 reg_eip++;
216                 /* TODO:thread; %fs: is CPU-dependent */
217                 if (*reg_eip==0x0F) {   /* two-byte opcode */
218                         reg_eip++;
219                         if (*reg_eip==0xB6) {   /* ??? */
220                                 reg_eip++;
221                                 if (*reg_eip==0x05) {   /* movzbl %fs:{reg_eip[1..4]},%eax */
222                                         reg_eip++;
223                                         if (instr_mov_fsmem_to_greg(*(const void **)reg_eip,REG_EAX,ucontext)) {
224                                                 reg_eip+=4;
225                                                 goto ok;
226                                                 }
227                                         g_assert_not_reached();
228                                         }
229                                 g_assert_not_reached();
230                                 }
231                         g_assert_not_reached();
232                         }
233                 if (*reg_eip==0xA3) {   /* 'mov %eax,%fs:{reg_eip[1..4]}' */
234                         reg_eip++;
235                         if (instr_mov_greg_to_fsmem(REG_EAX,*(const void **)reg_eip,ucontext)) {
236                                 reg_eip+=4;
237                                 goto ok;
238                                 }
239                         g_assert_not_reached();
240                         }
241                 if (*reg_eip==0x89) {   /* prefix 0x89 */
242                         reg_eip++;
243                         if ((*reg_eip & ~0x38)==0x05)   { /* 'mov %{op_regcode_to_greg(*reg_eip[b3..b5])},%fs:{reg_eip[1..4]} */
244                                 reg_eip++;
245                                 if (instr_mov_greg_to_fsmem(op_regcode_to_greg(reg_eip[-1]>>3U),*(const void **)reg_eip,ucontext)) {
246                                         reg_eip+=4;
247                                         goto ok;
248                                         }
249                                 g_assert_not_reached();
250                                 }
251                         g_assert_not_reached();
252                         }
253                 if (*reg_eip==0xA1) {   /* 'mov %fs:{reg_eip[1..4]},%eax' */
254                         reg_eip++;
255                         if (instr_mov_fsmem_to_greg(*(const void **)reg_eip,REG_EAX,ucontext)) {
256                                 reg_eip+=4;
257                                 goto ok;
258                                 }
259                         g_assert_not_reached();
260                         }
261                 if (*reg_eip==0x8B) {   /* prefix 0x8B */
262                         reg_eip++;
263                         if ((*reg_eip & ~0x38)==0x05) { /* 'mov %fs:{reg_eip[1..4]},%{op_regcode_to_greg(*reg_eip[b3..b5])}' */
264                                 reg_eip++;
265                                 if (instr_mov_fsmem_to_greg(*(const void **)reg_eip,op_regcode_to_greg(reg_eip[-1]>>3U),ucontext)) {
266                                         reg_eip+=4;
267                                         goto ok;
268                                         }
269                                 g_assert_not_reached();
270                                 }
271                         g_assert_not_reached();
272                         }
273                 if (*reg_eip==0xFF) {   /* prefix 0xFF */
274                         reg_eip++;
275                         if (*reg_eip==0x05) {   /* 'incl %fs:{reg_eip[1..4]}' */
276                                 reg_eip++;
277                                 if (instr_incl_fsmem(*(const void **)reg_eip,ucontext)) {
278                                         reg_eip+=4;
279                                         goto ok;
280                                         }
281                                 g_assert_not_reached();
282                                 }
283                         if (*reg_eip==0x35) {   /* 'pushl %fs:{reg_eip[1..4]}' */
284                                 reg_eip++;
285                                 if (instr_push_fsmem(*(const void **)reg_eip,ucontext)) {
286                                         reg_eip+=4;
287                                         goto ok;
288                                         }
289                                 g_assert_not_reached();
290                                 }
291                         g_assert_not_reached();
292                         }
293                 if (*reg_eip==0x8F) {   /* prefix 0x0F */
294                         reg_eip++;
295                         if (*reg_eip==0x05) {   /* 'popl %fs:{reg_eip[1..4]}' */
296                                 reg_eip++;
297                                 if (instr_pop_fsmem(*(const void **)reg_eip,ucontext)) {
298                                         reg_eip+=4;
299                                         goto ok;
300                                         }
301                                 g_assert_not_reached();
302                                 }
303                         g_assert_not_reached();
304                         }
305                 if (*reg_eip==0xC7) {   /* prefix 0xC7 */
306                         reg_eip++;
307                         if (*reg_eip==0x05) {   /* 'movl ${reg_eip[5..8]},%fs:{reg_eip[1..4]}' */
308                                 reg_eip++;
309                                 if (instr_mov_immed_to_fsmem(((greg_t *)reg_eip)[1],*(const void **)reg_eip,ucontext)) {
310                                         reg_eip+=4+4;
311                                         goto ok;
312                                         }
313                                 g_assert_not_reached();
314                                 }
315                         g_assert_not_reached();
316                         }
317                 g_assert_not_reached();
318                 }
319
320         /* all instruction notation comments are written in AT&T 'instr src,dest' syntax! */
321         if (*reg_eip==0x66) {   /* prefix '%fs:' */
322                 reg_eip++;
323                 /* TODO:thread; %fs: is CPU-dependent */
324                 if (*reg_eip==0x8E) {   /* two-byte opcode */
325                         reg_eip++;
326                         if (*reg_eip==0xE3) {   /* 'mov %bx,%fs' */
327                                 reg_eip++;
328                                 g_assert(0x30==(0xFFFF&ucontext->uc_mcontext.gregs[REG_EBX]));
329                                 /* 'reload' of %fs can be ignored */
330                                 goto ok;
331                                 }
332                         g_assert_not_reached();
333                         }
334                 g_assert_not_reached();
335                 }
336
337         if (*reg_eip==0xF4) {   /* hlt; from captive_ModuleList_patch() */
338 struct captive_ModuleList_patchpoint *patchpoint;
339 const gchar *funcname_disabled;
340
341                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: reg_eip=%p; 0xF4 hit",G_STRLOC,reg_eip);
342
343                 if ((funcname_disabled=captive_ModuleList_function_disable_find(
344                                                 reg_eip)))      { /* ExportAddress */
345                         g_error("%s: Reached disabled W32 function: %s",G_STRLOC,funcname_disabled);
346                         g_assert_not_reached();
347                         }
348                 patchpoint=captive_ModuleList_patchpoint_find(
349                                 reg_eip);       /* ExportAddress */
350                 g_assert(patchpoint!=NULL);
351                 if (reg_eip==patchpoint->orig_w32_func) {
352                         g_assert(0xF4 /* hlt */ ==*patchpoint->orig_w32_func);
353                         g_assert(patchpoint->orig_w32_2ndinstr_byte ==*patchpoint->orig_w32_2ndinstr);
354                         if (patchpoint->through_w32_func) {
355                                 *patchpoint->orig_w32_func=patchpoint->orig_w32_func_byte;
356                                 *patchpoint->orig_w32_2ndinstr=0xF4;    /* hlt */
357                                 }
358                         else {  /* !patchpoint->through_w32_func */
359                                 reg_eip=(guint8 *)patchpoint->wrap_wrap_func;
360                                 }
361                         goto ok;
362                         }
363                 if (reg_eip==patchpoint->orig_w32_2ndinstr) {
364                         g_assert(patchpoint->orig_w32_func_byte ==*patchpoint->orig_w32_func);
365                         g_assert(0xF4 /* hlt */ ==*patchpoint->orig_w32_2ndinstr);
366                         g_assert(patchpoint->through_w32_func==TRUE);
367                         *patchpoint->orig_w32_func=0xF4;        /* hlt */
368                         *patchpoint->orig_w32_2ndinstr=patchpoint->orig_w32_2ndinstr_byte;
369                         patchpoint->through_w32_func=FALSE;
370                         goto ok;
371                         }
372                 g_assert_not_reached();
373                 }
374
375         if (*reg_eip==0xFA) {   /* cli */
376                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: reg_eip=%p; CLI neutralized",G_STRLOC,reg_eip);
377                 *reg_eip=0x90;  /* nop */
378                 goto ok;
379                 }
380
381         if (*reg_eip==0xFB) {   /* sti */
382                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: reg_eip=%p; STI neutralized",G_STRLOC,reg_eip);
383                 *reg_eip=0x90;  /* nop */
384                 goto ok;
385                 }
386
387         g_assert_not_reached();
388
389 ok:
390         ucontext->uc_mcontext.gregs[REG_EIP]=(greg_t)reg_eip;
391         /* success */
392 }
393
394 /**
395  * captive_signal_init:
396  *
397  * Initialize UNIX signal handling to be able to emulate foreign W32
398  * instructions. These instructions must be located inside address
399  * space of foreign W32 binary code which is identified by successful
400  * call to captive_mmap_map_get() returning #PROT_EXEC bit set.
401  * This bit should be set from MmAllocateSection() called from
402  * ntoskrnl/ldr/loader.c/LdrPEProcessModule().
403  *
404  * Currently emulated set is the access to %fs register offset %0
405  * where the exception stack top pointer is located.
406  *
407  * Returns: %TRUE if successful.
408  */
409 gboolean captive_signal_init(void)
410 {
411 gint errint;
412 struct sigaction sigaction_struct;
413 sigset_t sigset;
414
415         CAPTIVE_MEMZERO(&sigaction_struct);     /* this structure may have unpredictable fields */
416
417         /* Init 'sigaction_struct.sa_mask'. */
418         errint=sigemptyset(&sigaction_struct.sa_mask);
419         g_return_val_if_fail(errint==0,FALSE);
420         errint=sigaddset(&sigaction_struct.sa_mask,SIGSEGV);
421         g_return_val_if_fail(errint==0,FALSE);
422
423         /* Set the signal sigaction handler. */
424         sigaction_struct.sa_sigaction=(void (*)(int,siginfo_t *,void *))sigaction_SIGSEGV;
425         sigaction_struct.sa_flags=0
426                         |SA_SIGINFO;    /* Use 'sa_sigaction' (not 'sa_handler') */
427         errint=sigaction(SIGSEGV,
428                         &sigaction_struct,      /* act */
429                         NULL);  /* oldact */
430         g_return_val_if_fail(errint==0,FALSE);
431
432         /* Enable SIGSEGV signal (should be default). */
433         errint=sigemptyset(&sigset);
434         g_return_val_if_fail(errint==0,FALSE);
435         errint=sigaddset(&sigset,SIGSEGV);
436         g_return_val_if_fail(errint==0,FALSE);
437         errint=sigprocmask(SIG_UNBLOCK,
438                         &sigset,        /* set */
439                         NULL);  /* oldset */
440         g_return_val_if_fail(errint==0,FALSE);
441
442         return TRUE;
443 }