Add stubbed IGraphConfig interface to the filtergraph.
[wine] / dlls / ntdll / relay.c
1 /*
2  * Win32 relay and snoop functions
3  *
4  * Copyright 1997 Alexandre Julliard
5  * Copyright 1998 Marcus Meissner
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #include <stdio.h>
29
30 #include "windef.h"
31 #include "winternl.h"
32 #include "excpt.h"
33 #include "wine/exception.h"
34 #include "ntdll_misc.h"
35 #include "wine/unicode.h"
36 #include "wine/debug.h"
37
38 WINE_DEFAULT_DEBUG_CHANNEL(relay);
39 WINE_DECLARE_DEBUG_CHANNEL(snoop);
40 WINE_DECLARE_DEBUG_CHANNEL(seh);
41
42 #ifdef __i386__
43
44 static const WCHAR **debug_relay_excludelist;
45 static const WCHAR **debug_relay_includelist;
46 static const WCHAR **debug_snoop_excludelist;
47 static const WCHAR **debug_snoop_includelist;
48 static const WCHAR **debug_from_relay_excludelist;
49 static const WCHAR **debug_from_relay_includelist;
50 static const WCHAR **debug_from_snoop_excludelist;
51 static const WCHAR **debug_from_snoop_includelist;
52
53 static BOOL init_done;
54
55 /* compare an ASCII and a Unicode string without depending on the current codepage */
56 inline static int strcmpAW( const char *strA, const WCHAR *strW )
57 {
58     while (*strA && ((unsigned char)*strA == *strW)) { strA++; strW++; }
59     return (unsigned char)*strA - *strW;
60 }
61
62 /* compare an ASCII and a Unicode string without depending on the current codepage */
63 inline static int strncmpiAW( const char *strA, const WCHAR *strW, int n )
64 {
65     int ret = 0;
66     for ( ; n > 0; n--, strA++, strW++)
67         if ((ret = toupperW((unsigned char)*strA) - toupperW(*strW)) || !*strA) break;
68     return ret;
69 }
70
71 /***********************************************************************
72  *           build_list
73  *
74  * Build a function list from a ';'-separated string.
75  */
76 static const WCHAR **build_list( const WCHAR *buffer )
77 {
78     int count = 1;
79     const WCHAR *p = buffer;
80     const WCHAR **ret;
81
82     while ((p = strchrW( p, ';' )))
83     {
84         count++;
85         p++;
86     }
87     /* allocate count+1 pointers, plus the space for a copy of the string */
88     if ((ret = RtlAllocateHeap( GetProcessHeap(), 0,
89                                 (count+1) * sizeof(WCHAR*) + (strlenW(buffer)+1) * sizeof(WCHAR) )))
90     {
91         WCHAR *str = (WCHAR *)(ret + count + 1);
92         WCHAR *p = str;
93
94         strcpyW( str, buffer );
95         count = 0;
96         for (;;)
97         {
98             ret[count++] = p;
99             if (!(p = strchrW( p, ';' ))) break;
100             *p++ = 0;
101         }
102         ret[count++] = NULL;
103     }
104     return ret;
105 }
106
107
108 /***********************************************************************
109  *           init_debug_lists
110  *
111  * Build the relay include/exclude function lists.
112  */
113 static void init_debug_lists(void)
114 {
115     OBJECT_ATTRIBUTES attr;
116     UNICODE_STRING name;
117     char buffer[1024];
118     HANDLE root, hkey;
119     DWORD count;
120     WCHAR *str;
121     static const WCHAR configW[] = {'S','o','f','t','w','a','r','e','\\',
122                                     'W','i','n','e','\\',
123                                     'D','e','b','u','g',0};
124     static const WCHAR RelayIncludeW[] = {'R','e','l','a','y','I','n','c','l','u','d','e',0};
125     static const WCHAR RelayExcludeW[] = {'R','e','l','a','y','E','x','c','l','u','d','e',0};
126     static const WCHAR SnoopIncludeW[] = {'S','n','o','o','p','I','n','c','l','u','d','e',0};
127     static const WCHAR SnoopExcludeW[] = {'S','n','o','o','p','E','x','c','l','u','d','e',0};
128     static const WCHAR RelayFromIncludeW[] = {'R','e','l','a','y','F','r','o','m','I','n','c','l','u','d','e',0};
129     static const WCHAR RelayFromExcludeW[] = {'R','e','l','a','y','F','r','o','m','E','x','c','l','u','d','e',0};
130     static const WCHAR SnoopFromIncludeW[] = {'S','n','o','o','p','F','r','o','m','I','n','c','l','u','d','e',0};
131     static const WCHAR SnoopFromExcludeW[] = {'S','n','o','o','p','F','r','o','m','E','x','c','l','u','d','e',0};
132
133     if (init_done) return;
134     init_done = TRUE;
135
136     RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
137     attr.Length = sizeof(attr);
138     attr.RootDirectory = root;
139     attr.ObjectName = &name;
140     attr.Attributes = 0;
141     attr.SecurityDescriptor = NULL;
142     attr.SecurityQualityOfService = NULL;
143     RtlInitUnicodeString( &name, configW );
144
145     /* @@ Wine registry key: HKCU\Software\Wine\Debug */
146     if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr )) hkey = 0;
147     NtClose( root );
148     if (!hkey) return;
149
150     str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)buffer)->Data;
151     RtlInitUnicodeString( &name, RelayIncludeW );
152     if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
153     {
154         TRACE("RelayInclude = %s\n", debugstr_w(str) );
155         debug_relay_includelist = build_list( str );
156     }
157
158     RtlInitUnicodeString( &name, RelayExcludeW );
159     if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
160     {
161         TRACE( "RelayExclude = %s\n", debugstr_w(str) );
162         debug_relay_excludelist = build_list( str );
163     }
164
165     RtlInitUnicodeString( &name, SnoopIncludeW );
166     if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
167     {
168         TRACE_(snoop)( "SnoopInclude = %s\n", debugstr_w(str) );
169         debug_snoop_includelist = build_list( str );
170     }
171
172     RtlInitUnicodeString( &name, SnoopExcludeW );
173     if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
174     {
175         TRACE_(snoop)( "SnoopExclude = %s\n", debugstr_w(str) );
176         debug_snoop_excludelist = build_list( str );
177     }
178
179     RtlInitUnicodeString( &name, RelayFromIncludeW );
180     if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
181     {
182         TRACE("RelayFromInclude = %s\n", debugstr_w(str) );
183         debug_from_relay_includelist = build_list( str );
184     }
185
186     RtlInitUnicodeString( &name, RelayFromExcludeW );
187     if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
188     {
189         TRACE( "RelayFromExclude = %s\n", debugstr_w(str) );
190         debug_from_relay_excludelist = build_list( str );
191     }
192
193     RtlInitUnicodeString( &name, SnoopFromIncludeW );
194     if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
195     {
196         TRACE_(snoop)("SnoopFromInclude = %s\n", debugstr_w(str) );
197         debug_from_snoop_includelist = build_list( str );
198     }
199
200     RtlInitUnicodeString( &name, SnoopFromExcludeW );
201     if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
202     {
203         TRACE_(snoop)( "SnoopFromExclude = %s\n", debugstr_w(str) );
204         debug_from_snoop_excludelist = build_list( str );
205     }
206
207     NtClose( hkey );
208 }
209
210
211 #include "pshpack1.h"
212
213 typedef struct
214 {
215     BYTE          call;         /* 0xe8 call callfrom32 (relative) */
216     DWORD         callfrom32;   /* RELAY_CallFrom32 relative addr */
217     BYTE          ret;          /* 0xc2 ret $n  or  0xc3 ret */
218     WORD          args;         /* nb of args to remove from the stack */
219     void         *orig;         /* original entry point */
220     DWORD         argtypes;     /* argument types */
221 } DEBUG_ENTRY_POINT;
222
223 typedef struct
224 {
225         /* code part */
226         BYTE            lcall;          /* 0xe8 call snoopentry (relative) */
227         /* NOTE: If you move snoopentry OR nrofargs fix the relative offset
228          * calculation!
229          */
230         DWORD           snoopentry;     /* SNOOP_Entry relative */
231         /* unreached */
232         int             nrofargs;
233         FARPROC origfun;
234         const char *name;
235 } SNOOP_FUN;
236
237 typedef struct tagSNOOP_DLL {
238         HMODULE hmod;
239         SNOOP_FUN       *funs;
240         DWORD           ordbase;
241         DWORD           nrofordinals;
242         struct tagSNOOP_DLL     *next;
243         char name[1];
244 } SNOOP_DLL;
245
246 typedef struct
247 {
248         /* code part */
249         BYTE            lcall;          /* 0xe8 call snoopret relative*/
250         /* NOTE: If you move snoopret OR origreturn fix the relative offset
251          * calculation!
252          */
253         DWORD           snoopret;       /* SNOOP_Ret relative */
254         /* unreached */
255         FARPROC origreturn;
256         SNOOP_DLL       *dll;
257         DWORD           ordinal;
258         DWORD           origESP;
259         DWORD           *args;          /* saved args across a stdcall */
260 } SNOOP_RETURNENTRY;
261
262 typedef struct tagSNOOP_RETURNENTRIES {
263         SNOOP_RETURNENTRY entry[4092/sizeof(SNOOP_RETURNENTRY)];
264         struct tagSNOOP_RETURNENTRIES   *next;
265 } SNOOP_RETURNENTRIES;
266
267 #include "poppack.h"
268
269 extern void WINAPI SNOOP_Entry();
270 extern void WINAPI SNOOP_Return();
271
272 static SNOOP_DLL *firstdll;
273 static SNOOP_RETURNENTRIES *firstrets;
274
275 static WINE_EXCEPTION_FILTER(page_fault)
276 {
277     if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
278         GetExceptionCode() == EXCEPTION_PRIV_INSTRUCTION)
279         return EXCEPTION_EXECUTE_HANDLER;
280     return EXCEPTION_CONTINUE_SEARCH;
281 }
282
283 /***********************************************************************
284  *           check_list
285  *
286  * Check if a given module and function is in the list.
287  */
288 static BOOL check_list( const char *module, int ordinal, const char *func, const WCHAR **list )
289 {
290     char ord_str[10];
291
292     sprintf( ord_str, "%d", ordinal );
293     for(; *list; list++)
294     {
295         const WCHAR *p = strrchrW( *list, '.' );
296         if (p && p > *list)  /* check module and function */
297         {
298             int len = p - *list;
299             if (strncmpiAW( module, *list, len-1 ) || module[len]) continue;
300             if (p[1] == '*' && !p[2]) return TRUE;
301             if (!strcmpAW( ord_str, p + 1 )) return TRUE;
302             if (func && !strcmpAW( func, p + 1 )) return TRUE;
303         }
304         else  /* function only */
305         {
306             if (func && !strcmpAW( func, *list )) return TRUE;
307         }
308     }
309     return FALSE;
310 }
311
312
313 /***********************************************************************
314  *           check_relay_include
315  *
316  * Check if a given function must be included in the relay output.
317  */
318 static BOOL check_relay_include( const char *module, int ordinal, const char *func )
319 {
320     if (debug_relay_excludelist && check_list( module, ordinal, func, debug_relay_excludelist ))
321         return FALSE;
322     if (debug_relay_includelist && !check_list( module, ordinal, func, debug_relay_includelist ))
323         return FALSE;
324     return TRUE;
325 }
326
327 /***********************************************************************
328  *           check_from_module
329  *
330  * Check if calls from a given module must be included in the relay/snoop output,
331  * given the exclusion and inclusion lists.
332  */
333 static BOOL check_from_module( const WCHAR **includelist, const WCHAR **excludelist, const WCHAR *module )
334 {
335     static const WCHAR dllW[] = {'.','d','l','l',0 };
336     const WCHAR **listitem;
337     BOOL show;
338
339     if (!module) return TRUE;
340     if (!includelist && !excludelist) return TRUE;
341     if (excludelist)
342     {
343         show = TRUE;
344         listitem = excludelist;
345     }
346     else
347     {
348         show = FALSE;
349         listitem = includelist;
350     }
351     for(; *listitem; listitem++)
352     {
353         int len;
354
355         if (!strcmpiW( *listitem, module )) return !show;
356         len = strlenW( *listitem );
357         if (!strncmpiW( *listitem, module, len ) && !strcmpiW( module + len, dllW ))
358             return !show;
359     }
360     return show;
361 }
362
363 /***********************************************************************
364  *           find_exported_name
365  *
366  * Find the name of an exported function.
367  */
368 static const char *find_exported_name( HMODULE module,
369                                        IMAGE_EXPORT_DIRECTORY *exp, int ordinal )
370 {
371     unsigned int i;
372     const char *ret = NULL;
373
374     WORD *ordptr = (WORD *)((char *)module + exp->AddressOfNameOrdinals);
375     for (i = 0; i < exp->NumberOfNames; i++, ordptr++)
376         if (*ordptr + exp->Base == ordinal) break;
377     if (i < exp->NumberOfNames)
378         ret = (char *)module + ((DWORD*)((char *)module + exp->AddressOfNames))[i];
379     return ret;
380 }
381
382
383 /***********************************************************************
384  *           get_entry_point
385  *
386  * Get the name of the DLL entry point corresponding to a relay address.
387  */
388 static void get_entry_point( char *buffer, DEBUG_ENTRY_POINT *relay )
389 {
390     IMAGE_EXPORT_DIRECTORY *exp = NULL;
391     DEBUG_ENTRY_POINT *debug;
392     char *p;
393     const char *name;
394     int ordinal = 0;
395     PLIST_ENTRY mark, entry;
396     PLDR_MODULE mod = NULL;
397     DWORD size;
398
399     /* First find the module */
400
401     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
402     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
403     {
404         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
405         if (!(mod->Flags & LDR_WINE_INTERNAL)) continue;
406         exp = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size );
407         if (!exp) continue;
408         debug = (DEBUG_ENTRY_POINT *)((char *)exp + size);
409         if (debug <= relay && relay < debug + exp->NumberOfFunctions)
410         {
411             ordinal = relay - debug;
412             break;
413         }
414     }
415
416     /* Now find the function */
417
418     strcpy( buffer, (char *)mod->BaseAddress + exp->Name );
419     p = buffer + strlen(buffer);
420     if (p > buffer + 4 && !strcasecmp( p - 4, ".dll" )) p -= 4;
421
422     if ((name = find_exported_name( mod->BaseAddress, exp, ordinal + exp->Base )))
423         sprintf( p, ".%s", name );
424     else
425         sprintf( p, ".%ld", ordinal + exp->Base );
426 }
427
428
429 /***********************************************************************
430  *           RELAY_PrintArgs
431  */
432 static inline void RELAY_PrintArgs( int *args, int nb_args, unsigned int typemask )
433 {
434     while (nb_args--)
435     {
436         if ((typemask & 3) && HIWORD(*args))
437         {
438             if (typemask & 2)
439                 DPRINTF( "%08x %s", *args, debugstr_w((LPWSTR)*args) );
440             else
441                 DPRINTF( "%08x %s", *args, debugstr_a((LPCSTR)*args) );
442         }
443         else DPRINTF( "%08x", *args );
444         if (nb_args) DPRINTF( "," );
445         args++;
446         typemask >>= 2;
447     }
448 }
449
450 extern LONGLONG call_entry_point( void *func, int nb_args, const int *args );
451 __ASM_GLOBAL_FUNC( call_entry_point,
452                    "\tpushl %ebp\n"
453                    "\tmovl %esp,%ebp\n"
454                    "\tmovl 12(%ebp),%ecx\n"
455                    "\tmovl 16(%ebp),%edx\n"
456                    "\tjecxz 1f\n"
457                    "2:\tpushl -4(%edx,%ecx,4)\n"
458                    "\tloop 2b\n"
459                    "1:\tcall *8(%ebp)\n"
460                    "\tmovl %ebp,%esp\n"
461                    "\tleave\n"
462                    "\tret" );
463
464
465 /***********************************************************************
466  *           RELAY_CallFrom32
467  *
468  * Stack layout on entry to this function:
469  *  ...      ...
470  * (esp+12)  arg2
471  * (esp+8)   arg1
472  * (esp+4)   ret_addr
473  * (esp)     return addr to relay code
474  */
475 static LONGLONG RELAY_CallFrom32( int ret_addr, ... )
476 {
477     LONGLONG ret;
478     char buffer[80];
479
480     int *args = &ret_addr + 1;
481     /* Relay addr is the return address for this function */
482     BYTE *relay_addr = (BYTE *)__builtin_return_address(0);
483     DEBUG_ENTRY_POINT *relay = (DEBUG_ENTRY_POINT *)(relay_addr - 5);
484     WORD nb_args = relay->args / sizeof(int);
485
486     if (TRACE_ON(relay))
487     {
488         get_entry_point( buffer, relay );
489
490         DPRINTF( "%04lx:Call %s(", GetCurrentThreadId(), buffer );
491         RELAY_PrintArgs( args, nb_args, relay->argtypes );
492         DPRINTF( ") ret=%08x\n", ret_addr );
493     }
494
495     ret = call_entry_point( relay->orig, nb_args, args );
496
497     if (TRACE_ON(relay))
498     {
499         BOOL ret64 = (relay->argtypes & 0x80000000) && (nb_args < 16);
500         if (ret64)
501             DPRINTF( "%04lx:Ret  %s() retval=%08x%08x ret=%08x\n",
502                      GetCurrentThreadId(),
503                      buffer, (UINT)(ret >> 32), (UINT)ret, ret_addr );
504         else
505             DPRINTF( "%04lx:Ret  %s() retval=%08x ret=%08x\n",
506                      GetCurrentThreadId(),
507                      buffer, (UINT)ret, ret_addr );
508     }
509     return ret;
510 }
511
512
513 /***********************************************************************
514  *           RELAY_CallFrom32Regs
515  *
516  * Stack layout (esp is context->Esp, not the current %esp):
517  *
518  * ...
519  * (esp+4) first arg
520  * (esp)   return addr to caller
521  * (esp-4) return addr to DEBUG_ENTRY_POINT
522  * (esp-8) ptr to relay entry code for RELAY_CallFrom32Regs
523  *  ...    >128 bytes space free to be modified (ensured by the assembly glue)
524  */
525 void WINAPI __regs_RELAY_CallFrom32Regs( CONTEXT86 *context )
526 {
527     char buffer[80];
528     int* args;
529     int args_copy[17];
530     BYTE *entry_point;
531
532     BYTE *relay_addr = *((BYTE **)context->Esp - 1);
533     DEBUG_ENTRY_POINT *relay = (DEBUG_ENTRY_POINT *)(relay_addr - 5);
534     WORD nb_args = relay->args / sizeof(int);
535
536     /* remove extra stuff from the stack */
537     context->Eip = *(DWORD *)context->Esp;
538     context->Esp += sizeof(DWORD);
539     args = (int *)context->Esp;
540     if (relay->ret == 0xc2) /* stdcall */
541         context->Esp += nb_args * sizeof(int);
542
543     entry_point = (BYTE *)relay->orig;
544     assert( *entry_point == 0xe8 /* lcall */ );
545
546     if (TRACE_ON(relay))
547     {
548         get_entry_point( buffer, relay );
549
550         DPRINTF( "%04lx:Call %s(", GetCurrentThreadId(), buffer );
551         RELAY_PrintArgs( args, nb_args, relay->argtypes );
552         DPRINTF( ") ret=%08lx fs=%04lx\n", context->Eip, context->SegFs );
553
554         DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
555                 context->Eax, context->Ebx, context->Ecx,
556                 context->Edx, context->Esi, context->Edi );
557         DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx gs=%04lx flags=%08lx\n",
558                 context->Ebp, context->Esp, context->SegDs,
559                 context->SegEs, context->SegGs, context->EFlags );
560     }
561
562     /* Now call the real function */
563
564     memcpy( args_copy, args, nb_args * sizeof(args[0]) );
565     args_copy[nb_args] = (int)context;  /* append context argument */
566
567     call_entry_point( (entry_point + 5 + *(DWORD *)(entry_point + 5)), nb_args+1, args_copy );
568
569     if (TRACE_ON(relay))
570     {
571         DPRINTF( "%04lx:Ret  %s() retval=%08lx ret=%08lx fs=%04lx\n",
572                  GetCurrentThreadId(),
573                  buffer, context->Eax, context->Eip, context->SegFs );
574
575         DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
576                 context->Eax, context->Ebx, context->Ecx,
577                 context->Edx, context->Esi, context->Edi );
578         DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx gs=%04lx flags=%08lx\n",
579                 context->Ebp, context->Esp, context->SegDs,
580                 context->SegEs, context->SegGs, context->EFlags );
581     }
582 }
583
584 void WINAPI RELAY_CallFrom32Regs(void);
585 DEFINE_REGS_ENTRYPOINT( RELAY_CallFrom32Regs, 0, 0 );
586
587 /* check whether the function at addr starts with a call to __wine_call_from_32_regs */
588 static BOOL is_register_entry_point( const BYTE *addr )
589 {
590     extern void __wine_call_from_32_regs();
591     const int *offset;
592     const void *ptr;
593
594     if (*addr != 0xe8) return FALSE;  /* not a call */
595     /* check if call target is __wine_call_from_32_regs */
596     offset = (const int *)(addr + 1);
597     if (*offset == (const char *)__wine_call_from_32_regs - (const char *)(offset + 1)) return TRUE;
598     /* now check if call target is an import table jump to __wine_call_from_32_regs */
599     addr = (const BYTE *)(offset + 1) + *offset;
600
601     /* Note: the following checks depend on the asm code generated by winebuild */
602
603     if (addr[0] == 0xff && addr[1] == 0x25)  /* indirect jmp */
604     {
605         ptr = *(const void * const*)(addr + 2);  /* get indirect jmp target address */
606     }
607     else  /* check for import thunk */
608     {
609         if (addr[0] != 0x50) return FALSE;  /* pushl %eax */
610         if (addr[1] != 0xe8 || addr[2] || addr[3] || addr[4] || addr[5]) return FALSE;  /* call .+0 */
611         if (addr[6] != 0x58) return FALSE;  /* popl %eax */
612         if (addr[7] != 0x8b || addr[8] != 0x80) return FALSE;  /* movl offset(%eax),%eax */
613         ptr = addr + 6 + *(const int *)(addr + 9);
614     }
615     return (*(const char * const*)ptr == (char *)__wine_call_from_32_regs);
616 }
617
618
619 /***********************************************************************
620  *           RELAY_GetProcAddress
621  *
622  * Return the proc address to use for a given function.
623  */
624 FARPROC RELAY_GetProcAddress( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
625                               DWORD exp_size, FARPROC proc, const WCHAR *user )
626 {
627     const DEBUG_ENTRY_POINT *debug = (DEBUG_ENTRY_POINT *)proc;
628     const DEBUG_ENTRY_POINT *list = (const DEBUG_ENTRY_POINT *)((const char *)exports + exp_size);
629
630     if (debug < list || debug >= list + exports->NumberOfFunctions) return proc;
631     if (list + (debug - list) != debug) return proc;  /* not a valid address */
632     if (check_from_module( debug_from_relay_includelist, debug_from_relay_excludelist, user ))
633        return proc;  /* we want to relay it */
634     if (!debug->call) return proc;  /* not a normal function */
635     if (debug->call != 0xe8 && debug->call != 0xe9) return proc; /* not a debug thunk at all */
636     return debug->orig;
637 }
638
639
640 /***********************************************************************
641  *           RELAY_SetupDLL
642  *
643  * Setup relay debugging for a built-in dll.
644  */
645 void RELAY_SetupDLL( HMODULE module )
646 {
647     IMAGE_EXPORT_DIRECTORY *exports;
648     DEBUG_ENTRY_POINT *debug;
649     DWORD *funcs;
650     unsigned int i;
651     const char *name;
652     char *p, dllname[80];
653     DWORD size;
654
655     if (!init_done) init_debug_lists();
656
657     exports = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size );
658     if (!exports) return;
659     debug = (DEBUG_ENTRY_POINT *)((char *)exports + size);
660     funcs = (DWORD *)((char *)module + exports->AddressOfFunctions);
661     strcpy( dllname, (char *)module + exports->Name );
662     p = dllname + strlen(dllname) - 4;
663     if (p > dllname && !strcasecmp( p, ".dll" )) *p = 0;
664
665     for (i = 0; i < exports->NumberOfFunctions; i++, funcs++, debug++)
666     {
667         int on = 1;
668
669         if (!debug->call) continue;  /* not a normal function */
670         if (debug->call != 0xe8 && debug->call != 0xe9) break; /* not a debug thunk at all */
671
672         name = find_exported_name( module, exports, i + exports->Base );
673         on = check_relay_include( dllname, i + exports->Base, name );
674
675         if (on)
676         {
677             debug->call = 0xe8;  /* call relative */
678             if (is_register_entry_point( debug->orig ))
679                 debug->callfrom32 = (char *)RELAY_CallFrom32Regs - (char *)&debug->ret;
680             else
681                 debug->callfrom32 = (char *)RELAY_CallFrom32 - (char *)&debug->ret;
682         }
683         else
684         {
685             debug->call = 0xe9;  /* jmp relative */
686             debug->callfrom32 = (char *)debug->orig - (char *)&debug->ret;
687         }
688         *funcs = (char *)debug - (char *)module;
689     }
690 }
691
692
693 /***********************************************************************
694  *          SNOOP_ShowDebugmsgSnoop
695  *
696  * Simple function to decide if a particular debugging message is
697  * wanted.
698  */
699 static BOOL SNOOP_ShowDebugmsgSnoop(const char *module, int ordinal, const char *func)
700 {
701     if (debug_snoop_excludelist && check_list( module, ordinal, func, debug_snoop_excludelist ))
702         return FALSE;
703     if (debug_snoop_includelist && !check_list( module, ordinal, func, debug_snoop_includelist ))
704         return FALSE;
705     return TRUE;
706 }
707
708
709 /***********************************************************************
710  *           SNOOP_SetupDLL
711  *
712  * Setup snoop debugging for a native dll.
713  */
714 void SNOOP_SetupDLL(HMODULE hmod)
715 {
716     SNOOP_DLL **dll = &firstdll;
717     char *p, *name;
718     void *addr;
719     SIZE_T size;
720     IMAGE_EXPORT_DIRECTORY *exports;
721
722     if (!init_done) init_debug_lists();
723
724     exports = RtlImageDirectoryEntryToData( hmod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size );
725     if (!exports) return;
726     name = (char *)hmod + exports->Name;
727
728     TRACE_(snoop)("hmod=%p, name=%s\n", hmod, name);
729
730     while (*dll) {
731         if ((*dll)->hmod == hmod)
732         {
733             /* another dll, loaded at the same address */
734             addr = (*dll)->funs;
735             size = (*dll)->nrofordinals * sizeof(SNOOP_FUN);
736             NtFreeVirtualMemory(NtCurrentProcess(), &addr, &size, MEM_RELEASE);
737             break;
738         }
739         dll = &((*dll)->next);
740     }
741     if (*dll)
742         *dll = RtlReAllocateHeap(GetProcessHeap(),
743                              HEAP_ZERO_MEMORY, *dll,
744                              sizeof(SNOOP_DLL) + strlen(name));
745     else
746         *dll = RtlAllocateHeap(GetProcessHeap(),
747                              HEAP_ZERO_MEMORY,
748                              sizeof(SNOOP_DLL) + strlen(name));
749     (*dll)->hmod        = hmod;
750     (*dll)->ordbase = exports->Base;
751     (*dll)->nrofordinals = exports->NumberOfFunctions;
752     strcpy( (*dll)->name, name );
753     p = (*dll)->name + strlen((*dll)->name) - 4;
754     if (p > (*dll)->name && !strcasecmp( p, ".dll" )) *p = 0;
755
756     size = exports->NumberOfFunctions * sizeof(SNOOP_FUN);
757     addr = NULL;
758     NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size,
759                             MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
760     if (!addr) {
761         RtlFreeHeap(GetProcessHeap(),0,*dll);
762         FIXME("out of memory\n");
763         return;
764     }
765     (*dll)->funs = addr;
766     memset((*dll)->funs,0,size);
767 }
768
769
770 /***********************************************************************
771  *           SNOOP_GetProcAddress
772  *
773  * Return the proc address to use for a given function.
774  */
775 FARPROC SNOOP_GetProcAddress( HMODULE hmod, const IMAGE_EXPORT_DIRECTORY *exports,
776                               DWORD exp_size, FARPROC origfun, DWORD ordinal,
777                               const WCHAR *user)
778 {
779     unsigned int i;
780     const char *ename;
781     const WORD *ordinals;
782     const DWORD *names;
783     SNOOP_DLL *dll = firstdll;
784     SNOOP_FUN *fun;
785     const IMAGE_SECTION_HEADER *sec;
786
787     if (!TRACE_ON(snoop)) return origfun;
788     if (!check_from_module( debug_from_snoop_includelist, debug_from_snoop_excludelist, user ))
789         return origfun; /* the calling module was explicitly excluded */
790
791     if (!*(LPBYTE)origfun) /* 0x00 is an imposs. opcode, poss. dataref. */
792         return origfun;
793
794     sec = RtlImageRvaToSection( RtlImageNtHeader(hmod), hmod, (char *)origfun - (char *)hmod );
795
796     if (!sec || !(sec->Characteristics & IMAGE_SCN_CNT_CODE))
797         return origfun;  /* most likely a data reference */
798
799     while (dll) {
800         if (hmod == dll->hmod)
801             break;
802         dll = dll->next;
803     }
804     if (!dll)   /* probably internal */
805         return origfun;
806
807     /* try to find a name for it */
808     ename = NULL;
809     names = (const DWORD *)((const char *)hmod + exports->AddressOfNames);
810     ordinals = (const WORD *)((const char *)hmod + exports->AddressOfNameOrdinals);
811     if (names) for (i = 0; i < exports->NumberOfNames; i++)
812     {
813         if (ordinals[i] == ordinal)
814         {
815             ename = (const char *)hmod + names[i];
816             break;
817         }
818     }
819     if (!SNOOP_ShowDebugmsgSnoop(dll->name,ordinal,ename))
820         return origfun;
821     assert(ordinal < dll->nrofordinals);
822     fun = dll->funs + ordinal;
823     if (!fun->name)
824     {
825         fun->name       = ename;
826         fun->lcall      = 0xe8;
827         /* NOTE: origreturn struct member MUST come directly after snoopentry */
828         fun->snoopentry = (char*)SNOOP_Entry-((char*)(&fun->nrofargs));
829         fun->origfun    = origfun;
830         fun->nrofargs   = -1;
831     }
832     return (FARPROC)&(fun->lcall);
833 }
834
835 static void SNOOP_PrintArg(DWORD x)
836 {
837     int i,nostring;
838
839     DPRINTF("%08lx",x);
840     if (!HIWORD(x) || TRACE_ON(seh)) return; /* trivial reject to avoid faults */
841     __TRY
842     {
843         LPBYTE s=(LPBYTE)x;
844         i=0;nostring=0;
845         while (i<80) {
846             if (s[i]==0) break;
847             if (s[i]<0x20) {nostring=1;break;}
848             if (s[i]>=0x80) {nostring=1;break;}
849             i++;
850         }
851         if (!nostring && i > 5)
852             DPRINTF(" %s",debugstr_an((LPSTR)x,i));
853         else  /* try unicode */
854         {
855             LPWSTR s=(LPWSTR)x;
856             i=0;nostring=0;
857             while (i<80) {
858                 if (s[i]==0) break;
859                 if (s[i]<0x20) {nostring=1;break;}
860                 if (s[i]>0x100) {nostring=1;break;}
861                 i++;
862             }
863             if (!nostring && i > 5) DPRINTF(" %s",debugstr_wn((LPWSTR)x,i));
864         }
865     }
866     __EXCEPT(page_fault)
867     {
868     }
869     __ENDTRY
870 }
871
872 #define CALLER1REF (*(DWORD*)context->Esp)
873
874 void WINAPI __regs_SNOOP_Entry( CONTEXT86 *context )
875 {
876         DWORD           ordinal=0,entry = context->Eip - 5;
877         SNOOP_DLL       *dll = firstdll;
878         SNOOP_FUN       *fun = NULL;
879         SNOOP_RETURNENTRIES     **rets = &firstrets;
880         SNOOP_RETURNENTRY       *ret;
881         int             i=0, max;
882
883         while (dll) {
884                 if (    ((char*)entry>=(char*)dll->funs)        &&
885                         ((char*)entry<=(char*)(dll->funs+dll->nrofordinals))
886                 ) {
887                         fun = (SNOOP_FUN*)entry;
888                         ordinal = fun-dll->funs;
889                         break;
890                 }
891                 dll=dll->next;
892         }
893         if (!dll) {
894                 FIXME("entrypoint 0x%08lx not found\n",entry);
895                 return; /* oops */
896         }
897         /* guess cdecl ... */
898         if (fun->nrofargs<0) {
899                 /* Typical cdecl return frame is:
900                  *     add esp, xxxxxxxx
901                  * which has (for xxxxxxxx up to 255 the opcode "83 C4 xx".
902                  * (after that 81 C2 xx xx xx xx)
903                  */
904                 LPBYTE  reteip = (LPBYTE)CALLER1REF;
905
906                 if (reteip) {
907                         if ((reteip[0]==0x83)&&(reteip[1]==0xc4))
908                                 fun->nrofargs=reteip[2]/4;
909                 }
910         }
911
912
913         while (*rets) {
914                 for (i=0;i<sizeof((*rets)->entry)/sizeof((*rets)->entry[0]);i++)
915                         if (!(*rets)->entry[i].origreturn)
916                                 break;
917                 if (i!=sizeof((*rets)->entry)/sizeof((*rets)->entry[0]))
918                         break;
919                 rets = &((*rets)->next);
920         }
921         if (!*rets) {
922                 SIZE_T size = 4096;
923                 VOID* addr = NULL;
924
925                 NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size, 
926                                         MEM_COMMIT | MEM_RESERVE,
927                                         PAGE_EXECUTE_READWRITE);
928                 if (!addr) return;
929                 *rets = addr;
930                 memset(*rets,0,4096);
931                 i = 0;  /* entry 0 is free */
932         }
933         ret = &((*rets)->entry[i]);
934         ret->lcall      = 0xe8;
935         /* NOTE: origreturn struct member MUST come directly after snoopret */
936         ret->snoopret   = ((char*)SNOOP_Return)-(char*)(&ret->origreturn);
937         ret->origreturn = (FARPROC)CALLER1REF;
938         CALLER1REF      = (DWORD)&ret->lcall;
939         ret->dll        = dll;
940         ret->args       = NULL;
941         ret->ordinal    = ordinal;
942         ret->origESP    = context->Esp;
943
944         context->Eip = (DWORD)fun->origfun;
945
946         if (fun->name) DPRINTF("%04lx:CALL %s.%s(",GetCurrentThreadId(),dll->name,fun->name);
947         else DPRINTF("%04lx:CALL %s.%ld(",GetCurrentThreadId(),dll->name,dll->ordbase+ordinal);
948         if (fun->nrofargs>0) {
949                 max = fun->nrofargs; if (max>16) max=16;
950                 for (i=0;i<max;i++)
951                 {
952                     SNOOP_PrintArg(*(DWORD*)(context->Esp + 4 + sizeof(DWORD)*i));
953                     if (i<fun->nrofargs-1) DPRINTF(",");
954                 }
955                 if (max!=fun->nrofargs)
956                         DPRINTF(" ...");
957         } else if (fun->nrofargs<0) {
958                 DPRINTF("<unknown, check return>");
959                 ret->args = RtlAllocateHeap(GetProcessHeap(),
960                                             0,16*sizeof(DWORD));
961                 memcpy(ret->args,(LPBYTE)(context->Esp + 4),sizeof(DWORD)*16);
962         }
963         DPRINTF(") ret=%08lx\n",(DWORD)ret->origreturn);
964 }
965
966
967 void WINAPI __regs_SNOOP_Return( CONTEXT86 *context )
968 {
969         SNOOP_RETURNENTRY       *ret = (SNOOP_RETURNENTRY*)(context->Eip - 5);
970         SNOOP_FUN *fun = &ret->dll->funs[ret->ordinal];
971
972         /* We haven't found out the nrofargs yet. If we called a cdecl
973          * function it is too late anyway and we can just set '0' (which
974          * will be the difference between orig and current ESP
975          * If stdcall -> everything ok.
976          */
977         if (ret->dll->funs[ret->ordinal].nrofargs<0)
978                 ret->dll->funs[ret->ordinal].nrofargs=(context->Esp - ret->origESP-4)/4;
979         context->Eip = (DWORD)ret->origreturn;
980         if (ret->args) {
981                 int     i,max;
982
983                 if (fun->name)
984                     DPRINTF("%04lx:RET  %s.%s(", GetCurrentThreadId(), ret->dll->name, fun->name);
985                 else
986                     DPRINTF("%04lx:RET  %s.%ld(", GetCurrentThreadId(),
987                             ret->dll->name,ret->dll->ordbase+ret->ordinal);
988
989                 max = fun->nrofargs;
990                 if (max>16) max=16;
991
992                 for (i=0;i<max;i++)
993                 {
994                     SNOOP_PrintArg(ret->args[i]);
995                     if (i<max-1) DPRINTF(",");
996                 }
997                 DPRINTF(") retval=%08lx ret=%08lx\n",
998                         context->Eax,(DWORD)ret->origreturn );
999                 RtlFreeHeap(GetProcessHeap(),0,ret->args);
1000                 ret->args = NULL;
1001         }
1002         else
1003         {
1004             if (fun->name)
1005                 DPRINTF("%04lx:RET  %s.%s() retval=%08lx ret=%08lx\n",
1006                         GetCurrentThreadId(),
1007                         ret->dll->name, fun->name, context->Eax, (DWORD)ret->origreturn);
1008             else
1009                 DPRINTF("%04lx:RET  %s.%ld() retval=%08lx ret=%08lx\n",
1010                         GetCurrentThreadId(),
1011                         ret->dll->name,ret->dll->ordbase+ret->ordinal,
1012                         context->Eax, (DWORD)ret->origreturn);
1013         }
1014         ret->origreturn = NULL; /* mark as empty */
1015 }
1016
1017 /* assembly wrappers that save the context */
1018 DEFINE_REGS_ENTRYPOINT( SNOOP_Entry, 0, 0 );
1019 DEFINE_REGS_ENTRYPOINT( SNOOP_Return, 0, 0 );
1020
1021 #else  /* __i386__ */
1022
1023 FARPROC RELAY_GetProcAddress( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
1024                               DWORD exp_size, FARPROC proc, const WCHAR *user )
1025 {
1026     return proc;
1027 }
1028
1029 FARPROC SNOOP_GetProcAddress( HMODULE hmod, const IMAGE_EXPORT_DIRECTORY *exports, DWORD exp_size,
1030                               FARPROC origfun, DWORD ordinal, const WCHAR *user )
1031 {
1032     return origfun;
1033 }
1034
1035 void RELAY_SetupDLL( HMODULE module )
1036 {
1037 }
1038
1039 void SNOOP_SetupDLL( HMODULE hmod )
1040 {
1041     FIXME("snooping works only on i386 for now.\n");
1042 }
1043
1044 #endif /* __i386__ */