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