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