+support (KPCR+0x51) as KeGetCurrentProcessorNumber()
[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 /**
59  * RtlpDispatchException:
60  * @ExceptionRecord: Ignored by libcaptive.
61  * @Context: Ignored by libcaptive.
62  *
63  * Function definition to prevent inclusion of real RtlpDispatchException() implementation.
64  * Currently libcaptive never raises any exception - fix _abnormal_termination() if it changes.
65  *
66  * Returns: Never returns. Value %0 if it returns although it is impossible.
67  */
68 ULONG RtlpDispatchException(IN PEXCEPTION_RECORD ExceptionRecord,IN PCONTEXT Context)
69 {
70         g_assert_not_reached();
71         g_return_val_if_reached(0);
72 }
73
74
75 /* =='KeGetCurrentKPCR()->ExceptionList';
76  * libcaptive has reduced KPCR (named 'captive_KPCR') which
77  * does not contain this field
78  */
79 static greg_t fs_KPCR_ExceptionList=(greg_t)-1;
80
81 static gboolean instr_mov_greg_to_fsmem(int greg,const void *fsmem,struct ucontext *ucontext)
82 {
83         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
84                 /* moving from %esp is required to pass! */
85                 fs_KPCR_ExceptionList=ucontext->uc_mcontext.gregs[greg];
86                 return TRUE;
87                 }
88         g_return_val_if_reached(FALSE);
89 }
90
91 static gboolean instr_mov_fsmem_to_greg(const void *fsmem,int greg,struct ucontext *ucontext)
92 {
93         if (fsmem==(const void *)0x00000000) {  /* exception stack top pointer */
94                 /* moving to %esp is required to pass! */
95                 ucontext->uc_mcontext.gregs[greg]=fs_KPCR_ExceptionList;
96                 return TRUE;
97                 }
98         if (fsmem==(const void *)0x00000051) {  /* =='KeGetCurrentKPCR()->Number' */
99                 g_return_val_if_fail(greg!=REG_ESP,FALSE);
100                 ucontext->uc_mcontext.gregs[greg]=(greg_t)0;    /* ==libcaptive version of KeGetCurrentProcessorNumber() */
101                 return TRUE;
102                 }
103         if (fsmem==(const void *)0x00000124) {  /* =='KeGetCurrentKPCR()->CurrentThread' */
104                 g_return_val_if_fail(greg!=REG_ESP,FALSE);
105                 ucontext->uc_mcontext.gregs[greg]=(greg_t)captive_KeGetCurrentKPCR()->CurrentThread;
106                 return TRUE;
107                 }
108         g_return_val_if_reached(FALSE);
109 }
110
111 static int op_regcode_to_greg(guint8 regcode)
112 {
113         switch (regcode) {
114                 case 0x00: return REG_EAX;
115                 case 0x01: return REG_ECX;
116                 case 0x02: return REG_EDX;
117                 case 0x03: return REG_EBX;
118                 case 0x04: return REG_ESP;
119                 case 0x05: return REG_EBP;
120                 case 0x06: return REG_ESI;
121                 case 0x07: return REG_EDI;
122                 }
123         g_return_val_if_reached(REG_EAX);
124 }
125
126 static void sigaction_SIGSEGV(int signo,siginfo_t *siginfo,struct ucontext *ucontext)
127 {
128 guint8 *reg_eip;
129 const void *reg_eip_aligned;
130
131         g_return_if_fail(signo==SIGSEGV);
132         g_return_if_fail(siginfo->si_signo==SIGSEGV);
133         /* siginfo->si_code is weird, seen to have value 128 */
134
135         reg_eip=(void *)ucontext->uc_mcontext.gregs[REG_EIP];
136
137         /* 'reg_eip' is not yet PAGE_SIZE-aligned but we need the aligned ptr for captive_mmap_map_get().
138          * glib NOTE: YOU MAY NOT STORE POINTERS IN INTEGERS.
139          */
140         reg_eip_aligned=(const void *)(((char *)reg_eip)-(GPOINTER_TO_UINT(reg_eip)&(PAGE_SIZE-1)));
141         g_assert(reg_eip_aligned!=NULL);
142         g_return_if_fail(!(captive_mmap_map_get(reg_eip_aligned)&PROT_EXEC));
143         
144         /* all instruction notation comments are written in AT&T 'instr src,dest' syntax! */
145         if (*reg_eip==0x64) {   /* prefix '%fs:' */
146                 reg_eip++;
147                 /* TODO:thread; %fs: is CPU-dependent */
148                 if (*reg_eip==0x0F) {   /* two-byte opcode */
149                         reg_eip++;
150                         if (*reg_eip==0xB6) {   /* ??? */
151                                 reg_eip++;
152                                 if (*reg_eip==0x05) {   /* movzbl %fs:{reg_eip[1..4]},%eax */
153                                         reg_eip++;
154                                         if (instr_mov_fsmem_to_greg(*(const void **)reg_eip,REG_EAX,ucontext)) {
155                                                 reg_eip+=4;
156                                                 goto ok;
157                                                 }
158                                         g_assert_not_reached();
159                                         }
160                                 g_assert_not_reached();
161                                 }
162                         g_assert_not_reached();
163                         }
164                 if (*reg_eip==0xA3) {   /* 'mov %eax,%fs:{reg_eip[1..4]}' */
165                         reg_eip++;
166                         if (instr_mov_greg_to_fsmem(REG_EAX,*(const void **)reg_eip,ucontext)) {
167                                 reg_eip+=4;
168                                 goto ok;
169                                 }
170                         g_assert_not_reached();
171                         }
172                 if (*reg_eip==0x89) {   /* prefix 0x89 */
173                         reg_eip++;
174                         if ((*reg_eip & ~0x38)==0x05)   { /* 'mov %{op_regcode_to_greg(*reg_eip[b3..b5])},%fs:{reg_eip[1..4]} */
175                                 reg_eip++;
176                                 if (instr_mov_greg_to_fsmem(op_regcode_to_greg(reg_eip[-1]>>3U),*(const void **)reg_eip,ucontext)) {
177                                         reg_eip+=4;
178                                         goto ok;
179                                         }
180                                 g_assert_not_reached();
181                                 }
182                         g_assert_not_reached();
183                         }
184                 if (*reg_eip==0xA1) {   /* 'mov %fs:{reg_eip[1..4]},%eax' */
185                         reg_eip++;
186                         if (instr_mov_fsmem_to_greg(*(const void **)reg_eip,REG_EAX,ucontext)) {
187                                 reg_eip+=4;
188                                 goto ok;
189                                 }
190                         g_assert_not_reached();
191                         }
192                 if (*reg_eip==0x8B) {   /* prefix 0x8B */
193                         reg_eip++;
194                         if ((*reg_eip & ~0x38)==0x05) { /* 'mov %fs:{reg_eip[1..4]},%{op_regcode_to_greg(*reg_eip[b3..b5])} */
195                                 reg_eip++;
196                                 if (instr_mov_fsmem_to_greg(*(const void **)reg_eip,op_regcode_to_greg(reg_eip[-1]>>3U),ucontext)) {
197                                         reg_eip+=4;
198                                         goto ok;
199                                         }
200                                 g_assert_not_reached();
201                                 }
202                         g_assert_not_reached();
203                         }
204                 g_assert_not_reached();
205                 }
206
207         if (*reg_eip==0xF4) {   /* hlt; from captive_ModuleList_patch() */
208 struct captive_ModuleList_patchpoint *patchpoint;
209 const gchar *funcname_disabled;
210
211                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: reg_eip=%p; 0xF4 hit",G_STRLOC,reg_eip);
212
213                 if ((funcname_disabled=captive_ModuleList_function_disable_find(
214                                                 reg_eip)))      { /* ExportAddress */
215                         g_error("%s: Reached disabled W32 function: %s",G_STRLOC,funcname_disabled);
216                         g_assert_not_reached();
217                         }
218                 patchpoint=captive_ModuleList_patchpoint_find(
219                                 reg_eip);       /* ExportAddress */
220                 g_assert(patchpoint!=NULL);
221                 if (reg_eip==patchpoint->orig_w32_func) {
222                         g_assert(0xF4 /* hlt */ ==*patchpoint->orig_w32_func);
223                         g_assert(patchpoint->orig_w32_2ndinstr_byte ==*patchpoint->orig_w32_2ndinstr);
224                         if (patchpoint->through_w32_func) {
225                                 *patchpoint->orig_w32_func=patchpoint->orig_w32_func_byte;
226                                 *patchpoint->orig_w32_2ndinstr=0xF4;    /* hlt */
227                                 }
228                         else {  /* !patchpoint->through_w32_func */
229                                 reg_eip=(guint8 *)patchpoint->wrap_wrap_func;
230                                 }
231                         goto ok;
232                         }
233                 if (reg_eip==patchpoint->orig_w32_2ndinstr) {
234                         g_assert(patchpoint->orig_w32_func_byte ==*patchpoint->orig_w32_func);
235                         g_assert(0xF4 /* hlt */ ==*patchpoint->orig_w32_2ndinstr);
236                         g_assert(patchpoint->through_w32_func==TRUE);
237                         *patchpoint->orig_w32_func=0xF4;        /* hlt */
238                         *patchpoint->orig_w32_2ndinstr=patchpoint->orig_w32_2ndinstr_byte;
239                         patchpoint->through_w32_func=FALSE;
240                         goto ok;
241                         }
242                 g_assert_not_reached();
243                 }
244
245         if (*reg_eip==0xFA) {   /* cli */
246                 g_log(G_LOG_DOMAIN,G_LOG_LEVEL_DEBUG,"%s: reg_eip=%p; CLI neutralized",G_STRLOC,reg_eip);
247                 *reg_eip=0x90;  /* nop */
248                 goto ok;
249                 }
250
251         g_assert_not_reached();
252
253 ok:
254         ucontext->uc_mcontext.gregs[REG_EIP]=(greg_t)reg_eip;
255         /* success */
256 }
257
258 /**
259  * captive_signal_init:
260  *
261  * Initialize UNIX signal handling to be able to emulate foreign W32
262  * instructions. These instructions must be located inside address
263  * space of foreign W32 binary code which is identified by successful
264  * call to captive_mmap_map_get() returning #PROT_EXEC bit set.
265  * This bit should be set from MmAllocateSection() called from
266  * ntoskrnl/ldr/loader.c/LdrPEProcessModule().
267  *
268  * Currently emulated set is the access to %fs register offset %0
269  * where the exception stack top pointer is located.
270  *
271  * Returns: %TRUE if successful.
272  */
273 gboolean captive_signal_init(void)
274 {
275 gint errint;
276 struct sigaction sigaction_struct;
277 sigset_t sigset;
278
279         CAPTIVE_MEMZERO(&sigaction_struct);     /* this structure may have unpredictable fields */
280
281         /* Init 'sigaction_struct.sa_mask'. */
282         errint=sigemptyset(&sigaction_struct.sa_mask);
283         g_return_val_if_fail(errint==0,FALSE);
284         errint=sigaddset(&sigaction_struct.sa_mask,SIGSEGV);
285         g_return_val_if_fail(errint==0,FALSE);
286
287         /* Set the signal sigaction handler. */
288         sigaction_struct.sa_sigaction=(void (*)(int,siginfo_t *,void *))sigaction_SIGSEGV;
289         sigaction_struct.sa_flags=0
290                         |SA_SIGINFO;    /* Use 'sa_sigaction' (not 'sa_handler') */
291         errint=sigaction(SIGSEGV,
292                         &sigaction_struct,      /* act */
293                         NULL);  /* oldact */
294         g_return_val_if_fail(errint==0,FALSE);
295
296         /* Enable SIGSEGV signal (should be default). */
297         errint=sigemptyset(&sigset);
298         g_return_val_if_fail(errint==0,FALSE);
299         errint=sigaddset(&sigset,SIGSEGV);
300         g_return_val_if_fail(errint==0,FALSE);
301         errint=sigprocmask(SIG_UNBLOCK,
302                         &sigset,        /* set */
303                         NULL);  /* oldset */
304         g_return_val_if_fail(errint==0,FALSE);
305
306         return TRUE;
307 }