Do not forward _mbccpy to strcpy.
[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)  saved %eax
523  * (esp-12) ptr to relay entry code for RELAY_CallFrom32Regs
524  *  ...    >128 bytes space free to be modified (ensured by the assembly glue)
525  */
526 void WINAPI __regs_RELAY_CallFrom32Regs( CONTEXT86 *context )
527 {
528     char buffer[80];
529     int* args;
530     int args_copy[17];
531     BYTE *entry_point;
532
533     BYTE *relay_addr = *((BYTE **)context->Esp - 1);
534     DEBUG_ENTRY_POINT *relay = (DEBUG_ENTRY_POINT *)(relay_addr - 5);
535     WORD nb_args = relay->args / sizeof(int);
536
537     /* remove extra stuff from the stack */
538     context->Eip = *(DWORD *)context->Esp;
539     context->Esp += sizeof(DWORD);
540     args = (int *)context->Esp;
541     if (relay->ret == 0xc2) /* stdcall */
542         context->Esp += nb_args * sizeof(int);
543
544     entry_point = (BYTE *)relay->orig;
545     assert( entry_point[0] == 0x50 /* pushl %eax */ );
546     assert( entry_point[1] == 0xe8 /* call */ );
547
548     if (TRACE_ON(relay))
549     {
550         get_entry_point( buffer, relay );
551
552         DPRINTF( "%04lx:Call %s(", GetCurrentThreadId(), buffer );
553         RELAY_PrintArgs( args, nb_args, relay->argtypes );
554         DPRINTF( ") ret=%08lx fs=%04lx\n", context->Eip, context->SegFs );
555
556         DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
557                 context->Eax, context->Ebx, context->Ecx,
558                 context->Edx, context->Esi, context->Edi );
559         DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx gs=%04lx flags=%08lx\n",
560                 context->Ebp, context->Esp, context->SegDs,
561                 context->SegEs, context->SegGs, context->EFlags );
562     }
563
564     /* Now call the real function */
565
566     memcpy( args_copy, args, nb_args * sizeof(args[0]) );
567     args_copy[nb_args] = (int)context;  /* append context argument */
568
569     call_entry_point( (entry_point + 6 + *(DWORD *)(entry_point + 6)), nb_args+1, args_copy );
570
571     if (TRACE_ON(relay))
572     {
573         DPRINTF( "%04lx:Ret  %s() retval=%08lx ret=%08lx fs=%04lx\n",
574                  GetCurrentThreadId(),
575                  buffer, context->Eax, context->Eip, context->SegFs );
576
577         DPRINTF(" eax=%08lx ebx=%08lx ecx=%08lx edx=%08lx esi=%08lx edi=%08lx\n",
578                 context->Eax, context->Ebx, context->Ecx,
579                 context->Edx, context->Esi, context->Edi );
580         DPRINTF(" ebp=%08lx esp=%08lx ds=%04lx es=%04lx gs=%04lx flags=%08lx\n",
581                 context->Ebp, context->Esp, context->SegDs,
582                 context->SegEs, context->SegGs, context->EFlags );
583     }
584 }
585
586 void WINAPI RELAY_CallFrom32Regs(void);
587 DEFINE_REGS_ENTRYPOINT( RELAY_CallFrom32Regs, 0, 0 );
588
589 /* check whether the function at addr starts with a call to __wine_call_from_32_regs */
590 static BOOL is_register_entry_point( const BYTE *addr )
591 {
592     extern void __wine_call_from_32_regs();
593     const int *offset;
594     const void *ptr;
595
596     if (addr[0] != 0x50) return FALSE;  /* pushl %eax */
597     if (addr[1] != 0xe8) return FALSE;  /* call */
598     /* check if call target is __wine_call_from_32_regs */
599     offset = (const int *)(addr + 2);
600     if (*offset == (const char *)__wine_call_from_32_regs - (const char *)(offset + 1)) return TRUE;
601     /* now check if call target is an import table jump to __wine_call_from_32_regs */
602     addr = (const BYTE *)(offset + 1) + *offset;
603
604     /* Note: the following checks depend on the asm code generated by winebuild */
605
606     if (addr[0] == 0xff && addr[1] == 0x25)  /* indirect jmp */
607     {
608         ptr = *(const void * const*)(addr + 2);  /* get indirect jmp target address */
609     }
610     else  /* check for import thunk */
611     {
612         if (addr[0] != 0xe8) return FALSE;  /* call get_pc_thunk */
613         if (addr[5] != 0xff || addr[6] != 0xa0) return FALSE;  /* jmp *offset(%eax) */
614         ptr = addr + 5 + *(const int *)(addr + 7);
615     }
616     return (*(const char * const*)ptr == (char *)__wine_call_from_32_regs);
617 }
618
619
620 /***********************************************************************
621  *           RELAY_GetProcAddress
622  *
623  * Return the proc address to use for a given function.
624  */
625 FARPROC RELAY_GetProcAddress( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
626                               DWORD exp_size, FARPROC proc, const WCHAR *user )
627 {
628     const DEBUG_ENTRY_POINT *debug = (DEBUG_ENTRY_POINT *)proc;
629     const DEBUG_ENTRY_POINT *list = (const DEBUG_ENTRY_POINT *)((const char *)exports + exp_size);
630
631     if (debug < list || debug >= list + exports->NumberOfFunctions) return proc;
632     if (list + (debug - list) != debug) return proc;  /* not a valid address */
633     if (check_from_module( debug_from_relay_includelist, debug_from_relay_excludelist, user ))
634        return proc;  /* we want to relay it */
635     if (!debug->call) return proc;  /* not a normal function */
636     if (debug->call != 0xe8 && debug->call != 0xe9) return proc; /* not a debug thunk at all */
637     return debug->orig;
638 }
639
640
641 /***********************************************************************
642  *           RELAY_SetupDLL
643  *
644  * Setup relay debugging for a built-in dll.
645  */
646 void RELAY_SetupDLL( HMODULE module )
647 {
648     IMAGE_EXPORT_DIRECTORY *exports;
649     DEBUG_ENTRY_POINT *debug;
650     DWORD *funcs;
651     unsigned int i;
652     const char *name;
653     char *p, dllname[80];
654     DWORD size;
655
656     if (!init_done) init_debug_lists();
657
658     exports = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size );
659     if (!exports) return;
660     debug = (DEBUG_ENTRY_POINT *)((char *)exports + size);
661     funcs = (DWORD *)((char *)module + exports->AddressOfFunctions);
662     strcpy( dllname, (char *)module + exports->Name );
663     p = dllname + strlen(dllname) - 4;
664     if (p > dllname && !strcasecmp( p, ".dll" )) *p = 0;
665
666     for (i = 0; i < exports->NumberOfFunctions; i++, funcs++, debug++)
667     {
668         int on = 1;
669
670         if (!debug->call) continue;  /* not a normal function */
671         if (debug->call != 0xe8 && debug->call != 0xe9) break; /* not a debug thunk at all */
672
673         name = find_exported_name( module, exports, i + exports->Base );
674         on = check_relay_include( dllname, i + exports->Base, name );
675
676         if (on)
677         {
678             debug->call = 0xe8;  /* call relative */
679             if (is_register_entry_point( debug->orig ))
680                 debug->callfrom32 = (char *)RELAY_CallFrom32Regs - (char *)&debug->ret;
681             else
682                 debug->callfrom32 = (char *)RELAY_CallFrom32 - (char *)&debug->ret;
683         }
684         else
685         {
686             debug->call = 0xe9;  /* jmp relative */
687             debug->callfrom32 = (char *)debug->orig - (char *)&debug->ret;
688         }
689         *funcs = (char *)debug - (char *)module;
690     }
691 }
692
693
694 /***********************************************************************
695  *          SNOOP_ShowDebugmsgSnoop
696  *
697  * Simple function to decide if a particular debugging message is
698  * wanted.
699  */
700 static BOOL SNOOP_ShowDebugmsgSnoop(const char *module, int ordinal, const char *func)
701 {
702     if (debug_snoop_excludelist && check_list( module, ordinal, func, debug_snoop_excludelist ))
703         return FALSE;
704     if (debug_snoop_includelist && !check_list( module, ordinal, func, debug_snoop_includelist ))
705         return FALSE;
706     return TRUE;
707 }
708
709
710 /***********************************************************************
711  *           SNOOP_SetupDLL
712  *
713  * Setup snoop debugging for a native dll.
714  */
715 void SNOOP_SetupDLL(HMODULE hmod)
716 {
717     SNOOP_DLL **dll = &firstdll;
718     char *p, *name;
719     void *addr;
720     SIZE_T size;
721     IMAGE_EXPORT_DIRECTORY *exports;
722
723     if (!init_done) init_debug_lists();
724
725     exports = RtlImageDirectoryEntryToData( hmod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size );
726     if (!exports) return;
727     name = (char *)hmod + exports->Name;
728
729     TRACE_(snoop)("hmod=%p, name=%s\n", hmod, name);
730
731     while (*dll) {
732         if ((*dll)->hmod == hmod)
733         {
734             /* another dll, loaded at the same address */
735             addr = (*dll)->funs;
736             size = (*dll)->nrofordinals * sizeof(SNOOP_FUN);
737             NtFreeVirtualMemory(NtCurrentProcess(), &addr, &size, MEM_RELEASE);
738             break;
739         }
740         dll = &((*dll)->next);
741     }
742     if (*dll)
743         *dll = RtlReAllocateHeap(GetProcessHeap(),
744                              HEAP_ZERO_MEMORY, *dll,
745                              sizeof(SNOOP_DLL) + strlen(name));
746     else
747         *dll = RtlAllocateHeap(GetProcessHeap(),
748                              HEAP_ZERO_MEMORY,
749                              sizeof(SNOOP_DLL) + strlen(name));
750     (*dll)->hmod        = hmod;
751     (*dll)->ordbase = exports->Base;
752     (*dll)->nrofordinals = exports->NumberOfFunctions;
753     strcpy( (*dll)->name, name );
754     p = (*dll)->name + strlen((*dll)->name) - 4;
755     if (p > (*dll)->name && !strcasecmp( p, ".dll" )) *p = 0;
756
757     size = exports->NumberOfFunctions * sizeof(SNOOP_FUN);
758     addr = NULL;
759     NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size,
760                             MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
761     if (!addr) {
762         RtlFreeHeap(GetProcessHeap(),0,*dll);
763         FIXME("out of memory\n");
764         return;
765     }
766     (*dll)->funs = addr;
767     memset((*dll)->funs,0,size);
768 }
769
770
771 /***********************************************************************
772  *           SNOOP_GetProcAddress
773  *
774  * Return the proc address to use for a given function.
775  */
776 FARPROC SNOOP_GetProcAddress( HMODULE hmod, const IMAGE_EXPORT_DIRECTORY *exports,
777                               DWORD exp_size, FARPROC origfun, DWORD ordinal,
778                               const WCHAR *user)
779 {
780     unsigned int i;
781     const char *ename;
782     const WORD *ordinals;
783     const DWORD *names;
784     SNOOP_DLL *dll = firstdll;
785     SNOOP_FUN *fun;
786     const IMAGE_SECTION_HEADER *sec;
787
788     if (!TRACE_ON(snoop)) return origfun;
789     if (!check_from_module( debug_from_snoop_includelist, debug_from_snoop_excludelist, user ))
790         return origfun; /* the calling module was explicitly excluded */
791
792     if (!*(LPBYTE)origfun) /* 0x00 is an imposs. opcode, poss. dataref. */
793         return origfun;
794
795     sec = RtlImageRvaToSection( RtlImageNtHeader(hmod), hmod, (char *)origfun - (char *)hmod );
796
797     if (!sec || !(sec->Characteristics & IMAGE_SCN_CNT_CODE))
798         return origfun;  /* most likely a data reference */
799
800     while (dll) {
801         if (hmod == dll->hmod)
802             break;
803         dll = dll->next;
804     }
805     if (!dll)   /* probably internal */
806         return origfun;
807
808     /* try to find a name for it */
809     ename = NULL;
810     names = (const DWORD *)((const char *)hmod + exports->AddressOfNames);
811     ordinals = (const WORD *)((const char *)hmod + exports->AddressOfNameOrdinals);
812     if (names) for (i = 0; i < exports->NumberOfNames; i++)
813     {
814         if (ordinals[i] == ordinal)
815         {
816             ename = (const char *)hmod + names[i];
817             break;
818         }
819     }
820     if (!SNOOP_ShowDebugmsgSnoop(dll->name,ordinal,ename))
821         return origfun;
822     assert(ordinal < dll->nrofordinals);
823     fun = dll->funs + ordinal;
824     if (!fun->name)
825     {
826         fun->name       = ename;
827         fun->lcall      = 0xe8;
828         /* NOTE: origreturn struct member MUST come directly after snoopentry */
829         fun->snoopentry = (char*)SNOOP_Entry-((char*)(&fun->nrofargs));
830         fun->origfun    = origfun;
831         fun->nrofargs   = -1;
832     }
833     return (FARPROC)&(fun->lcall);
834 }
835
836 static void SNOOP_PrintArg(DWORD x)
837 {
838     int i,nostring;
839
840     DPRINTF("%08lx",x);
841     if (!HIWORD(x) || TRACE_ON(seh)) return; /* trivial reject to avoid faults */
842     __TRY
843     {
844         LPBYTE s=(LPBYTE)x;
845         i=0;nostring=0;
846         while (i<80) {
847             if (s[i]==0) break;
848             if (s[i]<0x20) {nostring=1;break;}
849             if (s[i]>=0x80) {nostring=1;break;}
850             i++;
851         }
852         if (!nostring && i > 5)
853             DPRINTF(" %s",debugstr_an((LPSTR)x,i));
854         else  /* try unicode */
855         {
856             LPWSTR s=(LPWSTR)x;
857             i=0;nostring=0;
858             while (i<80) {
859                 if (s[i]==0) break;
860                 if (s[i]<0x20) {nostring=1;break;}
861                 if (s[i]>0x100) {nostring=1;break;}
862                 i++;
863             }
864             if (!nostring && i > 5) DPRINTF(" %s",debugstr_wn((LPWSTR)x,i));
865         }
866     }
867     __EXCEPT(page_fault)
868     {
869     }
870     __ENDTRY
871 }
872
873 #define CALLER1REF (*(DWORD*)context->Esp)
874
875 void WINAPI __regs_SNOOP_Entry( CONTEXT86 *context )
876 {
877         DWORD           ordinal=0,entry = context->Eip - 5;
878         SNOOP_DLL       *dll = firstdll;
879         SNOOP_FUN       *fun = NULL;
880         SNOOP_RETURNENTRIES     **rets = &firstrets;
881         SNOOP_RETURNENTRY       *ret;
882         int             i=0, max;
883
884         while (dll) {
885                 if (    ((char*)entry>=(char*)dll->funs)        &&
886                         ((char*)entry<=(char*)(dll->funs+dll->nrofordinals))
887                 ) {
888                         fun = (SNOOP_FUN*)entry;
889                         ordinal = fun-dll->funs;
890                         break;
891                 }
892                 dll=dll->next;
893         }
894         if (!dll) {
895                 FIXME("entrypoint 0x%08lx not found\n",entry);
896                 return; /* oops */
897         }
898         /* guess cdecl ... */
899         if (fun->nrofargs<0) {
900                 /* Typical cdecl return frame is:
901                  *     add esp, xxxxxxxx
902                  * which has (for xxxxxxxx up to 255 the opcode "83 C4 xx".
903                  * (after that 81 C2 xx xx xx xx)
904                  */
905                 LPBYTE  reteip = (LPBYTE)CALLER1REF;
906
907                 if (reteip) {
908                         if ((reteip[0]==0x83)&&(reteip[1]==0xc4))
909                                 fun->nrofargs=reteip[2]/4;
910                 }
911         }
912
913
914         while (*rets) {
915                 for (i=0;i<sizeof((*rets)->entry)/sizeof((*rets)->entry[0]);i++)
916                         if (!(*rets)->entry[i].origreturn)
917                                 break;
918                 if (i!=sizeof((*rets)->entry)/sizeof((*rets)->entry[0]))
919                         break;
920                 rets = &((*rets)->next);
921         }
922         if (!*rets) {
923                 SIZE_T size = 4096;
924                 VOID* addr = NULL;
925
926                 NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size, 
927                                         MEM_COMMIT | MEM_RESERVE,
928                                         PAGE_EXECUTE_READWRITE);
929                 if (!addr) return;
930                 *rets = addr;
931                 memset(*rets,0,4096);
932                 i = 0;  /* entry 0 is free */
933         }
934         ret = &((*rets)->entry[i]);
935         ret->lcall      = 0xe8;
936         /* NOTE: origreturn struct member MUST come directly after snoopret */
937         ret->snoopret   = ((char*)SNOOP_Return)-(char*)(&ret->origreturn);
938         ret->origreturn = (FARPROC)CALLER1REF;
939         CALLER1REF      = (DWORD)&ret->lcall;
940         ret->dll        = dll;
941         ret->args       = NULL;
942         ret->ordinal    = ordinal;
943         ret->origESP    = context->Esp;
944
945         context->Eip = (DWORD)fun->origfun;
946
947         if (fun->name) DPRINTF("%04lx:CALL %s.%s(",GetCurrentThreadId(),dll->name,fun->name);
948         else DPRINTF("%04lx:CALL %s.%ld(",GetCurrentThreadId(),dll->name,dll->ordbase+ordinal);
949         if (fun->nrofargs>0) {
950                 max = fun->nrofargs; if (max>16) max=16;
951                 for (i=0;i<max;i++)
952                 {
953                     SNOOP_PrintArg(*(DWORD*)(context->Esp + 4 + sizeof(DWORD)*i));
954                     if (i<fun->nrofargs-1) DPRINTF(",");
955                 }
956                 if (max!=fun->nrofargs)
957                         DPRINTF(" ...");
958         } else if (fun->nrofargs<0) {
959                 DPRINTF("<unknown, check return>");
960                 ret->args = RtlAllocateHeap(GetProcessHeap(),
961                                             0,16*sizeof(DWORD));
962                 memcpy(ret->args,(LPBYTE)(context->Esp + 4),sizeof(DWORD)*16);
963         }
964         DPRINTF(") ret=%08lx\n",(DWORD)ret->origreturn);
965 }
966
967
968 void WINAPI __regs_SNOOP_Return( CONTEXT86 *context )
969 {
970         SNOOP_RETURNENTRY       *ret = (SNOOP_RETURNENTRY*)(context->Eip - 5);
971         SNOOP_FUN *fun = &ret->dll->funs[ret->ordinal];
972
973         /* We haven't found out the nrofargs yet. If we called a cdecl
974          * function it is too late anyway and we can just set '0' (which
975          * will be the difference between orig and current ESP
976          * If stdcall -> everything ok.
977          */
978         if (ret->dll->funs[ret->ordinal].nrofargs<0)
979                 ret->dll->funs[ret->ordinal].nrofargs=(context->Esp - ret->origESP-4)/4;
980         context->Eip = (DWORD)ret->origreturn;
981         if (ret->args) {
982                 int     i,max;
983
984                 if (fun->name)
985                     DPRINTF("%04lx:RET  %s.%s(", GetCurrentThreadId(), ret->dll->name, fun->name);
986                 else
987                     DPRINTF("%04lx:RET  %s.%ld(", GetCurrentThreadId(),
988                             ret->dll->name,ret->dll->ordbase+ret->ordinal);
989
990                 max = fun->nrofargs;
991                 if (max>16) max=16;
992
993                 for (i=0;i<max;i++)
994                 {
995                     SNOOP_PrintArg(ret->args[i]);
996                     if (i<max-1) DPRINTF(",");
997                 }
998                 DPRINTF(") retval=%08lx ret=%08lx\n",
999                         context->Eax,(DWORD)ret->origreturn );
1000                 RtlFreeHeap(GetProcessHeap(),0,ret->args);
1001                 ret->args = NULL;
1002         }
1003         else
1004         {
1005             if (fun->name)
1006                 DPRINTF("%04lx:RET  %s.%s() retval=%08lx ret=%08lx\n",
1007                         GetCurrentThreadId(),
1008                         ret->dll->name, fun->name, context->Eax, (DWORD)ret->origreturn);
1009             else
1010                 DPRINTF("%04lx:RET  %s.%ld() retval=%08lx ret=%08lx\n",
1011                         GetCurrentThreadId(),
1012                         ret->dll->name,ret->dll->ordbase+ret->ordinal,
1013                         context->Eax, (DWORD)ret->origreturn);
1014         }
1015         ret->origreturn = NULL; /* mark as empty */
1016 }
1017
1018 /* assembly wrappers that save the context */
1019 DEFINE_REGS_ENTRYPOINT( SNOOP_Entry, 0, 0 );
1020 DEFINE_REGS_ENTRYPOINT( SNOOP_Return, 0, 0 );
1021
1022 #else  /* __i386__ */
1023
1024 FARPROC RELAY_GetProcAddress( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
1025                               DWORD exp_size, FARPROC proc, const WCHAR *user )
1026 {
1027     return proc;
1028 }
1029
1030 FARPROC SNOOP_GetProcAddress( HMODULE hmod, const IMAGE_EXPORT_DIRECTORY *exports, DWORD exp_size,
1031                               FARPROC origfun, DWORD ordinal, const WCHAR *user )
1032 {
1033     return origfun;
1034 }
1035
1036 void RELAY_SetupDLL( HMODULE module )
1037 {
1038 }
1039
1040 void SNOOP_SetupDLL( HMODULE hmod )
1041 {
1042     FIXME("snooping works only on i386 for now.\n");
1043 }
1044
1045 #endif /* __i386__ */