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