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