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