- Fix handling of text color.
[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 "stackframe.h"
17 #include "debugtools.h"
18 #include "wine/exception.h"
19
20 DEFAULT_DEBUG_CHANNEL(snoop);
21
22 static WINE_EXCEPTION_FILTER(page_fault)
23 {
24     if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
25         GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION)
26         return EXCEPTION_EXECUTE_HANDLER;
27     return EXCEPTION_CONTINUE_SEARCH;
28 }
29
30 char **debug_snoop_excludelist = NULL, **debug_snoop_includelist = NULL;
31
32 #ifdef __i386__
33
34 extern void WINAPI SNOOP_Entry();
35 extern void WINAPI SNOOP_Return();
36
37 #ifdef NEED_UNDERSCORE_PREFIX
38 # define PREFIX "_"
39 #else
40 # define PREFIX
41 #endif
42
43 #include "pshpack1.h"
44
45 typedef struct tagSNOOP_FUN {
46         /* code part */
47         BYTE            lcall;          /* 0xe8 call snoopentry (relative) */
48         /* NOTE: If you move snoopentry OR nrofargs fix the relative offset
49          * calculation!
50          */
51         DWORD           snoopentry;     /* SNOOP_Entry relative */
52         /* unreached */
53         int             nrofargs;
54         FARPROC origfun;
55         char            *name;
56 } SNOOP_FUN;
57
58 typedef struct tagSNOOP_DLL {
59         HMODULE hmod;
60         SNOOP_FUN       *funs;
61         LPCSTR          name;
62         DWORD           ordbase;
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 && !strncasecmp(*listitem, buf, len)) ||
118          (itemlen == len2 && !strncasecmp(*listitem, buf, len2)) ||
119          !strcasecmp(*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 ordbase,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)->ordbase = ordbase;
144         (*dll)->nrofordinals = nrofordinals;
145         (*dll)->name    = HEAP_strdupA(GetProcessHeap(),0,name);
146         if ((s=strrchr((*dll)->name,'.')))
147                 *s='\0';
148         (*dll)->funs = VirtualAlloc(NULL,nrofordinals*sizeof(SNOOP_FUN),MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
149         memset((*dll)->funs,0,nrofordinals*sizeof(SNOOP_FUN));
150         if (!(*dll)->funs) {
151                 HeapFree(GetProcessHeap(),0,*dll);
152                 FIXME("out of memory\n");
153                 return;
154         }
155 }
156
157 FARPROC
158 SNOOP_GetProcAddress(HMODULE hmod,LPCSTR name,DWORD ordinal,FARPROC origfun) {
159         SNOOP_DLL                       *dll = firstdll;
160         SNOOP_FUN                       *fun;
161         int                             j;
162         IMAGE_SECTION_HEADER            *pe_seg = PE_SECTIONS(hmod);
163
164         if (!TRACE_ON(snoop)) return origfun;
165         if (!*(LPBYTE)origfun) /* 0x00 is an imposs. opcode, poss. dataref. */
166                 return origfun;
167         for (j=0;j<PE_HEADER(hmod)->FileHeader.NumberOfSections;j++)
168                 /* 0x42 is special ELF loader tag */
169                 if ((pe_seg[j].VirtualAddress==0x42) ||
170                     (((DWORD)origfun-hmod>=pe_seg[j].VirtualAddress)&&
171                      ((DWORD)origfun-hmod <pe_seg[j].VirtualAddress+
172                                    pe_seg[j].SizeOfRawData
173                    ))
174                 )
175                         break;
176         /* If we looked through all sections (and didn't find one)
177          * or if the sectionname contains "data", we return the
178          * original function since it is most likely a datareference.
179          */
180         if (    (j==PE_HEADER(hmod)->FileHeader.NumberOfSections)       ||
181                 (strstr(pe_seg[j].Name,"data"))                         ||
182                 !(pe_seg[j].Characteristics & IMAGE_SCN_CNT_CODE)
183         )
184                 return origfun;
185
186         while (dll) {
187                 if (hmod == dll->hmod)
188                         break;
189                 dll=dll->next;
190         }
191         if (!dll)       /* probably internal */
192                 return origfun;
193         if (!SNOOP_ShowDebugmsgSnoop(dll->name,ordinal,name))
194                 return origfun;
195         assert(ordinal < dll->nrofordinals);
196         fun = dll->funs+ordinal;
197         if (!fun->name) 
198           {
199             fun->name = HEAP_strdupA(GetProcessHeap(),0,name);
200             fun->lcall  = 0xe8;
201             /* NOTE: origreturn struct member MUST come directly after snoopentry */
202             fun->snoopentry     = (char*)SNOOP_Entry-((char*)(&fun->nrofargs));
203             fun->origfun        = origfun;
204             fun->nrofargs       = -1;
205           }
206         return (FARPROC)&(fun->lcall);
207 }
208
209 static char*
210 SNOOP_PrintArg(DWORD x) {
211         static char     buf[200];
212         int             i,nostring;
213         char * volatile ret=0;
214
215         if ( !HIWORD(x) ) { /* trivial reject to avoid faults */
216             sprintf(buf,"%08lx",x);
217             return buf;
218         }
219         __TRY{
220                 LPBYTE  s=(LPBYTE)x;
221                 i=0;nostring=0;
222                 while (i<80) {
223                         if (s[i]==0) break;
224                         if (s[i]<0x20) {nostring=1;break;}
225                         if (s[i]>=0x80) {nostring=1;break;}
226                         i++;
227                 }
228                 if (!nostring) {
229                         if (i>5) {
230                                 snprintf(buf,sizeof(buf),"%08lx %s",x,debugstr_an((LPSTR)x,sizeof(buf)-10));
231                                 ret=buf;
232                         }
233                 }
234         }
235         __EXCEPT(page_fault){}
236         __ENDTRY
237         if (ret)
238           return ret;
239         __TRY{
240                 LPWSTR  s=(LPWSTR)x;
241                 i=0;nostring=0;
242                 while (i<80) {
243                         if (s[i]==0) break;
244                         if (s[i]<0x20) {nostring=1;break;}
245                         if (s[i]>0x100) {nostring=1;break;}
246                         i++;
247                 }
248                 if (!nostring) {
249                         if (i>5) {
250                                 snprintf(buf,sizeof(buf),"%08lx %s",x,debugstr_wn((LPWSTR)x,sizeof(buf)-10));
251                                 ret=buf;
252                         }
253                 }
254         }
255         __EXCEPT(page_fault){}
256         __ENDTRY
257         if (ret)
258           return ret;
259         sprintf(buf,"%08lx",x);
260         return buf;
261 }
262
263 #define CALLER1REF (*(DWORD*)context->Esp)
264
265 void WINAPI SNOOP_DoEntry( CONTEXT86 *context )
266 {
267         DWORD           ordinal=0,entry = context->Eip - 5;
268         SNOOP_DLL       *dll = firstdll;
269         SNOOP_FUN       *fun = NULL;
270         SNOOP_RETURNENTRIES     **rets = &firstrets;
271         SNOOP_RETURNENTRY       *ret;
272         int             i=0, 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("entrypoint 0x%08lx not found\n",entry);
286                 return; /* oops */
287         }
288         /* guess cdecl ... */
289         if (fun->nrofargs<0) {
290                 /* Typical cdecl return frame is:
291                  *      add esp, xxxxxxxx
292                  * which has (for xxxxxxxx up to 255 the opcode "83 C4 xx".
293                  * (after that 81 C2 xx xx xx xx)
294                  */
295                 LPBYTE  reteip = (LPBYTE)CALLER1REF;
296
297                 if (reteip) {
298                         if ((reteip[0]==0x83)&&(reteip[1]==0xc4))
299                                 fun->nrofargs=reteip[2]/4;
300                 }
301         }
302
303
304         while (*rets) {
305                 for (i=0;i<sizeof((*rets)->entry)/sizeof((*rets)->entry[0]);i++)
306                         if (!(*rets)->entry[i].origreturn)
307                                 break;
308                 if (i!=sizeof((*rets)->entry)/sizeof((*rets)->entry[0]))
309                         break;
310                 rets = &((*rets)->next);
311         }
312         if (!*rets) {
313                 *rets = VirtualAlloc(NULL,4096,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
314                 memset(*rets,0,4096);
315                 i = 0;  /* entry 0 is free */
316         }
317         ret = &((*rets)->entry[i]);
318         ret->lcall      = 0xe8;
319         /* NOTE: origreturn struct member MUST come directly after snoopret */
320         ret->snoopret   = ((char*)SNOOP_Return)-(char*)(&ret->origreturn);
321         ret->origreturn = (FARPROC)CALLER1REF;
322         CALLER1REF      = (DWORD)&ret->lcall;
323         ret->dll        = dll;
324         ret->args       = NULL;
325         ret->ordinal    = ordinal;
326         ret->origESP    = context->Esp;
327
328         context->Eip = (DWORD)fun->origfun;
329
330         DPRINTF("%08lx:CALL %s.%ld: %s(",GetCurrentThreadId(),dll->name,dll->ordbase+ordinal,fun->name);
331         if (fun->nrofargs>0) {
332                 max = fun->nrofargs; if (max>16) max=16;
333                 for (i=0;i<max;i++)
334                         DPRINTF("%s%s",SNOOP_PrintArg(*(DWORD*)(context->Esp + 4 + sizeof(DWORD)*i)),(i<fun->nrofargs-1)?",":"");
335                 if (max!=fun->nrofargs)
336                         DPRINTF(" ...");
337         } else if (fun->nrofargs<0) {
338                 DPRINTF("<unknown, check return>");
339                 ret->args = HeapAlloc(GetProcessHeap(),0,16*sizeof(DWORD));
340                 memcpy(ret->args,(LPBYTE)(context->Esp + 4),sizeof(DWORD)*16);
341         }
342         DPRINTF(") ret=%08lx\n",(DWORD)ret->origreturn);
343 }
344
345
346 void WINAPI SNOOP_DoReturn( CONTEXT86 *context )
347 {
348         SNOOP_RETURNENTRY       *ret = (SNOOP_RETURNENTRY*)(context->Eip - 5);
349
350         /* We haven't found out the nrofargs yet. If we called a cdecl
351          * function it is too late anyway and we can just set '0' (which
352          * will be the difference between orig and current ESP
353          * If stdcall -> everything ok.
354          */
355         if (ret->dll->funs[ret->ordinal].nrofargs<0)
356                 ret->dll->funs[ret->ordinal].nrofargs=(context->Esp - ret->origESP-4)/4;
357         context->Eip = (DWORD)ret->origreturn;
358         if (ret->args) {
359                 int     i,max;
360
361                 DPRINTF("%08lx:RET  %s.%ld: %s(",
362                         GetCurrentThreadId(),
363                         ret->dll->name,ret->dll->ordbase+ret->ordinal,ret->dll->funs[ret->ordinal].name);
364                 max = ret->dll->funs[ret->ordinal].nrofargs;
365                 if (max>16) max=16;
366
367                 for (i=0;i<max;i++)
368                         DPRINTF("%s%s",SNOOP_PrintArg(ret->args[i]),(i<max-1)?",":"");
369                 DPRINTF(") retval = %08lx ret=%08lx\n",
370                         context->Eax,(DWORD)ret->origreturn );
371                 HeapFree(GetProcessHeap(),0,ret->args);
372                 ret->args = NULL;
373         } else
374                 DPRINTF("%08lx:RET  %s.%ld: %s() retval = %08lx ret=%08lx\n",
375                         GetCurrentThreadId(),
376                         ret->dll->name,ret->dll->ordbase+ret->ordinal,ret->dll->funs[ret->ordinal].name,
377                         context->Eax, (DWORD)ret->origreturn);
378         ret->origreturn = NULL; /* mark as empty */
379 }
380
381 /* assembly wrappers that save the context */
382 __ASM_GLOBAL_FUNC( SNOOP_Entry,
383                    "call " __ASM_NAME("CALL32_Regs") "\n\t"
384                    ".long " __ASM_NAME("SNOOP_DoEntry") ",0" );
385 __ASM_GLOBAL_FUNC( SNOOP_Return,
386                    "call " __ASM_NAME("CALL32_Regs") "\n\t"
387                    ".long " __ASM_NAME("SNOOP_DoReturn") ",0" );
388
389 #else   /* !__i386__ */
390 void SNOOP_RegisterDLL(HMODULE hmod,LPCSTR name,DWORD nrofordinals) {
391         if (!TRACE_ON(snoop)) return;
392         FIXME("snooping works only on i386 for now.\n");
393 }
394
395 FARPROC SNOOP_GetProcAddress(HMODULE hmod,LPCSTR name,DWORD ordinal,FARPROC origfun) {
396         return origfun;
397 }
398 #endif  /* !__i386__ */