Changes in crossover-wine-src-6.1.0 except for configure
[wine/hacks.git] / dlls / ntdll / relay.c
blob8e17d19f9f82c5fead5fce83384290c05a52c875
1 /*
2 * Win32 relay and snoop functions
4 * Copyright 1997 Alexandre Julliard
5 * Copyright 1998 Marcus Meissner
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.
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.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #include <stdio.h>
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"
38 WINE_DEFAULT_DEBUG_CHANNEL(relay);
40 #ifdef __i386__
42 WINE_DECLARE_DEBUG_CHANNEL(snoop);
43 #if 0
44 WINE_DECLARE_DEBUG_CHANNEL(seh);
45 #endif
47 struct relay_descr /* descriptor for a module */
49 void *magic; /* signature */
50 void *relay_from_32; /* functions to call from relay thunks */
51 void *relay_from_32_regs;
52 void *private; /* reserved for the relay code private data */
53 const char *entry_point_base; /* base address of entry point thunks */
54 const unsigned int *entry_point_offsets; /* offsets of entry points thunks */
55 const unsigned int *arg_types; /* table of argument types for all entry points */
58 #define RELAY_DESCR_MAGIC ((void *)0xdeb90001)
60 /* private data built at dll load time */
62 struct relay_entry_point
64 void *orig_func; /* original entry point function */
65 const char *name; /* function name (if any) */
68 struct relay_private_data
70 HMODULE module; /* module handle of this dll */
71 unsigned int base; /* ordinal base */
72 char dllname[40]; /* dll name (without .dll extension) */
73 struct relay_entry_point entry_points[1]; /* list of dll entry points */
76 static const WCHAR **debug_relay_excludelist;
77 static const WCHAR **debug_relay_includelist;
78 static const WCHAR **debug_snoop_excludelist;
79 static const WCHAR **debug_snoop_includelist;
80 static const WCHAR **debug_from_relay_excludelist;
81 static const WCHAR **debug_from_relay_includelist;
82 static const WCHAR **debug_from_snoop_excludelist;
83 static const WCHAR **debug_from_snoop_includelist;
85 static BOOL init_done;
87 /* compare an ASCII and a Unicode string without depending on the current codepage */
88 static inline int strcmpAW( const char *strA, const WCHAR *strW )
90 while (*strA && ((unsigned char)*strA == *strW)) { strA++; strW++; }
91 return (unsigned char)*strA - *strW;
94 /* compare an ASCII and a Unicode string without depending on the current codepage */
95 static inline int strncmpiAW( const char *strA, const WCHAR *strW, int n )
97 int ret = 0;
98 for ( ; n > 0; n--, strA++, strW++)
99 if ((ret = toupperW((unsigned char)*strA) - toupperW(*strW)) || !*strA) break;
100 return ret;
103 /***********************************************************************
104 * build_list
106 * Build a function list from a ';'-separated string.
108 static const WCHAR **build_list( const WCHAR *buffer )
110 int count = 1;
111 const WCHAR *p = buffer;
112 const WCHAR **ret;
114 while ((p = strchrW( p, ';' )))
116 count++;
117 p++;
119 /* allocate count+1 pointers, plus the space for a copy of the string */
120 if ((ret = RtlAllocateHeap( GetProcessHeap(), 0,
121 (count+1) * sizeof(WCHAR*) + (strlenW(buffer)+1) * sizeof(WCHAR) )))
123 WCHAR *str = (WCHAR *)(ret + count + 1);
124 WCHAR *p = str;
126 strcpyW( str, buffer );
127 count = 0;
128 for (;;)
130 ret[count++] = p;
131 if (!(p = strchrW( p, ';' ))) break;
132 *p++ = 0;
134 ret[count++] = NULL;
136 return ret;
140 /***********************************************************************
141 * init_debug_lists
143 * Build the relay include/exclude function lists.
145 static void init_debug_lists(void)
147 OBJECT_ATTRIBUTES attr;
148 UNICODE_STRING name;
149 char buffer[1024];
150 HANDLE root, hkey;
151 DWORD count;
152 WCHAR *str;
153 static const WCHAR configW[] = {'S','o','f','t','w','a','r','e','\\',
154 'W','i','n','e','\\',
155 'D','e','b','u','g',0};
156 static const WCHAR RelayIncludeW[] = {'R','e','l','a','y','I','n','c','l','u','d','e',0};
157 static const WCHAR RelayExcludeW[] = {'R','e','l','a','y','E','x','c','l','u','d','e',0};
158 static const WCHAR SnoopIncludeW[] = {'S','n','o','o','p','I','n','c','l','u','d','e',0};
159 static const WCHAR SnoopExcludeW[] = {'S','n','o','o','p','E','x','c','l','u','d','e',0};
160 static const WCHAR RelayFromIncludeW[] = {'R','e','l','a','y','F','r','o','m','I','n','c','l','u','d','e',0};
161 static const WCHAR RelayFromExcludeW[] = {'R','e','l','a','y','F','r','o','m','E','x','c','l','u','d','e',0};
162 static const WCHAR SnoopFromIncludeW[] = {'S','n','o','o','p','F','r','o','m','I','n','c','l','u','d','e',0};
163 static const WCHAR SnoopFromExcludeW[] = {'S','n','o','o','p','F','r','o','m','E','x','c','l','u','d','e',0};
165 if (init_done) return;
166 init_done = TRUE;
168 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
169 attr.Length = sizeof(attr);
170 attr.RootDirectory = root;
171 attr.ObjectName = &name;
172 attr.Attributes = 0;
173 attr.SecurityDescriptor = NULL;
174 attr.SecurityQualityOfService = NULL;
175 RtlInitUnicodeString( &name, configW );
177 /* @@ Wine registry key: HKCU\Software\Wine\Debug */
178 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr )) hkey = 0;
179 NtClose( root );
180 if (!hkey) return;
182 str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)buffer)->Data;
183 RtlInitUnicodeString( &name, RelayIncludeW );
184 if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
186 TRACE("RelayInclude = %s\n", debugstr_w(str) );
187 debug_relay_includelist = build_list( str );
190 RtlInitUnicodeString( &name, RelayExcludeW );
191 if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
193 TRACE( "RelayExclude = %s\n", debugstr_w(str) );
194 debug_relay_excludelist = build_list( str );
197 RtlInitUnicodeString( &name, SnoopIncludeW );
198 if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
200 TRACE_(snoop)( "SnoopInclude = %s\n", debugstr_w(str) );
201 debug_snoop_includelist = build_list( str );
204 RtlInitUnicodeString( &name, SnoopExcludeW );
205 if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
207 TRACE_(snoop)( "SnoopExclude = %s\n", debugstr_w(str) );
208 debug_snoop_excludelist = build_list( str );
211 RtlInitUnicodeString( &name, RelayFromIncludeW );
212 if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
214 TRACE("RelayFromInclude = %s\n", debugstr_w(str) );
215 debug_from_relay_includelist = build_list( str );
218 RtlInitUnicodeString( &name, RelayFromExcludeW );
219 if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
221 TRACE( "RelayFromExclude = %s\n", debugstr_w(str) );
222 debug_from_relay_excludelist = build_list( str );
225 RtlInitUnicodeString( &name, SnoopFromIncludeW );
226 if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
228 TRACE_(snoop)("SnoopFromInclude = %s\n", debugstr_w(str) );
229 debug_from_snoop_includelist = build_list( str );
232 RtlInitUnicodeString( &name, SnoopFromExcludeW );
233 if (!NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count ))
235 TRACE_(snoop)( "SnoopFromExclude = %s\n", debugstr_w(str) );
236 debug_from_snoop_excludelist = build_list( str );
239 NtClose( hkey );
243 /***********************************************************************
244 * check_list
246 * Check if a given module and function is in the list.
248 static BOOL check_list( const char *module, int ordinal, const char *func, const WCHAR **list )
250 char ord_str[10];
252 sprintf( ord_str, "%d", ordinal );
253 for(; *list; list++)
255 const WCHAR *p = strrchrW( *list, '.' );
256 if (p && p > *list) /* check module and function */
258 int len = p - *list;
259 if (strncmpiAW( module, *list, len-1 ) || module[len]) continue;
260 if (p[1] == '*' && !p[2]) return TRUE;
261 if (!strcmpAW( ord_str, p + 1 )) return TRUE;
262 if (func && !strcmpAW( func, p + 1 )) return TRUE;
264 else /* function only */
266 if (func && !strcmpAW( func, *list )) return TRUE;
269 return FALSE;
273 /***********************************************************************
274 * check_relay_include
276 * Check if a given function must be included in the relay output.
278 static BOOL check_relay_include( const char *module, int ordinal, const char *func )
280 if (debug_relay_excludelist && check_list( module, ordinal, func, debug_relay_excludelist ))
281 return FALSE;
282 if (debug_relay_includelist && !check_list( module, ordinal, func, debug_relay_includelist ))
283 return FALSE;
284 return TRUE;
287 /***********************************************************************
288 * check_from_module
290 * Check if calls from a given module must be included in the relay/snoop output,
291 * given the exclusion and inclusion lists.
293 static BOOL check_from_module( const WCHAR **includelist, const WCHAR **excludelist, const WCHAR *module )
295 static const WCHAR dllW[] = {'.','d','l','l',0 };
296 const WCHAR **listitem;
297 BOOL show;
299 if (!module) return TRUE;
300 if (!includelist && !excludelist) return TRUE;
301 if (excludelist)
303 show = TRUE;
304 listitem = excludelist;
306 else
308 show = FALSE;
309 listitem = includelist;
311 for(; *listitem; listitem++)
313 int len;
315 if (!strcmpiW( *listitem, module )) return !show;
316 len = strlenW( *listitem );
317 if (!strncmpiW( *listitem, module, len ) && !strcmpiW( module + len, dllW ))
318 return !show;
320 return show;
323 /***********************************************************************
324 * RELAY_PrintArgs
326 static inline void RELAY_PrintArgs( int *args, int nb_args, unsigned int typemask )
328 while (nb_args--)
330 if ((typemask & 3) && HIWORD(*args))
332 if (typemask & 2)
333 DPRINTF( "%08x %s", *args, debugstr_w((LPWSTR)*args) );
334 else
335 DPRINTF( "%08x %s", *args, debugstr_a((LPCSTR)*args) );
337 else DPRINTF( "%08x", *args );
338 if (nb_args) DPRINTF( "," );
339 args++;
340 typemask >>= 2;
344 extern LONGLONG call_entry_point( void *func, int nb_args, const int *args );
345 __ASM_GLOBAL_FUNC( call_entry_point,
346 "\tpushl %ebp\n"
347 "\tmovl %esp,%ebp\n"
348 "\tpushl %esi\n"
349 "\tpushl %edi\n"
350 "\tmovl 12(%ebp),%edx\n"
351 "\tshll $2,%edx\n"
352 "\tjz 1f\n"
353 "\tsubl %edx,%esp\n"
354 "\tandl $~15,%esp\n"
355 "\tmovl 12(%ebp),%ecx\n"
356 "\tmovl 16(%ebp),%esi\n"
357 "\tmovl %esp,%edi\n"
358 "\tcld\n"
359 "\trep; movsl\n"
360 "1:\tcall *8(%ebp)\n"
361 "\tleal -8(%ebp),%esp\n"
362 "\tpopl %edi\n"
363 "\tpopl %esi\n"
364 "\tpopl %ebp\n"
365 "\tret" )
368 /***********************************************************************
369 * relay_call_from_32
371 * stack points to the return address, i.e. the first argument is stack[1].
373 static LONGLONG WINAPI relay_call_from_32( struct relay_descr *descr, unsigned int idx, int *stack )
375 LONGLONG ret;
376 WORD ordinal = LOWORD(idx);
377 BYTE nb_args = LOBYTE(HIWORD(idx));
378 BYTE flags = HIBYTE(HIWORD(idx));
379 struct relay_private_data *data = descr->private;
380 struct relay_entry_point *entry_point = data->entry_points + ordinal;
382 if (!TRACE_ON(relay))
383 ret = call_entry_point( entry_point->orig_func, nb_args, stack + 1 );
384 else
386 if (entry_point->name)
387 DPRINTF( "%04x:Call %s.%s(", GetCurrentThreadId(), data->dllname, entry_point->name );
388 else
389 DPRINTF( "%04x:Call %s.%u(", GetCurrentThreadId(), data->dllname, data->base + ordinal );
390 RELAY_PrintArgs( stack + 1, nb_args, descr->arg_types[ordinal] );
391 DPRINTF( ") ret=%08x\n", stack[0] );
393 ret = call_entry_point( entry_point->orig_func, nb_args, stack + 1 );
395 if (entry_point->name)
396 DPRINTF( "%04x:Ret %s.%s()", GetCurrentThreadId(), data->dllname, entry_point->name );
397 else
398 DPRINTF( "%04x:Ret %s.%u()", GetCurrentThreadId(), data->dllname, data->base + ordinal );
400 if (flags & 1) /* 64-bit return value */
401 DPRINTF( " retval=%08x%08x ret=%08x\n",
402 (UINT)(ret >> 32), (UINT)ret, stack[0] );
403 else
404 DPRINTF( " retval=%08x ret=%08x\n", (UINT)ret, stack[0] );
406 return ret;
410 /***********************************************************************
411 * relay_call_from_32_regs
413 void WINAPI __regs_relay_call_from_32_regs( struct relay_descr *descr, unsigned int idx,
414 unsigned int orig_eax, unsigned int ret_addr,
415 CONTEXT86 *context )
417 WORD ordinal = LOWORD(idx);
418 BYTE nb_args = LOBYTE(HIWORD(idx));
419 BYTE flags = HIBYTE(HIWORD(idx));
420 struct relay_private_data *data = descr->private;
421 struct relay_entry_point *entry_point = data->entry_points + ordinal;
422 BYTE *orig_func = entry_point->orig_func;
423 int *args = (int *)context->Esp;
424 int args_copy[32];
426 /* restore the context to what it was before the relay thunk */
427 context->Eax = orig_eax;
428 context->Eip = ret_addr;
429 if (flags & 2) /* stdcall */
430 context->Esp += nb_args * sizeof(int);
432 if (TRACE_ON(relay))
434 if (entry_point->name)
435 DPRINTF( "%04x:Call %s.%s(", GetCurrentThreadId(), data->dllname, entry_point->name );
436 else
437 DPRINTF( "%04x:Call %s.%u(", GetCurrentThreadId(), data->dllname, data->base + ordinal );
438 RELAY_PrintArgs( args, nb_args, descr->arg_types[ordinal] );
439 DPRINTF( ") ret=%08x\n", ret_addr );
441 DPRINTF( "%04x: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x "
442 "ebp=%08x esp=%08x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
443 GetCurrentThreadId(), context->Eax, context->Ebx, context->Ecx,
444 context->Edx, context->Esi, context->Edi, context->Ebp, context->Esp,
445 context->SegDs, context->SegEs, context->SegFs, context->SegGs, context->EFlags );
447 assert( orig_func[0] == 0x50 /* pushl %eax */ );
448 assert( orig_func[1] == 0xe8 /* call */ );
451 /* now call the real function */
453 memcpy( args_copy, args, nb_args * sizeof(args[0]) );
454 args_copy[nb_args++] = (int)context; /* append context argument */
456 call_entry_point( orig_func + 6 + *(int *)(orig_func + 6), nb_args, args_copy );
459 if (TRACE_ON(relay))
461 if (entry_point->name)
462 DPRINTF( "%04x:Ret %s.%s() retval=%08x ret=%08x\n",
463 GetCurrentThreadId(), data->dllname, entry_point->name,
464 context->Eax, context->Eip );
465 else
466 DPRINTF( "%04x:Ret %s.%u() retval=%08x ret=%08x\n",
467 GetCurrentThreadId(), data->dllname, data->base + ordinal,
468 context->Eax, context->Eip );
469 DPRINTF( "%04x: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x "
470 "ebp=%08x esp=%08x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
471 GetCurrentThreadId(), context->Eax, context->Ebx, context->Ecx,
472 context->Edx, context->Esi, context->Edi, context->Ebp, context->Esp,
473 context->SegDs, context->SegEs, context->SegFs, context->SegGs, context->EFlags );
476 extern void WINAPI relay_call_from_32_regs(void);
477 DEFINE_REGS_ENTRYPOINT( relay_call_from_32_regs, 16, 16 );
480 /***********************************************************************
481 * RELAY_GetProcAddress
483 * Return the proc address to use for a given function.
485 FARPROC RELAY_GetProcAddress( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
486 DWORD exp_size, FARPROC proc, DWORD ordinal, const WCHAR *user )
488 struct relay_private_data *data;
489 const struct relay_descr *descr = (const struct relay_descr *)((const char *)exports + exp_size);
491 if (descr->magic != RELAY_DESCR_MAGIC || !(data = descr->private)) return proc; /* no relay data */
492 if (!data->entry_points[ordinal].orig_func) return proc; /* not a relayed function */
493 if (check_from_module( debug_from_relay_includelist, debug_from_relay_excludelist, user ))
494 return proc; /* we want to relay it */
495 return data->entry_points[ordinal].orig_func;
499 /***********************************************************************
500 * RELAY_SetupDLL
502 * Setup relay debugging for a built-in dll.
504 void RELAY_SetupDLL( HMODULE module )
506 IMAGE_EXPORT_DIRECTORY *exports;
507 DWORD *funcs;
508 unsigned int i, len;
509 DWORD size, entry_point_rva;
510 struct relay_descr *descr;
511 struct relay_private_data *data;
512 const WORD *ordptr;
514 if (!init_done) init_debug_lists();
516 exports = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size );
517 if (!exports) return;
519 descr = (struct relay_descr *)((char *)exports + size);
520 if (descr->magic != RELAY_DESCR_MAGIC) return;
522 if (!(data = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data) +
523 (exports->NumberOfFunctions-1) * sizeof(data->entry_points) )))
524 return;
526 descr->relay_from_32 = relay_call_from_32;
527 descr->relay_from_32_regs = relay_call_from_32_regs;
528 descr->private = data;
530 data->module = module;
531 data->base = exports->Base;
532 len = strlen( (char *)module + exports->Name );
533 if (len > 4 && !strcasecmp( (char *)module + exports->Name + len - 4, ".dll" )) len -= 4;
534 len = min( len, sizeof(data->dllname) - 1 );
535 memcpy( data->dllname, (char *)module + exports->Name, len );
536 data->dllname[len] = 0;
538 /* fetch name pointer for all entry points and store them in the private structure */
540 ordptr = (const WORD *)((char *)module + exports->AddressOfNameOrdinals);
541 for (i = 0; i < exports->NumberOfNames; i++, ordptr++)
543 DWORD name_rva = ((DWORD*)((char *)module + exports->AddressOfNames))[i];
544 data->entry_points[*ordptr].name = (const char *)module + name_rva;
547 /* patch the functions in the export table to point to the relay thunks */
549 funcs = (DWORD *)((char *)module + exports->AddressOfFunctions);
550 entry_point_rva = (const char *)descr->entry_point_base - (const char *)module;
551 for (i = 0; i < exports->NumberOfFunctions; i++, funcs++)
553 if (!descr->entry_point_offsets[i]) continue; /* not a normal function */
554 if (!check_relay_include( data->dllname, i + exports->Base, data->entry_points[i].name ))
555 continue; /* don't include this entry point */
557 data->entry_points[i].orig_func = (char *)module + *funcs;
558 *funcs = entry_point_rva + descr->entry_point_offsets[i];
564 /***********************************************************************/
565 /* snoop support */
566 /***********************************************************************/
568 #include "pshpack1.h"
570 typedef struct
572 /* code part */
573 BYTE lcall; /* 0xe8 call snoopentry (relative) */
574 /* NOTE: If you move snoopentry OR nrofargs fix the relative offset
575 * calculation!
577 DWORD snoopentry; /* SNOOP_Entry relative */
578 /* unreached */
579 int nrofargs;
580 FARPROC origfun;
581 const char *name;
582 } SNOOP_FUN;
584 typedef struct tagSNOOP_DLL {
585 HMODULE hmod;
586 SNOOP_FUN *funs;
587 DWORD ordbase;
588 DWORD nrofordinals;
589 struct tagSNOOP_DLL *next;
590 char name[1];
591 } SNOOP_DLL;
593 typedef struct
595 /* code part */
596 BYTE lcall; /* 0xe8 call snoopret relative*/
597 /* NOTE: If you move snoopret OR origreturn fix the relative offset
598 * calculation!
600 DWORD snoopret; /* SNOOP_Ret relative */
601 /* unreached */
602 FARPROC origreturn;
603 SNOOP_DLL *dll;
604 DWORD ordinal;
605 DWORD origESP;
606 DWORD *args; /* saved args across a stdcall */
607 } SNOOP_RETURNENTRY;
609 typedef struct tagSNOOP_RETURNENTRIES {
610 SNOOP_RETURNENTRY entry[4092/sizeof(SNOOP_RETURNENTRY)];
611 struct tagSNOOP_RETURNENTRIES *next;
612 } SNOOP_RETURNENTRIES;
614 #include "poppack.h"
616 extern void WINAPI SNOOP_Entry(void);
617 extern void WINAPI SNOOP_Return(void);
619 static SNOOP_DLL *firstdll;
620 static SNOOP_RETURNENTRIES *firstrets;
623 /***********************************************************************
624 * SNOOP_ShowDebugmsgSnoop
626 * Simple function to decide if a particular debugging message is
627 * wanted.
629 static BOOL SNOOP_ShowDebugmsgSnoop(const char *module, int ordinal, const char *func)
631 if (debug_snoop_excludelist && check_list( module, ordinal, func, debug_snoop_excludelist ))
632 return FALSE;
633 if (debug_snoop_includelist && !check_list( module, ordinal, func, debug_snoop_includelist ))
634 return FALSE;
635 return TRUE;
639 /***********************************************************************
640 * SNOOP_SetupDLL
642 * Setup snoop debugging for a native dll.
644 void SNOOP_SetupDLL(HMODULE hmod)
646 SNOOP_DLL **dll = &firstdll;
647 char *p, *name;
648 void *addr;
649 SIZE_T size;
650 ULONG size32;
651 IMAGE_EXPORT_DIRECTORY *exports;
653 if (!init_done) init_debug_lists();
655 exports = RtlImageDirectoryEntryToData( hmod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size32 );
656 if (!exports) return;
657 name = (char *)hmod + exports->Name;
658 size = size32;
660 TRACE_(snoop)("hmod=%p, name=%s\n", hmod, name);
662 while (*dll) {
663 if ((*dll)->hmod == hmod)
665 /* another dll, loaded at the same address */
666 addr = (*dll)->funs;
667 size = (*dll)->nrofordinals * sizeof(SNOOP_FUN);
668 NtFreeVirtualMemory(NtCurrentProcess(), &addr, &size, MEM_RELEASE);
669 break;
671 dll = &((*dll)->next);
673 if (*dll)
674 *dll = RtlReAllocateHeap(GetProcessHeap(),
675 HEAP_ZERO_MEMORY, *dll,
676 sizeof(SNOOP_DLL) + strlen(name));
677 else
678 *dll = RtlAllocateHeap(GetProcessHeap(),
679 HEAP_ZERO_MEMORY,
680 sizeof(SNOOP_DLL) + strlen(name));
681 (*dll)->hmod = hmod;
682 (*dll)->ordbase = exports->Base;
683 (*dll)->nrofordinals = exports->NumberOfFunctions;
684 strcpy( (*dll)->name, name );
685 p = (*dll)->name + strlen((*dll)->name) - 4;
686 if (p > (*dll)->name && !strcasecmp( p, ".dll" )) *p = 0;
688 size = exports->NumberOfFunctions * sizeof(SNOOP_FUN);
689 addr = NULL;
690 NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size,
691 MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
692 if (!addr) {
693 RtlFreeHeap(GetProcessHeap(),0,*dll);
694 FIXME("out of memory\n");
695 return;
697 (*dll)->funs = addr;
698 memset((*dll)->funs,0,size);
702 /***********************************************************************
703 * SNOOP_GetProcAddress
705 * Return the proc address to use for a given function.
707 FARPROC SNOOP_GetProcAddress( HMODULE hmod, const IMAGE_EXPORT_DIRECTORY *exports,
708 DWORD exp_size, FARPROC origfun, DWORD ordinal,
709 const WCHAR *user)
711 unsigned int i;
712 const char *ename;
713 const WORD *ordinals;
714 const DWORD *names;
715 SNOOP_DLL *dll = firstdll;
716 SNOOP_FUN *fun;
717 const IMAGE_SECTION_HEADER *sec;
719 if (!TRACE_ON(snoop)) return origfun;
720 if (!check_from_module( debug_from_snoop_includelist, debug_from_snoop_excludelist, user ))
721 return origfun; /* the calling module was explicitly excluded */
723 if (!*(LPBYTE)origfun) /* 0x00 is an imposs. opcode, poss. dataref. */
724 return origfun;
726 sec = RtlImageRvaToSection( RtlImageNtHeader(hmod), hmod, (char *)origfun - (char *)hmod );
728 if (!sec || !(sec->Characteristics & IMAGE_SCN_CNT_CODE))
729 return origfun; /* most likely a data reference */
731 while (dll) {
732 if (hmod == dll->hmod)
733 break;
734 dll = dll->next;
736 if (!dll) /* probably internal */
737 return origfun;
739 /* try to find a name for it */
740 ename = NULL;
741 names = (const DWORD *)((const char *)hmod + exports->AddressOfNames);
742 ordinals = (const WORD *)((const char *)hmod + exports->AddressOfNameOrdinals);
743 if (names) for (i = 0; i < exports->NumberOfNames; i++)
745 if (ordinals[i] == ordinal)
747 ename = (const char *)hmod + names[i];
748 break;
751 if (!SNOOP_ShowDebugmsgSnoop(dll->name,ordinal,ename))
752 return origfun;
753 assert(ordinal < dll->nrofordinals);
754 fun = dll->funs + ordinal;
755 if (!fun->name)
757 fun->name = ename;
758 fun->lcall = 0xe8;
759 /* NOTE: origreturn struct member MUST come directly after snoopentry */
760 fun->snoopentry = (char*)SNOOP_Entry-((char*)(&fun->nrofargs));
761 fun->origfun = origfun;
762 fun->nrofargs = -1;
764 return (FARPROC)&(fun->lcall);
767 static void SNOOP_PrintArg(DWORD x)
769 #if 0
770 int i,nostring;
772 DPRINTF("%08x",x);
773 if (!HIWORD(x) || TRACE_ON(seh)) return; /* trivial reject to avoid faults */
774 __TRY
776 LPBYTE s=(LPBYTE)x;
777 i=0;nostring=0;
778 while (i<80) {
779 if (s[i]==0) break;
780 if (s[i]<0x20) {nostring=1;break;}
781 if (s[i]>=0x80) {nostring=1;break;}
782 i++;
784 if (!nostring && i > 5)
785 DPRINTF(" %s",debugstr_an((LPSTR)x,i));
786 else /* try unicode */
788 LPWSTR s=(LPWSTR)x;
789 i=0;nostring=0;
790 while (i<80) {
791 if (s[i]==0) break;
792 if (s[i]<0x20) {nostring=1;break;}
793 if (s[i]>0x100) {nostring=1;break;}
794 i++;
796 if (!nostring && i > 5) DPRINTF(" %s",debugstr_wn((LPWSTR)x,i));
799 __EXCEPT_PAGE_FAULT
802 __ENDTRY
803 #else
804 DPRINTF("%08x",x);
805 #endif
808 #define CALLER1REF (*(DWORD*)context->Esp)
810 void WINAPI __regs_SNOOP_Entry( CONTEXT86 *context )
812 DWORD ordinal=0,entry = context->Eip - 5;
813 SNOOP_DLL *dll = firstdll;
814 SNOOP_FUN *fun = NULL;
815 SNOOP_RETURNENTRIES **rets = &firstrets;
816 SNOOP_RETURNENTRY *ret;
817 int i=0, max;
819 while (dll) {
820 if ( ((char*)entry>=(char*)dll->funs) &&
821 ((char*)entry<=(char*)(dll->funs+dll->nrofordinals))
823 fun = (SNOOP_FUN*)entry;
824 ordinal = fun-dll->funs;
825 break;
827 dll=dll->next;
829 if (!dll) {
830 FIXME("entrypoint 0x%08x not found\n",entry);
831 return; /* oops */
833 /* guess cdecl ... */
834 if (fun->nrofargs<0) {
835 /* Typical cdecl return frame is:
836 * add esp, xxxxxxxx
837 * which has (for xxxxxxxx up to 255 the opcode "83 C4 xx".
838 * (after that 81 C2 xx xx xx xx)
840 LPBYTE reteip = (LPBYTE)CALLER1REF;
842 if (reteip) {
843 if ((reteip[0]==0x83)&&(reteip[1]==0xc4))
844 fun->nrofargs=reteip[2]/4;
849 while (*rets) {
850 for (i=0;i<sizeof((*rets)->entry)/sizeof((*rets)->entry[0]);i++)
851 if (!(*rets)->entry[i].origreturn)
852 break;
853 if (i!=sizeof((*rets)->entry)/sizeof((*rets)->entry[0]))
854 break;
855 rets = &((*rets)->next);
857 if (!*rets) {
858 SIZE_T size = 4096;
859 VOID* addr = NULL;
861 NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size,
862 MEM_COMMIT | MEM_RESERVE,
863 PAGE_EXECUTE_READWRITE);
864 if (!addr) return;
865 *rets = addr;
866 memset(*rets,0,4096);
867 i = 0; /* entry 0 is free */
869 ret = &((*rets)->entry[i]);
870 ret->lcall = 0xe8;
871 /* NOTE: origreturn struct member MUST come directly after snoopret */
872 ret->snoopret = ((char*)SNOOP_Return)-(char*)(&ret->origreturn);
873 ret->origreturn = (FARPROC)CALLER1REF;
874 CALLER1REF = (DWORD)&ret->lcall;
875 ret->dll = dll;
876 ret->args = NULL;
877 ret->ordinal = ordinal;
878 ret->origESP = context->Esp;
880 context->Eip = (DWORD)fun->origfun;
882 if (fun->name) DPRINTF("%04x:CALL %s.%s(",GetCurrentThreadId(),dll->name,fun->name);
883 else DPRINTF("%04x:CALL %s.%d(",GetCurrentThreadId(),dll->name,dll->ordbase+ordinal);
884 if (fun->nrofargs>0) {
885 max = fun->nrofargs; if (max>16) max=16;
886 for (i=0;i<max;i++)
888 SNOOP_PrintArg(*(DWORD*)(context->Esp + 4 + sizeof(DWORD)*i));
889 if (i<fun->nrofargs-1) DPRINTF(",");
891 if (max!=fun->nrofargs)
892 DPRINTF(" ...");
893 } else if (fun->nrofargs<0) {
894 DPRINTF("<unknown, check return>");
895 ret->args = RtlAllocateHeap(GetProcessHeap(),
896 0,16*sizeof(DWORD));
897 memcpy(ret->args,(LPBYTE)(context->Esp + 4),sizeof(DWORD)*16);
899 DPRINTF(") ret=%08x\n",(DWORD)ret->origreturn);
903 void WINAPI __regs_SNOOP_Return( CONTEXT86 *context )
905 SNOOP_RETURNENTRY *ret = (SNOOP_RETURNENTRY*)(context->Eip - 5);
906 SNOOP_FUN *fun = &ret->dll->funs[ret->ordinal];
908 /* We haven't found out the nrofargs yet. If we called a cdecl
909 * function it is too late anyway and we can just set '0' (which
910 * will be the difference between orig and current ESP
911 * If stdcall -> everything ok.
913 if (ret->dll->funs[ret->ordinal].nrofargs<0)
914 ret->dll->funs[ret->ordinal].nrofargs=(context->Esp - ret->origESP-4)/4;
915 context->Eip = (DWORD)ret->origreturn;
916 if (ret->args) {
917 int i,max;
919 if (fun->name)
920 DPRINTF("%04x:RET %s.%s(", GetCurrentThreadId(), ret->dll->name, fun->name);
921 else
922 DPRINTF("%04x:RET %s.%d(", GetCurrentThreadId(),
923 ret->dll->name,ret->dll->ordbase+ret->ordinal);
925 max = fun->nrofargs;
926 if (max>16) max=16;
928 for (i=0;i<max;i++)
930 SNOOP_PrintArg(ret->args[i]);
931 if (i<max-1) DPRINTF(",");
933 DPRINTF(") retval=%08x ret=%08x\n",
934 context->Eax,(DWORD)ret->origreturn );
935 RtlFreeHeap(GetProcessHeap(),0,ret->args);
936 ret->args = NULL;
938 else
940 if (fun->name)
941 DPRINTF("%04x:RET %s.%s() retval=%08x ret=%08x\n",
942 GetCurrentThreadId(),
943 ret->dll->name, fun->name, context->Eax, (DWORD)ret->origreturn);
944 else
945 DPRINTF("%04x:RET %s.%d() retval=%08x ret=%08x\n",
946 GetCurrentThreadId(),
947 ret->dll->name,ret->dll->ordbase+ret->ordinal,
948 context->Eax, (DWORD)ret->origreturn);
950 ret->origreturn = NULL; /* mark as empty */
953 /* assembly wrappers that save the context */
954 DEFINE_REGS_ENTRYPOINT( SNOOP_Entry, 0, 0 );
955 DEFINE_REGS_ENTRYPOINT( SNOOP_Return, 0, 0 );
957 #else /* __i386__ */
959 FARPROC RELAY_GetProcAddress( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
960 DWORD exp_size, FARPROC proc, DWORD ordinal, const WCHAR *user )
962 return proc;
965 FARPROC SNOOP_GetProcAddress( HMODULE hmod, const IMAGE_EXPORT_DIRECTORY *exports, DWORD exp_size,
966 FARPROC origfun, DWORD ordinal, const WCHAR *user )
968 return origfun;
971 void RELAY_SetupDLL( HMODULE module )
975 void SNOOP_SetupDLL( HMODULE hmod )
977 FIXME("snooping works only on i386 for now.\n");
980 #endif /* __i386__ */