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