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