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