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