Align data to proper size.
[wine] / relay32 / snoop.c
1 /*
2  * 386-specific Win32 dll<->dll snooping functions
3  *
4  * Copyright 1998 Marcus Meissner
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.1 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
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include "winternl.h"
28 #include "snoop.h"
29 #include "wine/debug.h"
30 #include "wine/exception.h"
31 #include "excpt.h"
32 #include "ntdll_misc.h"
33
34 WINE_DEFAULT_DEBUG_CHANNEL(snoop);
35 WINE_DECLARE_DEBUG_CHANNEL(seh);
36
37 static WINE_EXCEPTION_FILTER(page_fault)
38 {
39     if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
40         GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION)
41         return EXCEPTION_EXECUTE_HANDLER;
42     return EXCEPTION_CONTINUE_SEARCH;
43 }
44
45 extern const char **debug_snoop_excludelist;
46 extern const char **debug_snoop_includelist;
47
48 #ifdef __i386__
49
50 extern void WINAPI SNOOP_Entry();
51 extern void WINAPI SNOOP_Return();
52
53 #include "pshpack1.h"
54
55 typedef struct tagSNOOP_FUN {
56         /* code part */
57         BYTE            lcall;          /* 0xe8 call snoopentry (relative) */
58         /* NOTE: If you move snoopentry OR nrofargs fix the relative offset
59          * calculation!
60          */
61         DWORD           snoopentry;     /* SNOOP_Entry relative */
62         /* unreached */
63         int             nrofargs;
64         FARPROC origfun;
65         char            *name;
66 } SNOOP_FUN;
67
68 typedef struct tagSNOOP_DLL {
69         HMODULE hmod;
70         SNOOP_FUN       *funs;
71         DWORD           ordbase;
72         DWORD           nrofordinals;
73         struct tagSNOOP_DLL     *next;
74         char name[1];
75 } SNOOP_DLL;
76
77 typedef struct tagSNOOP_RETURNENTRY {
78         /* code part */
79         BYTE            lcall;          /* 0xe8 call snoopret relative*/
80         /* NOTE: If you move snoopret OR origreturn fix the relative offset
81          * calculation!
82          */
83         DWORD           snoopret;       /* SNOOP_Ret relative */
84         /* unreached */
85         FARPROC origreturn;
86         SNOOP_DLL       *dll;
87         DWORD           ordinal;
88         DWORD           origESP;
89         DWORD           *args;          /* saved args across a stdcall */
90 } SNOOP_RETURNENTRY;
91
92 typedef struct tagSNOOP_RETURNENTRIES {
93         SNOOP_RETURNENTRY entry[4092/sizeof(SNOOP_RETURNENTRY)];
94         struct tagSNOOP_RETURNENTRIES   *next;
95 } SNOOP_RETURNENTRIES;
96
97 #include "poppack.h"
98
99 static  SNOOP_DLL               *firstdll = NULL;
100 static  SNOOP_RETURNENTRIES     *firstrets = NULL;
101
102 /***********************************************************************
103  *          SNOOP_ShowDebugmsgSnoop
104  *
105  * Simple function to decide if a particular debugging message is
106  * wanted.
107  */
108 int SNOOP_ShowDebugmsgSnoop(const char *dll, int ord, const char *fname) {
109
110   if(debug_snoop_excludelist || debug_snoop_includelist) {
111     const char **listitem;
112     char buf[80];
113     int len, len2, itemlen, show;
114
115     if(debug_snoop_excludelist) {
116       show = 1;
117       listitem = debug_snoop_excludelist;
118     } else {
119       show = 0;
120       listitem = debug_snoop_includelist;
121     }
122     len = strlen(dll);
123     assert(len < 64);
124     sprintf(buf, "%s.%d", dll, ord);
125     len2 = strlen(buf);
126     for(; *listitem; listitem++) {
127       itemlen = strlen(*listitem);
128       if((itemlen == len && !strncasecmp(*listitem, buf, len)) ||
129          (itemlen == len2 && !strncasecmp(*listitem, buf, len2)) ||
130          !strcasecmp(*listitem, fname)) {
131         show = !show;
132        break;
133       }
134     }
135     return show;
136   }
137   return 1;
138 }
139
140 void
141 SNOOP_RegisterDLL(HMODULE hmod,LPCSTR name,DWORD ordbase,DWORD nrofordinals) {
142         SNOOP_DLL       **dll = &(firstdll);
143         char            *s;
144         void            *addr;
145         SIZE_T          size;
146
147     TRACE("hmod=%p, name=%s, ordbase=%ld, nrofordinals=%ld\n",
148            hmod, name, ordbase, nrofordinals);
149
150         if (!TRACE_ON(snoop)) return;
151         while (*dll) {
152                 if ((*dll)->hmod == hmod)
153                 {
154                     /* another dll, loaded at the same address */
155                     addr = (*dll)->funs;
156                     size = (*dll)->nrofordinals * sizeof(SNOOP_FUN);
157                     NtFreeVirtualMemory(GetCurrentProcess(), &addr, &size, MEM_RELEASE);
158                     break;
159                 }
160                 dll = &((*dll)->next);
161         }
162         *dll = RtlReAllocateHeap(ntdll_get_process_heap(),
163                                  HEAP_ZERO_MEMORY, *dll, 
164                                  sizeof(SNOOP_DLL) + strlen(name));
165         (*dll)->hmod    = hmod;
166         (*dll)->ordbase = ordbase;
167         (*dll)->nrofordinals = nrofordinals;
168         strcpy( (*dll)->name, name );
169         if ((s=strrchr((*dll)->name,'.')))
170                 *s='\0';
171         size = nrofordinals * sizeof(SNOOP_FUN);
172         NtAllocateVirtualMemory(GetCurrentProcess(), &addr, NULL, &size, 
173                                 MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
174         if (!addr) {
175                 RtlFreeHeap(ntdll_get_process_heap(),0,*dll);
176                 FIXME("out of memory\n");
177                 return;
178         }
179         (*dll)->funs = addr;
180         memset((*dll)->funs,0,size);
181 }
182
183 FARPROC
184 SNOOP_GetProcAddress(HMODULE hmod,LPCSTR name,DWORD ordinal,FARPROC origfun) {
185         SNOOP_DLL                       *dll = firstdll;
186         SNOOP_FUN                       *fun;
187         IMAGE_SECTION_HEADER *sec;
188
189         if (!TRACE_ON(snoop)) return origfun;
190         if (!*(LPBYTE)origfun) /* 0x00 is an imposs. opcode, poss. dataref. */
191                 return origfun;
192
193         sec = RtlImageRvaToSection( RtlImageNtHeader(hmod), hmod, (char *)origfun - (char *)hmod );
194
195         if (!sec || !(sec->Characteristics & IMAGE_SCN_CNT_CODE))
196             return origfun;  /* most likely a data reference */
197
198         while (dll) {
199                 if (hmod == dll->hmod)
200                         break;
201                 dll=dll->next;
202         }
203         if (!dll)       /* probably internal */
204                 return origfun;
205         if (!SNOOP_ShowDebugmsgSnoop(dll->name,ordinal,name))
206                 return origfun;
207         assert(ordinal < dll->nrofordinals);
208         fun = dll->funs+ordinal;
209         if (!fun->name)
210           {
211             fun->name = RtlAllocateHeap(ntdll_get_process_heap(),0,strlen(name)+1);
212             strcpy( fun->name, name );
213             fun->lcall  = 0xe8;
214             /* NOTE: origreturn struct member MUST come directly after snoopentry */
215             fun->snoopentry     = (char*)SNOOP_Entry-((char*)(&fun->nrofargs));
216             fun->origfun        = origfun;
217             fun->nrofargs       = -1;
218           }
219         return (FARPROC)&(fun->lcall);
220 }
221
222 static void SNOOP_PrintArg(DWORD x)
223 {
224     int i,nostring;
225
226     DPRINTF("%08lx",x);
227     if (!HIWORD(x) || TRACE_ON(seh)) return; /* trivial reject to avoid faults */
228     __TRY
229     {
230         LPBYTE s=(LPBYTE)x;
231         i=0;nostring=0;
232         while (i<80) {
233             if (s[i]==0) break;
234             if (s[i]<0x20) {nostring=1;break;}
235             if (s[i]>=0x80) {nostring=1;break;}
236             i++;
237         }
238         if (!nostring && i > 5)
239             DPRINTF(" %s",debugstr_an((LPSTR)x,i));
240         else  /* try unicode */
241         {
242             LPWSTR s=(LPWSTR)x;
243             i=0;nostring=0;
244             while (i<80) {
245                 if (s[i]==0) break;
246                 if (s[i]<0x20) {nostring=1;break;}
247                 if (s[i]>0x100) {nostring=1;break;}
248                 i++;
249             }
250             if (!nostring && i > 5) DPRINTF(" %s",debugstr_wn((LPWSTR)x,i));
251         }
252     }
253     __EXCEPT(page_fault)
254     {
255     }
256     __ENDTRY
257 }
258
259 #define CALLER1REF (*(DWORD*)context->Esp)
260
261 void WINAPI SNOOP_DoEntry( CONTEXT86 *context )
262 {
263         DWORD           ordinal=0,entry = context->Eip - 5;
264         SNOOP_DLL       *dll = firstdll;
265         SNOOP_FUN       *fun = NULL;
266         SNOOP_RETURNENTRIES     **rets = &firstrets;
267         SNOOP_RETURNENTRY       *ret;
268         int             i=0, max;
269
270         while (dll) {
271                 if (    ((char*)entry>=(char*)dll->funs)        &&
272                         ((char*)entry<=(char*)(dll->funs+dll->nrofordinals))
273                 ) {
274                         fun = (SNOOP_FUN*)entry;
275                         ordinal = fun-dll->funs;
276                         break;
277                 }
278                 dll=dll->next;
279         }
280         if (!dll) {
281                 FIXME("entrypoint 0x%08lx not found\n",entry);
282                 return; /* oops */
283         }
284         /* guess cdecl ... */
285         if (fun->nrofargs<0) {
286                 /* Typical cdecl return frame is:
287                  *      add esp, xxxxxxxx
288                  * which has (for xxxxxxxx up to 255 the opcode "83 C4 xx".
289                  * (after that 81 C2 xx xx xx xx)
290                  */
291                 LPBYTE  reteip = (LPBYTE)CALLER1REF;
292
293                 if (reteip) {
294                         if ((reteip[0]==0x83)&&(reteip[1]==0xc4))
295                                 fun->nrofargs=reteip[2]/4;
296                 }
297         }
298
299
300         while (*rets) {
301                 for (i=0;i<sizeof((*rets)->entry)/sizeof((*rets)->entry[0]);i++)
302                         if (!(*rets)->entry[i].origreturn)
303                                 break;
304                 if (i!=sizeof((*rets)->entry)/sizeof((*rets)->entry[0]))
305                         break;
306                 rets = &((*rets)->next);
307         }
308         if (!*rets) {
309                 SIZE_T size = 4096;
310                 VOID* addr;
311
312                 NtAllocateVirtualMemory(GetCurrentProcess(), &addr, NULL, &size, 
313                                         MEM_COMMIT | MEM_RESERVE,
314                                         PAGE_EXECUTE_READWRITE);
315                 if (!addr) return;
316                 *rets = addr;
317                 memset(*rets,0,4096);
318                 i = 0;  /* entry 0 is free */
319         }
320         ret = &((*rets)->entry[i]);
321         ret->lcall      = 0xe8;
322         /* NOTE: origreturn struct member MUST come directly after snoopret */
323         ret->snoopret   = ((char*)SNOOP_Return)-(char*)(&ret->origreturn);
324         ret->origreturn = (FARPROC)CALLER1REF;
325         CALLER1REF      = (DWORD)&ret->lcall;
326         ret->dll        = dll;
327         ret->args       = NULL;
328         ret->ordinal    = ordinal;
329         ret->origESP    = context->Esp;
330
331         context->Eip = (DWORD)fun->origfun;
332
333         DPRINTF("%04lx:CALL %s.%ld: %s(",GetCurrentThreadId(),dll->name,dll->ordbase+ordinal,fun->name);
334         if (fun->nrofargs>0) {
335                 max = fun->nrofargs; if (max>16) max=16;
336                 for (i=0;i<max;i++)
337                 {
338                     SNOOP_PrintArg(*(DWORD*)(context->Esp + 4 + sizeof(DWORD)*i));
339                     if (i<fun->nrofargs-1) DPRINTF(",");
340                 }
341                 if (max!=fun->nrofargs)
342                         DPRINTF(" ...");
343         } else if (fun->nrofargs<0) {
344                 DPRINTF("<unknown, check return>");
345                 ret->args = RtlAllocateHeap(ntdll_get_process_heap(),
346                                             0,16*sizeof(DWORD));
347                 memcpy(ret->args,(LPBYTE)(context->Esp + 4),sizeof(DWORD)*16);
348         }
349         DPRINTF(") ret=%08lx\n",(DWORD)ret->origreturn);
350 }
351
352
353 void WINAPI SNOOP_DoReturn( CONTEXT86 *context )
354 {
355         SNOOP_RETURNENTRY       *ret = (SNOOP_RETURNENTRY*)(context->Eip - 5);
356
357         /* We haven't found out the nrofargs yet. If we called a cdecl
358          * function it is too late anyway and we can just set '0' (which
359          * will be the difference between orig and current ESP
360          * If stdcall -> everything ok.
361          */
362         if (ret->dll->funs[ret->ordinal].nrofargs<0)
363                 ret->dll->funs[ret->ordinal].nrofargs=(context->Esp - ret->origESP-4)/4;
364         context->Eip = (DWORD)ret->origreturn;
365         if (ret->args) {
366                 int     i,max;
367
368                 DPRINTF("%04lx:RET  %s.%ld: %s(",
369                         GetCurrentThreadId(),
370                         ret->dll->name,ret->dll->ordbase+ret->ordinal,ret->dll->funs[ret->ordinal].name);
371                 max = ret->dll->funs[ret->ordinal].nrofargs;
372                 if (max>16) max=16;
373
374                 for (i=0;i<max;i++)
375                 {
376                     SNOOP_PrintArg(ret->args[i]);
377                     if (i<max-1) DPRINTF(",");
378                 }
379                 DPRINTF(") retval = %08lx ret=%08lx\n",
380                         context->Eax,(DWORD)ret->origreturn );
381                 RtlFreeHeap(ntdll_get_process_heap(),0,ret->args);
382                 ret->args = NULL;
383         } else
384                 DPRINTF("%04lx:RET  %s.%ld: %s() retval = %08lx ret=%08lx\n",
385                         GetCurrentThreadId(),
386                         ret->dll->name,ret->dll->ordbase+ret->ordinal,ret->dll->funs[ret->ordinal].name,
387                         context->Eax, (DWORD)ret->origreturn);
388         ret->origreturn = NULL; /* mark as empty */
389 }
390
391 /* assembly wrappers that save the context */
392 __ASM_GLOBAL_FUNC( SNOOP_Entry,
393                    "call " __ASM_NAME("__wine_call_from_32_regs") "\n\t"
394                    ".long " __ASM_NAME("SNOOP_DoEntry") ",0" );
395 __ASM_GLOBAL_FUNC( SNOOP_Return,
396                    "call " __ASM_NAME("__wine_call_from_32_regs") "\n\t"
397                    ".long " __ASM_NAME("SNOOP_DoReturn") ",0" );
398
399 #else   /* !__i386__ */
400 void SNOOP_RegisterDLL(HMODULE hmod,LPCSTR name,DWORD nrofordinals, DWORD dw) {
401         if (!TRACE_ON(snoop)) return;
402         FIXME("snooping works only on i386 for now.\n");
403 }
404
405 FARPROC SNOOP_GetProcAddress(HMODULE hmod,LPCSTR name,DWORD ordinal,FARPROC origfun) {
406         return origfun;
407 }
408 #endif  /* !__i386__ */