push c22b4aa826b27f0c6bc5101b378e6e68716a85d9
[wine/hacks.git] / dlls / ntdll / relay.c
blob6dec576f44412ef7d350d91b078371180181055c
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 "ntstatus.h"
31 #define WIN32_NO_STATUS
32 #include "windef.h"
33 #include "winternl.h"
34 #include "wine/exception.h"
35 #include "ntdll_misc.h"
36 #include "wine/unicode.h"
37 #include "wine/debug.h"
39 WINE_DEFAULT_DEBUG_CHANNEL(relay);
41 #if defined(__i386__) || defined(__x86_64__)
43 struct relay_descr /* descriptor for a module */
45 void *magic; /* signature */
46 void *relay_call; /* functions to call from relay thunks */
47 void *relay_call_regs;
48 void *private; /* reserved for the relay code private data */
49 const char *entry_point_base; /* base address of entry point thunks */
50 const unsigned int *entry_point_offsets; /* offsets of entry points thunks */
51 const unsigned int *arg_types; /* table of argument types for all entry points */
54 #define RELAY_DESCR_MAGIC ((void *)0xdeb90001)
56 /* private data built at dll load time */
58 struct relay_entry_point
60 void *orig_func; /* original entry point function */
61 const char *name; /* function name (if any) */
64 struct relay_private_data
66 HMODULE module; /* module handle of this dll */
67 unsigned int base; /* ordinal base */
68 char dllname[40]; /* dll name (without .dll extension) */
69 struct relay_entry_point entry_points[1]; /* list of dll entry points */
72 static const WCHAR **debug_relay_excludelist;
73 static const WCHAR **debug_relay_includelist;
74 static const WCHAR **debug_snoop_excludelist;
75 static const WCHAR **debug_snoop_includelist;
76 static const WCHAR **debug_from_relay_excludelist;
77 static const WCHAR **debug_from_relay_includelist;
78 static const WCHAR **debug_from_snoop_excludelist;
79 static const WCHAR **debug_from_snoop_includelist;
81 static BOOL init_done;
83 /* compare an ASCII and a Unicode string without depending on the current codepage */
84 static inline int strcmpAW( const char *strA, const WCHAR *strW )
86 while (*strA && ((unsigned char)*strA == *strW)) { strA++; strW++; }
87 return (unsigned char)*strA - *strW;
90 /* compare an ASCII and a Unicode string without depending on the current codepage */
91 static inline int strncmpiAW( const char *strA, const WCHAR *strW, int n )
93 int ret = 0;
94 for ( ; n > 0; n--, strA++, strW++)
95 if ((ret = toupperW((unsigned char)*strA) - toupperW(*strW)) || !*strA) break;
96 return ret;
99 /***********************************************************************
100 * build_list
102 * Build a function list from a ';'-separated string.
104 static const WCHAR **build_list( const WCHAR *buffer )
106 int count = 1;
107 const WCHAR *p = buffer;
108 const WCHAR **ret;
110 while ((p = strchrW( p, ';' )))
112 count++;
113 p++;
115 /* allocate count+1 pointers, plus the space for a copy of the string */
116 if ((ret = RtlAllocateHeap( GetProcessHeap(), 0,
117 (count+1) * sizeof(WCHAR*) + (strlenW(buffer)+1) * sizeof(WCHAR) )))
119 WCHAR *str = (WCHAR *)(ret + count + 1);
120 WCHAR *p = str;
122 strcpyW( str, buffer );
123 count = 0;
124 for (;;)
126 ret[count++] = p;
127 if (!(p = strchrW( p, ';' ))) break;
128 *p++ = 0;
130 ret[count++] = NULL;
132 return ret;
135 /***********************************************************************
136 * load_list_value
138 * Load a function list from a registry value.
140 static const WCHAR **load_list( HKEY hkey, const WCHAR *value )
142 char initial_buffer[4096];
143 char *buffer = initial_buffer;
144 DWORD count;
145 NTSTATUS status;
146 UNICODE_STRING name;
147 const WCHAR **list = NULL;
149 RtlInitUnicodeString( &name, value );
150 status = NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(buffer), &count );
151 if (status == STATUS_BUFFER_OVERFLOW)
153 buffer = RtlAllocateHeap( GetProcessHeap(), 0, count );
154 status = NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, count, &count );
156 if (status == STATUS_SUCCESS)
158 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)buffer)->Data;
159 list = build_list( str );
160 if (list) TRACE( "%s = %s\n", debugstr_w(value), debugstr_w(str) );
163 if (buffer != initial_buffer) RtlFreeHeap( GetProcessHeap(), 0, buffer );
164 return list;
167 /***********************************************************************
168 * init_debug_lists
170 * Build the relay include/exclude function lists.
172 static void init_debug_lists(void)
174 OBJECT_ATTRIBUTES attr;
175 UNICODE_STRING name;
176 HANDLE root, hkey;
177 static const WCHAR configW[] = {'S','o','f','t','w','a','r','e','\\',
178 'W','i','n','e','\\',
179 'D','e','b','u','g',0};
180 static const WCHAR RelayIncludeW[] = {'R','e','l','a','y','I','n','c','l','u','d','e',0};
181 static const WCHAR RelayExcludeW[] = {'R','e','l','a','y','E','x','c','l','u','d','e',0};
182 static const WCHAR SnoopIncludeW[] = {'S','n','o','o','p','I','n','c','l','u','d','e',0};
183 static const WCHAR SnoopExcludeW[] = {'S','n','o','o','p','E','x','c','l','u','d','e',0};
184 static const WCHAR RelayFromIncludeW[] = {'R','e','l','a','y','F','r','o','m','I','n','c','l','u','d','e',0};
185 static const WCHAR RelayFromExcludeW[] = {'R','e','l','a','y','F','r','o','m','E','x','c','l','u','d','e',0};
186 static const WCHAR SnoopFromIncludeW[] = {'S','n','o','o','p','F','r','o','m','I','n','c','l','u','d','e',0};
187 static const WCHAR SnoopFromExcludeW[] = {'S','n','o','o','p','F','r','o','m','E','x','c','l','u','d','e',0};
189 if (init_done) return;
190 init_done = TRUE;
192 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
193 attr.Length = sizeof(attr);
194 attr.RootDirectory = root;
195 attr.ObjectName = &name;
196 attr.Attributes = 0;
197 attr.SecurityDescriptor = NULL;
198 attr.SecurityQualityOfService = NULL;
199 RtlInitUnicodeString( &name, configW );
201 /* @@ Wine registry key: HKCU\Software\Wine\Debug */
202 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr )) hkey = 0;
203 NtClose( root );
204 if (!hkey) return;
206 debug_relay_includelist = load_list( hkey, RelayIncludeW );
207 debug_relay_excludelist = load_list( hkey, RelayExcludeW );
208 debug_snoop_includelist = load_list( hkey, SnoopIncludeW );
209 debug_snoop_excludelist = load_list( hkey, SnoopExcludeW );
210 debug_from_relay_includelist = load_list( hkey, RelayFromIncludeW );
211 debug_from_relay_excludelist = load_list( hkey, RelayFromExcludeW );
212 debug_from_snoop_includelist = load_list( hkey, SnoopFromIncludeW );
213 debug_from_snoop_excludelist = load_list( hkey, SnoopFromExcludeW );
215 NtClose( hkey );
219 /***********************************************************************
220 * check_list
222 * Check if a given module and function is in the list.
224 static BOOL check_list( const char *module, int ordinal, const char *func, const WCHAR *const *list )
226 char ord_str[10];
228 sprintf( ord_str, "%d", ordinal );
229 for(; *list; list++)
231 const WCHAR *p = strrchrW( *list, '.' );
232 if (p && p > *list) /* check module and function */
234 int len = p - *list;
235 if (strncmpiAW( module, *list, len-1 ) || module[len]) continue;
236 if (p[1] == '*' && !p[2]) return TRUE;
237 if (!strcmpAW( ord_str, p + 1 )) return TRUE;
238 if (func && !strcmpAW( func, p + 1 )) return TRUE;
240 else /* function only */
242 if (func && !strcmpAW( func, *list )) return TRUE;
245 return FALSE;
249 /***********************************************************************
250 * check_relay_include
252 * Check if a given function must be included in the relay output.
254 static BOOL check_relay_include( const char *module, int ordinal, const char *func )
256 if (debug_relay_excludelist && check_list( module, ordinal, func, debug_relay_excludelist ))
257 return FALSE;
258 if (debug_relay_includelist && !check_list( module, ordinal, func, debug_relay_includelist ))
259 return FALSE;
260 return TRUE;
263 /***********************************************************************
264 * check_from_module
266 * Check if calls from a given module must be included in the relay/snoop output,
267 * given the exclusion and inclusion lists.
269 static BOOL check_from_module( const WCHAR **includelist, const WCHAR **excludelist, const WCHAR *module )
271 static const WCHAR dllW[] = {'.','d','l','l',0 };
272 const WCHAR **listitem;
273 BOOL show;
275 if (!module) return TRUE;
276 if (!includelist && !excludelist) return TRUE;
277 if (excludelist)
279 show = TRUE;
280 listitem = excludelist;
282 else
284 show = FALSE;
285 listitem = includelist;
287 for(; *listitem; listitem++)
289 int len;
291 if (!strcmpiW( *listitem, module )) return !show;
292 len = strlenW( *listitem );
293 if (!strncmpiW( *listitem, module, len ) && !strcmpiW( module + len, dllW ))
294 return !show;
296 return show;
299 /***********************************************************************
300 * RELAY_PrintArgs
302 static inline void RELAY_PrintArgs( const INT_PTR *args, int nb_args, unsigned int typemask )
304 while (nb_args--)
306 if ((typemask & 3) && HIWORD(*args))
308 if (typemask & 2)
309 DPRINTF( "%08lx %s", *args, debugstr_w((LPCWSTR)*args) );
310 else
311 DPRINTF( "%08lx %s", *args, debugstr_a((LPCSTR)*args) );
313 else DPRINTF( "%08lx", *args );
314 if (nb_args) DPRINTF( "," );
315 args++;
316 typemask >>= 2;
320 extern LONGLONG CDECL call_entry_point( void *func, int nb_args, const INT_PTR *args );
321 #ifdef __i386__
322 __ASM_GLOBAL_FUNC( call_entry_point,
323 "\tpushl %ebp\n"
324 "\tmovl %esp,%ebp\n"
325 "\tpushl %esi\n"
326 "\tpushl %edi\n"
327 "\tmovl 12(%ebp),%edx\n"
328 "\tshll $2,%edx\n"
329 "\tjz 1f\n"
330 "\tsubl %edx,%esp\n"
331 "\tandl $~15,%esp\n"
332 "\tmovl 12(%ebp),%ecx\n"
333 "\tmovl 16(%ebp),%esi\n"
334 "\tmovl %esp,%edi\n"
335 "\tcld\n"
336 "\trep; movsl\n"
337 "1:\tcall *8(%ebp)\n"
338 "\tleal -8(%ebp),%esp\n"
339 "\tpopl %edi\n"
340 "\tpopl %esi\n"
341 "\tpopl %ebp\n"
342 "\tret" )
343 #else
344 __ASM_GLOBAL_FUNC( call_entry_point,
345 "\tpushq %rbp\n"
346 "\tmovq %rsp,%rbp\n"
347 "\tpushq %rsi\n"
348 "\tpushq %rdi\n"
349 "\tmovq %rcx,%rax\n"
350 "\tmovq $4,%rcx\n"
351 "\tcmp %rcx,%rdx\n"
352 "\tcmovgq %rdx,%rcx\n"
353 "\tleaq 0(,%rcx,8),%rdx\n"
354 "\tsubq %rdx,%rsp\n"
355 "\tandq $~15,%rsp\n"
356 "\tmovq %rsp,%rdi\n"
357 "\tmovq %r8,%rsi\n"
358 "\trep; movsq\n"
359 "\tmovq 0(%rsp),%rcx\n"
360 "\tmovq 8(%rsp),%rdx\n"
361 "\tmovq 16(%rsp),%r8\n"
362 "\tmovq 24(%rsp),%r9\n"
363 "\tcallq *%rax\n"
364 "\tleaq -16(%rbp),%rsp\n"
365 "\tpopq %rdi\n"
366 "\tpopq %rsi\n"
367 "\tpopq %rbp\n"
368 "\tret\n" )
369 #endif
372 /***********************************************************************
373 * relay_call
375 * stack points to the return address, i.e. the first argument is stack[1].
377 static LONGLONG WINAPI relay_call( struct relay_descr *descr, unsigned int idx, const INT_PTR *stack )
379 LONGLONG ret;
380 WORD ordinal = LOWORD(idx);
381 BYTE nb_args = LOBYTE(HIWORD(idx));
382 BYTE flags = HIBYTE(HIWORD(idx));
383 struct relay_private_data *data = descr->private;
384 struct relay_entry_point *entry_point = data->entry_points + ordinal;
386 if (!TRACE_ON(relay))
387 ret = call_entry_point( entry_point->orig_func, nb_args, stack + 1 );
388 else
390 if (entry_point->name)
391 DPRINTF( "%04x:Call %s.%s(", GetCurrentThreadId(), data->dllname, entry_point->name );
392 else
393 DPRINTF( "%04x:Call %s.%u(", GetCurrentThreadId(), data->dllname, data->base + ordinal );
394 RELAY_PrintArgs( stack + 1, nb_args, descr->arg_types[ordinal] );
395 DPRINTF( ") ret=%08lx\n", stack[0] );
397 ret = call_entry_point( entry_point->orig_func, nb_args, stack + 1 );
399 if (entry_point->name)
400 DPRINTF( "%04x:Ret %s.%s()", GetCurrentThreadId(), data->dllname, entry_point->name );
401 else
402 DPRINTF( "%04x:Ret %s.%u()", GetCurrentThreadId(), data->dllname, data->base + ordinal );
404 if (flags & 1) /* 64-bit return value */
405 DPRINTF( " retval=%08x%08x ret=%08lx\n",
406 (UINT)(ret >> 32), (UINT)ret, stack[0] );
407 else
408 DPRINTF( " retval=%08lx ret=%08lx\n", (UINT_PTR)ret, stack[0] );
410 return ret;
414 /***********************************************************************
415 * relay_call_regs
417 #ifdef __i386__
418 void WINAPI __regs_relay_call_regs( struct relay_descr *descr, unsigned int idx,
419 unsigned int orig_eax, unsigned int ret_addr,
420 CONTEXT86 *context )
422 WORD ordinal = LOWORD(idx);
423 BYTE nb_args = LOBYTE(HIWORD(idx));
424 BYTE flags = HIBYTE(HIWORD(idx));
425 struct relay_private_data *data = descr->private;
426 struct relay_entry_point *entry_point = data->entry_points + ordinal;
427 BYTE *orig_func = entry_point->orig_func;
428 INT_PTR *args = (INT_PTR *)context->Esp;
429 INT_PTR args_copy[32];
431 /* restore the context to what it was before the relay thunk */
432 context->Eax = orig_eax;
433 context->Eip = ret_addr;
434 if (flags & 2) /* stdcall */
435 context->Esp += nb_args * sizeof(int);
437 if (TRACE_ON(relay))
439 if (entry_point->name)
440 DPRINTF( "%04x:Call %s.%s(", GetCurrentThreadId(), data->dllname, entry_point->name );
441 else
442 DPRINTF( "%04x:Call %s.%u(", GetCurrentThreadId(), data->dllname, data->base + ordinal );
443 RELAY_PrintArgs( args, nb_args, descr->arg_types[ordinal] );
444 DPRINTF( ") ret=%08x\n", ret_addr );
446 DPRINTF( "%04x: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x "
447 "ebp=%08x esp=%08x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
448 GetCurrentThreadId(), context->Eax, context->Ebx, context->Ecx,
449 context->Edx, context->Esi, context->Edi, context->Ebp, context->Esp,
450 context->SegDs, context->SegEs, context->SegFs, context->SegGs, context->EFlags );
452 assert( orig_func[0] == 0x50 /* pushl %eax */ );
453 assert( orig_func[1] == 0xe8 /* call */ );
456 /* now call the real function */
458 memcpy( args_copy, args, nb_args * sizeof(args[0]) );
459 args_copy[nb_args++] = (int)context; /* append context argument */
461 call_entry_point( orig_func + 6 + *(int *)(orig_func + 6), nb_args, args_copy );
464 if (TRACE_ON(relay))
466 if (entry_point->name)
467 DPRINTF( "%04x:Ret %s.%s() retval=%08x ret=%08x\n",
468 GetCurrentThreadId(), data->dllname, entry_point->name,
469 context->Eax, context->Eip );
470 else
471 DPRINTF( "%04x:Ret %s.%u() retval=%08x ret=%08x\n",
472 GetCurrentThreadId(), data->dllname, data->base + ordinal,
473 context->Eax, context->Eip );
474 DPRINTF( "%04x: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x "
475 "ebp=%08x esp=%08x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
476 GetCurrentThreadId(), context->Eax, context->Ebx, context->Ecx,
477 context->Edx, context->Esi, context->Edi, context->Ebp, context->Esp,
478 context->SegDs, context->SegEs, context->SegFs, context->SegGs, context->EFlags );
481 extern void WINAPI relay_call_regs(void);
482 DEFINE_REGS_ENTRYPOINT( relay_call_regs, 16, 16 )
483 #endif
486 /***********************************************************************
487 * RELAY_GetProcAddress
489 * Return the proc address to use for a given function.
491 FARPROC RELAY_GetProcAddress( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
492 DWORD exp_size, FARPROC proc, DWORD ordinal, const WCHAR *user )
494 struct relay_private_data *data;
495 const struct relay_descr *descr = (const struct relay_descr *)((const char *)exports + exp_size);
497 if (descr->magic != RELAY_DESCR_MAGIC || !(data = descr->private)) return proc; /* no relay data */
498 if (!data->entry_points[ordinal].orig_func) return proc; /* not a relayed function */
499 if (check_from_module( debug_from_relay_includelist, debug_from_relay_excludelist, user ))
500 return proc; /* we want to relay it */
501 return data->entry_points[ordinal].orig_func;
505 /***********************************************************************
506 * RELAY_SetupDLL
508 * Setup relay debugging for a built-in dll.
510 void RELAY_SetupDLL( HMODULE module )
512 IMAGE_EXPORT_DIRECTORY *exports;
513 DWORD *funcs;
514 unsigned int i, len;
515 DWORD size, entry_point_rva;
516 struct relay_descr *descr;
517 struct relay_private_data *data;
518 const WORD *ordptr;
520 if (!init_done) init_debug_lists();
522 exports = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size );
523 if (!exports) return;
525 descr = (struct relay_descr *)((char *)exports + size);
526 if (descr->magic != RELAY_DESCR_MAGIC) return;
528 if (!(data = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data) +
529 (exports->NumberOfFunctions-1) * sizeof(data->entry_points) )))
530 return;
532 descr->relay_call = relay_call;
533 #ifdef __i386__
534 descr->relay_call_regs = relay_call_regs;
535 #endif
536 descr->private = data;
538 data->module = module;
539 data->base = exports->Base;
540 len = strlen( (char *)module + exports->Name );
541 if (len > 4 && !strcasecmp( (char *)module + exports->Name + len - 4, ".dll" )) len -= 4;
542 len = min( len, sizeof(data->dllname) - 1 );
543 memcpy( data->dllname, (char *)module + exports->Name, len );
544 data->dllname[len] = 0;
546 /* fetch name pointer for all entry points and store them in the private structure */
548 ordptr = (const WORD *)((char *)module + exports->AddressOfNameOrdinals);
549 for (i = 0; i < exports->NumberOfNames; i++, ordptr++)
551 DWORD name_rva = ((DWORD*)((char *)module + exports->AddressOfNames))[i];
552 data->entry_points[*ordptr].name = (const char *)module + name_rva;
555 /* patch the functions in the export table to point to the relay thunks */
557 funcs = (DWORD *)((char *)module + exports->AddressOfFunctions);
558 entry_point_rva = descr->entry_point_base - (const char *)module;
559 for (i = 0; i < exports->NumberOfFunctions; i++, funcs++)
561 if (!descr->entry_point_offsets[i]) continue; /* not a normal function */
562 if (!check_relay_include( data->dllname, i + exports->Base, data->entry_points[i].name ))
563 continue; /* don't include this entry point */
565 data->entry_points[i].orig_func = (char *)module + *funcs;
566 *funcs = entry_point_rva + descr->entry_point_offsets[i];
570 #else /* __i386__ || __x86_64__ */
572 FARPROC RELAY_GetProcAddress( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
573 DWORD exp_size, FARPROC proc, DWORD ordinal, const WCHAR *user )
575 return proc;
578 void RELAY_SetupDLL( HMODULE module )
582 #endif /* __i386__ || __x86_64__ */
585 /***********************************************************************/
586 /* snoop support */
587 /***********************************************************************/
589 #ifdef __i386__
591 WINE_DECLARE_DEBUG_CHANNEL(seh);
592 WINE_DECLARE_DEBUG_CHANNEL(snoop);
594 #include "pshpack1.h"
596 typedef struct
598 /* code part */
599 BYTE lcall; /* 0xe8 call snoopentry (relative) */
600 /* NOTE: If you move snoopentry OR nrofargs fix the relative offset
601 * calculation!
603 DWORD snoopentry; /* SNOOP_Entry relative */
604 /* unreached */
605 int nrofargs;
606 FARPROC origfun;
607 const char *name;
608 } SNOOP_FUN;
610 typedef struct tagSNOOP_DLL {
611 HMODULE hmod;
612 SNOOP_FUN *funs;
613 DWORD ordbase;
614 DWORD nrofordinals;
615 struct tagSNOOP_DLL *next;
616 char name[1];
617 } SNOOP_DLL;
619 typedef struct
621 /* code part */
622 BYTE lcall; /* 0xe8 call snoopret relative*/
623 /* NOTE: If you move snoopret OR origreturn fix the relative offset
624 * calculation!
626 DWORD snoopret; /* SNOOP_Ret relative */
627 /* unreached */
628 FARPROC origreturn;
629 SNOOP_DLL *dll;
630 DWORD ordinal;
631 DWORD origESP;
632 DWORD *args; /* saved args across a stdcall */
633 } SNOOP_RETURNENTRY;
635 typedef struct tagSNOOP_RETURNENTRIES {
636 SNOOP_RETURNENTRY entry[4092/sizeof(SNOOP_RETURNENTRY)];
637 struct tagSNOOP_RETURNENTRIES *next;
638 } SNOOP_RETURNENTRIES;
640 #include "poppack.h"
642 extern void WINAPI SNOOP_Entry(void);
643 extern void WINAPI SNOOP_Return(void);
645 static SNOOP_DLL *firstdll;
646 static SNOOP_RETURNENTRIES *firstrets;
649 /***********************************************************************
650 * SNOOP_ShowDebugmsgSnoop
652 * Simple function to decide if a particular debugging message is
653 * wanted.
655 static BOOL SNOOP_ShowDebugmsgSnoop(const char *module, int ordinal, const char *func)
657 if (debug_snoop_excludelist && check_list( module, ordinal, func, debug_snoop_excludelist ))
658 return FALSE;
659 if (debug_snoop_includelist && !check_list( module, ordinal, func, debug_snoop_includelist ))
660 return FALSE;
661 return TRUE;
665 /***********************************************************************
666 * SNOOP_SetupDLL
668 * Setup snoop debugging for a native dll.
670 void SNOOP_SetupDLL(HMODULE hmod)
672 SNOOP_DLL **dll = &firstdll;
673 char *p, *name;
674 void *addr;
675 SIZE_T size;
676 ULONG size32;
677 IMAGE_EXPORT_DIRECTORY *exports;
679 if (!init_done) init_debug_lists();
681 exports = RtlImageDirectoryEntryToData( hmod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size32 );
682 if (!exports || !exports->NumberOfFunctions) return;
683 name = (char *)hmod + exports->Name;
684 size = size32;
686 TRACE_(snoop)("hmod=%p, name=%s\n", hmod, name);
688 while (*dll) {
689 if ((*dll)->hmod == hmod)
691 /* another dll, loaded at the same address */
692 addr = (*dll)->funs;
693 size = (*dll)->nrofordinals * sizeof(SNOOP_FUN);
694 NtFreeVirtualMemory(NtCurrentProcess(), &addr, &size, MEM_RELEASE);
695 break;
697 dll = &((*dll)->next);
699 if (*dll)
700 *dll = RtlReAllocateHeap(GetProcessHeap(),
701 HEAP_ZERO_MEMORY, *dll,
702 sizeof(SNOOP_DLL) + strlen(name));
703 else
704 *dll = RtlAllocateHeap(GetProcessHeap(),
705 HEAP_ZERO_MEMORY,
706 sizeof(SNOOP_DLL) + strlen(name));
707 (*dll)->hmod = hmod;
708 (*dll)->ordbase = exports->Base;
709 (*dll)->nrofordinals = exports->NumberOfFunctions;
710 strcpy( (*dll)->name, name );
711 p = (*dll)->name + strlen((*dll)->name) - 4;
712 if (p > (*dll)->name && !strcasecmp( p, ".dll" )) *p = 0;
714 size = exports->NumberOfFunctions * sizeof(SNOOP_FUN);
715 addr = NULL;
716 NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size,
717 MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
718 if (!addr) {
719 RtlFreeHeap(GetProcessHeap(),0,*dll);
720 FIXME("out of memory\n");
721 return;
723 (*dll)->funs = addr;
724 memset((*dll)->funs,0,size);
728 /***********************************************************************
729 * SNOOP_GetProcAddress
731 * Return the proc address to use for a given function.
733 FARPROC SNOOP_GetProcAddress( HMODULE hmod, const IMAGE_EXPORT_DIRECTORY *exports,
734 DWORD exp_size, FARPROC origfun, DWORD ordinal,
735 const WCHAR *user)
737 unsigned int i;
738 const char *ename;
739 const WORD *ordinals;
740 const DWORD *names;
741 SNOOP_DLL *dll = firstdll;
742 SNOOP_FUN *fun;
743 const IMAGE_SECTION_HEADER *sec;
745 if (!TRACE_ON(snoop)) return origfun;
746 if (!check_from_module( debug_from_snoop_includelist, debug_from_snoop_excludelist, user ))
747 return origfun; /* the calling module was explicitly excluded */
749 if (!*(LPBYTE)origfun) /* 0x00 is an impossible opcode, possible dataref. */
750 return origfun;
752 sec = RtlImageRvaToSection( RtlImageNtHeader(hmod), hmod, (char *)origfun - (char *)hmod );
754 if (!sec || !(sec->Characteristics & IMAGE_SCN_CNT_CODE))
755 return origfun; /* most likely a data reference */
757 while (dll) {
758 if (hmod == dll->hmod)
759 break;
760 dll = dll->next;
762 if (!dll) /* probably internal */
763 return origfun;
765 /* try to find a name for it */
766 ename = NULL;
767 names = (const DWORD *)((const char *)hmod + exports->AddressOfNames);
768 ordinals = (const WORD *)((const char *)hmod + exports->AddressOfNameOrdinals);
769 if (names) for (i = 0; i < exports->NumberOfNames; i++)
771 if (ordinals[i] == ordinal)
773 ename = (const char *)hmod + names[i];
774 break;
777 if (!SNOOP_ShowDebugmsgSnoop(dll->name,ordinal,ename))
778 return origfun;
779 assert(ordinal < dll->nrofordinals);
780 fun = dll->funs + ordinal;
781 if (!fun->name)
783 fun->name = ename;
784 fun->lcall = 0xe8;
785 /* NOTE: origreturn struct member MUST come directly after snoopentry */
786 fun->snoopentry = (char*)SNOOP_Entry-((char*)(&fun->nrofargs));
787 fun->origfun = origfun;
788 fun->nrofargs = -1;
790 return (FARPROC)&(fun->lcall);
793 static void SNOOP_PrintArg(DWORD x)
795 int i,nostring;
797 DPRINTF("%08x",x);
798 if (!HIWORD(x) || TRACE_ON(seh)) return; /* trivial reject to avoid faults */
799 __TRY
801 LPBYTE s=(LPBYTE)x;
802 i=0;nostring=0;
803 while (i<80) {
804 if (s[i]==0) break;
805 if (s[i]<0x20) {nostring=1;break;}
806 if (s[i]>=0x80) {nostring=1;break;}
807 i++;
809 if (!nostring && i > 5)
810 DPRINTF(" %s",debugstr_an((LPSTR)x,i));
811 else /* try unicode */
813 LPWSTR s=(LPWSTR)x;
814 i=0;nostring=0;
815 while (i<80) {
816 if (s[i]==0) break;
817 if (s[i]<0x20) {nostring=1;break;}
818 if (s[i]>0x100) {nostring=1;break;}
819 i++;
821 if (!nostring && i > 5) DPRINTF(" %s",debugstr_wn((LPWSTR)x,i));
824 __EXCEPT_PAGE_FAULT
827 __ENDTRY
830 #define CALLER1REF (*(DWORD*)context->Esp)
832 void WINAPI __regs_SNOOP_Entry( CONTEXT86 *context )
834 DWORD ordinal=0,entry = context->Eip - 5;
835 SNOOP_DLL *dll = firstdll;
836 SNOOP_FUN *fun = NULL;
837 SNOOP_RETURNENTRIES **rets = &firstrets;
838 SNOOP_RETURNENTRY *ret;
839 int i=0, max;
841 while (dll) {
842 if ( ((char*)entry>=(char*)dll->funs) &&
843 ((char*)entry<=(char*)(dll->funs+dll->nrofordinals))
845 fun = (SNOOP_FUN*)entry;
846 ordinal = fun-dll->funs;
847 break;
849 dll=dll->next;
851 if (!dll) {
852 FIXME("entrypoint 0x%08x not found\n",entry);
853 return; /* oops */
855 /* guess cdecl ... */
856 if (fun->nrofargs<0) {
857 /* Typical cdecl return frame is:
858 * add esp, xxxxxxxx
859 * which has (for xxxxxxxx up to 255 the opcode "83 C4 xx".
860 * (after that 81 C2 xx xx xx xx)
862 LPBYTE reteip = (LPBYTE)CALLER1REF;
864 if (reteip) {
865 if ((reteip[0]==0x83)&&(reteip[1]==0xc4))
866 fun->nrofargs=reteip[2]/4;
871 while (*rets) {
872 for (i=0;i<sizeof((*rets)->entry)/sizeof((*rets)->entry[0]);i++)
873 if (!(*rets)->entry[i].origreturn)
874 break;
875 if (i!=sizeof((*rets)->entry)/sizeof((*rets)->entry[0]))
876 break;
877 rets = &((*rets)->next);
879 if (!*rets) {
880 SIZE_T size = 4096;
881 VOID* addr = NULL;
883 NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size,
884 MEM_COMMIT | MEM_RESERVE,
885 PAGE_EXECUTE_READWRITE);
886 if (!addr) return;
887 *rets = addr;
888 memset(*rets,0,4096);
889 i = 0; /* entry 0 is free */
891 ret = &((*rets)->entry[i]);
892 ret->lcall = 0xe8;
893 /* NOTE: origreturn struct member MUST come directly after snoopret */
894 ret->snoopret = ((char*)SNOOP_Return)-(char*)(&ret->origreturn);
895 ret->origreturn = (FARPROC)CALLER1REF;
896 CALLER1REF = (DWORD)&ret->lcall;
897 ret->dll = dll;
898 ret->args = NULL;
899 ret->ordinal = ordinal;
900 ret->origESP = context->Esp;
902 context->Eip = (DWORD)fun->origfun;
904 if (fun->name) DPRINTF("%04x:CALL %s.%s(",GetCurrentThreadId(),dll->name,fun->name);
905 else DPRINTF("%04x:CALL %s.%d(",GetCurrentThreadId(),dll->name,dll->ordbase+ordinal);
906 if (fun->nrofargs>0) {
907 max = fun->nrofargs; if (max>16) max=16;
908 for (i=0;i<max;i++)
910 SNOOP_PrintArg(*(DWORD*)(context->Esp + 4 + sizeof(DWORD)*i));
911 if (i<fun->nrofargs-1) DPRINTF(",");
913 if (max!=fun->nrofargs)
914 DPRINTF(" ...");
915 } else if (fun->nrofargs<0) {
916 DPRINTF("<unknown, check return>");
917 ret->args = RtlAllocateHeap(GetProcessHeap(),
918 0,16*sizeof(DWORD));
919 memcpy(ret->args,(LPBYTE)(context->Esp + 4),sizeof(DWORD)*16);
921 DPRINTF(") ret=%08x\n",(DWORD)ret->origreturn);
925 void WINAPI __regs_SNOOP_Return( CONTEXT86 *context )
927 SNOOP_RETURNENTRY *ret = (SNOOP_RETURNENTRY*)(context->Eip - 5);
928 SNOOP_FUN *fun = &ret->dll->funs[ret->ordinal];
930 /* We haven't found out the nrofargs yet. If we called a cdecl
931 * function it is too late anyway and we can just set '0' (which
932 * will be the difference between orig and current ESP
933 * If stdcall -> everything ok.
935 if (ret->dll->funs[ret->ordinal].nrofargs<0)
936 ret->dll->funs[ret->ordinal].nrofargs=(context->Esp - ret->origESP-4)/4;
937 context->Eip = (DWORD)ret->origreturn;
938 if (ret->args) {
939 int i,max;
941 if (fun->name)
942 DPRINTF("%04x:RET %s.%s(", GetCurrentThreadId(), ret->dll->name, fun->name);
943 else
944 DPRINTF("%04x:RET %s.%d(", GetCurrentThreadId(),
945 ret->dll->name,ret->dll->ordbase+ret->ordinal);
947 max = fun->nrofargs;
948 if (max>16) max=16;
950 for (i=0;i<max;i++)
952 SNOOP_PrintArg(ret->args[i]);
953 if (i<max-1) DPRINTF(",");
955 DPRINTF(") retval=%08x ret=%08x\n",
956 context->Eax,(DWORD)ret->origreturn );
957 RtlFreeHeap(GetProcessHeap(),0,ret->args);
958 ret->args = NULL;
960 else
962 if (fun->name)
963 DPRINTF("%04x:RET %s.%s() retval=%08x ret=%08x\n",
964 GetCurrentThreadId(),
965 ret->dll->name, fun->name, context->Eax, (DWORD)ret->origreturn);
966 else
967 DPRINTF("%04x:RET %s.%d() retval=%08x ret=%08x\n",
968 GetCurrentThreadId(),
969 ret->dll->name,ret->dll->ordbase+ret->ordinal,
970 context->Eax, (DWORD)ret->origreturn);
972 ret->origreturn = NULL; /* mark as empty */
975 /* assembly wrappers that save the context */
976 DEFINE_REGS_ENTRYPOINT( SNOOP_Entry, 0, 0 )
977 DEFINE_REGS_ENTRYPOINT( SNOOP_Return, 0, 0 )
979 #else /* __i386__ */
981 FARPROC SNOOP_GetProcAddress( HMODULE hmod, const IMAGE_EXPORT_DIRECTORY *exports, DWORD exp_size,
982 FARPROC origfun, DWORD ordinal, const WCHAR *user )
984 return origfun;
987 void SNOOP_SetupDLL( HMODULE hmod )
989 FIXME("snooping works only on i386 for now.\n");
992 #endif /* __i386__ */