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