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