ntdll: Check for case-insensitive volumes.
[wine.git] / dlls / ntdll / relay.c
blob4855a0003d14b31489c1dffcb4687a9c941f3b7e
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)
55 #define IS_INTARG(x) (((ULONG_PTR)(x) >> 16) == 0)
57 /* private data built at dll load time */
59 struct relay_entry_point
61 void *orig_func; /* original entry point function */
62 const char *name; /* function name (if any) */
65 struct relay_private_data
67 HMODULE module; /* module handle of this dll */
68 unsigned int base; /* ordinal base */
69 char dllname[40]; /* dll name (without .dll extension) */
70 struct relay_entry_point entry_points[1]; /* list of dll entry points */
73 static const WCHAR **debug_relay_excludelist;
74 static const WCHAR **debug_relay_includelist;
75 static const WCHAR **debug_snoop_excludelist;
76 static const WCHAR **debug_snoop_includelist;
77 static const WCHAR **debug_from_relay_excludelist;
78 static const WCHAR **debug_from_relay_includelist;
79 static const WCHAR **debug_from_snoop_excludelist;
80 static const WCHAR **debug_from_snoop_includelist;
82 static BOOL init_done;
84 /* compare an ASCII and a Unicode string without depending on the current codepage */
85 static inline int strcmpAW( const char *strA, const WCHAR *strW )
87 while (*strA && ((unsigned char)*strA == *strW)) { strA++; strW++; }
88 return (unsigned char)*strA - *strW;
91 /* compare an ASCII and a Unicode string without depending on the current codepage */
92 static inline int strncmpiAW( const char *strA, const WCHAR *strW, int n )
94 int ret = 0;
95 for ( ; n > 0; n--, strA++, strW++)
96 if ((ret = toupperW((unsigned char)*strA) - toupperW(*strW)) || !*strA) break;
97 return ret;
100 /***********************************************************************
101 * build_list
103 * Build a function list from a ';'-separated string.
105 static const WCHAR **build_list( const WCHAR *buffer )
107 int count = 1;
108 const WCHAR *p = buffer;
109 const WCHAR **ret;
111 while ((p = strchrW( p, ';' )))
113 count++;
114 p++;
116 /* allocate count+1 pointers, plus the space for a copy of the string */
117 if ((ret = RtlAllocateHeap( GetProcessHeap(), 0,
118 (count+1) * sizeof(WCHAR*) + (strlenW(buffer)+1) * sizeof(WCHAR) )))
120 WCHAR *str = (WCHAR *)(ret + count + 1);
121 WCHAR *p = str;
123 strcpyW( str, buffer );
124 count = 0;
125 for (;;)
127 ret[count++] = p;
128 if (!(p = strchrW( p, ';' ))) break;
129 *p++ = 0;
131 ret[count++] = NULL;
133 return ret;
136 /***********************************************************************
137 * load_list_value
139 * Load a function list from a registry value.
141 static const WCHAR **load_list( HKEY hkey, const WCHAR *value )
143 char initial_buffer[4096];
144 char *buffer = initial_buffer;
145 DWORD count;
146 NTSTATUS status;
147 UNICODE_STRING name;
148 const WCHAR **list = NULL;
150 RtlInitUnicodeString( &name, value );
151 status = NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, sizeof(initial_buffer), &count );
152 if (status == STATUS_BUFFER_OVERFLOW)
154 buffer = RtlAllocateHeap( GetProcessHeap(), 0, count );
155 status = NtQueryValueKey( hkey, &name, KeyValuePartialInformation, buffer, count, &count );
157 if (status == STATUS_SUCCESS)
159 WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)buffer)->Data;
160 list = build_list( str );
161 if (list) TRACE( "%s = %s\n", debugstr_w(value), debugstr_w(str) );
164 if (buffer != initial_buffer) RtlFreeHeap( GetProcessHeap(), 0, buffer );
165 return list;
168 /***********************************************************************
169 * init_debug_lists
171 * Build the relay include/exclude function lists.
173 static void init_debug_lists(void)
175 OBJECT_ATTRIBUTES attr;
176 UNICODE_STRING name;
177 HANDLE root, hkey;
178 static const WCHAR configW[] = {'S','o','f','t','w','a','r','e','\\',
179 'W','i','n','e','\\',
180 'D','e','b','u','g',0};
181 static const WCHAR RelayIncludeW[] = {'R','e','l','a','y','I','n','c','l','u','d','e',0};
182 static const WCHAR RelayExcludeW[] = {'R','e','l','a','y','E','x','c','l','u','d','e',0};
183 static const WCHAR SnoopIncludeW[] = {'S','n','o','o','p','I','n','c','l','u','d','e',0};
184 static const WCHAR SnoopExcludeW[] = {'S','n','o','o','p','E','x','c','l','u','d','e',0};
185 static const WCHAR RelayFromIncludeW[] = {'R','e','l','a','y','F','r','o','m','I','n','c','l','u','d','e',0};
186 static const WCHAR RelayFromExcludeW[] = {'R','e','l','a','y','F','r','o','m','E','x','c','l','u','d','e',0};
187 static const WCHAR SnoopFromIncludeW[] = {'S','n','o','o','p','F','r','o','m','I','n','c','l','u','d','e',0};
188 static const WCHAR SnoopFromExcludeW[] = {'S','n','o','o','p','F','r','o','m','E','x','c','l','u','d','e',0};
190 if (init_done) return;
191 init_done = TRUE;
193 RtlOpenCurrentUser( KEY_ALL_ACCESS, &root );
194 attr.Length = sizeof(attr);
195 attr.RootDirectory = root;
196 attr.ObjectName = &name;
197 attr.Attributes = 0;
198 attr.SecurityDescriptor = NULL;
199 attr.SecurityQualityOfService = NULL;
200 RtlInitUnicodeString( &name, configW );
202 /* @@ Wine registry key: HKCU\Software\Wine\Debug */
203 if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr )) hkey = 0;
204 NtClose( root );
205 if (!hkey) return;
207 debug_relay_includelist = load_list( hkey, RelayIncludeW );
208 debug_relay_excludelist = load_list( hkey, RelayExcludeW );
209 debug_snoop_includelist = load_list( hkey, SnoopIncludeW );
210 debug_snoop_excludelist = load_list( hkey, SnoopExcludeW );
211 debug_from_relay_includelist = load_list( hkey, RelayFromIncludeW );
212 debug_from_relay_excludelist = load_list( hkey, RelayFromExcludeW );
213 debug_from_snoop_includelist = load_list( hkey, SnoopFromIncludeW );
214 debug_from_snoop_excludelist = load_list( hkey, SnoopFromExcludeW );
216 NtClose( hkey );
220 /***********************************************************************
221 * check_list
223 * Check if a given module and function is in the list.
225 static BOOL check_list( const char *module, int ordinal, const char *func, const WCHAR *const *list )
227 char ord_str[10];
229 sprintf( ord_str, "%d", ordinal );
230 for(; *list; list++)
232 const WCHAR *p = strrchrW( *list, '.' );
233 if (p && p > *list) /* check module and function */
235 int len = p - *list;
236 if (strncmpiAW( module, *list, len-1 ) || module[len]) continue;
237 if (p[1] == '*' && !p[2]) return TRUE;
238 if (!strcmpAW( ord_str, p + 1 )) return TRUE;
239 if (func && !strcmpAW( func, p + 1 )) return TRUE;
241 else /* function only */
243 if (func && !strcmpAW( func, *list )) return TRUE;
246 return FALSE;
250 /***********************************************************************
251 * check_relay_include
253 * Check if a given function must be included in the relay output.
255 static BOOL check_relay_include( const char *module, int ordinal, const char *func )
257 if (debug_relay_excludelist && check_list( module, ordinal, func, debug_relay_excludelist ))
258 return FALSE;
259 if (debug_relay_includelist && !check_list( module, ordinal, func, debug_relay_includelist ))
260 return FALSE;
261 return TRUE;
264 /***********************************************************************
265 * check_from_module
267 * Check if calls from a given module must be included in the relay/snoop output,
268 * given the exclusion and inclusion lists.
270 static BOOL check_from_module( const WCHAR **includelist, const WCHAR **excludelist, const WCHAR *module )
272 static const WCHAR dllW[] = {'.','d','l','l',0 };
273 const WCHAR **listitem;
274 BOOL show;
276 if (!module) return TRUE;
277 if (!includelist && !excludelist) return TRUE;
278 if (excludelist)
280 show = TRUE;
281 listitem = excludelist;
283 else
285 show = FALSE;
286 listitem = includelist;
288 for(; *listitem; listitem++)
290 int len;
292 if (!strcmpiW( *listitem, module )) return !show;
293 len = strlenW( *listitem );
294 if (!strncmpiW( *listitem, module, len ) && !strcmpiW( module + len, dllW ))
295 return !show;
297 return show;
300 /***********************************************************************
301 * RELAY_PrintArgs
303 static inline void RELAY_PrintArgs( const INT_PTR *args, int nb_args, unsigned int typemask )
305 while (nb_args--)
307 if ((typemask & 3) && !IS_INTARG(*args))
309 if (typemask & 2)
310 DPRINTF( "%08lx %s", *args, debugstr_w((LPCWSTR)*args) );
311 else
312 DPRINTF( "%08lx %s", *args, debugstr_a((LPCSTR)*args) );
314 else DPRINTF( "%08lx", *args );
315 if (nb_args) DPRINTF( "," );
316 args++;
317 typemask >>= 2;
321 extern LONGLONG CDECL call_entry_point( void *func, int nb_args, const INT_PTR *args, int flags );
322 #ifdef __i386__
323 __ASM_GLOBAL_FUNC( call_entry_point,
324 "pushl %ebp\n\t"
325 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
326 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
327 "movl %esp,%ebp\n\t"
328 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
329 "pushl %esi\n\t"
330 __ASM_CFI(".cfi_rel_offset %esi,-4\n\t")
331 "pushl %edi\n\t"
332 __ASM_CFI(".cfi_rel_offset %edi,-8\n\t")
333 "movl 12(%ebp),%edx\n\t"
334 "shll $2,%edx\n\t"
335 "jz 1f\n\t"
336 "subl %edx,%esp\n\t"
337 "andl $~15,%esp\n\t"
338 "movl 12(%ebp),%ecx\n\t"
339 "movl 16(%ebp),%esi\n\t"
340 "movl %esp,%edi\n\t"
341 "cld\n\t"
342 "rep; movsl\n"
343 "testl $2,20(%ebp)\n\t" /* (flags & 2) -> thiscall */
344 "jz 1f\n\t"
345 "popl %ecx\n\t"
346 "1:\tcall *8(%ebp)\n\t"
347 "leal -8(%ebp),%esp\n\t"
348 "popl %edi\n\t"
349 __ASM_CFI(".cfi_same_value %edi\n\t")
350 "popl %esi\n\t"
351 __ASM_CFI(".cfi_same_value %esi\n\t")
352 "popl %ebp\n\t"
353 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
354 __ASM_CFI(".cfi_same_value %ebp\n\t")
355 "ret" )
356 #else
357 __ASM_GLOBAL_FUNC( call_entry_point,
358 "pushq %rbp\n\t"
359 __ASM_CFI(".cfi_adjust_cfa_offset 8\n\t")
360 __ASM_CFI(".cfi_rel_offset %rbp,0\n\t")
361 "movq %rsp,%rbp\n\t"
362 __ASM_CFI(".cfi_def_cfa_register %rbp\n\t")
363 "pushq %rsi\n\t"
364 __ASM_CFI(".cfi_rel_offset %rsi,-8\n\t")
365 "pushq %rdi\n\t"
366 __ASM_CFI(".cfi_rel_offset %rdi,-16\n\t")
367 "movq %rcx,%rax\n\t"
368 "movq $4,%rcx\n\t"
369 "cmp %rcx,%rdx\n\t"
370 "cmovgq %rdx,%rcx\n\t"
371 "leaq 0(,%rcx,8),%rdx\n\t"
372 "subq %rdx,%rsp\n\t"
373 "andq $~15,%rsp\n\t"
374 "movq %rsp,%rdi\n\t"
375 "movq %r8,%rsi\n\t"
376 "rep; movsq\n\t"
377 "movq 0(%rsp),%rcx\n\t"
378 "movq 8(%rsp),%rdx\n\t"
379 "movq 16(%rsp),%r8\n\t"
380 "movq 24(%rsp),%r9\n\t"
381 "movq %rcx,%xmm0\n\t"
382 "movq %rdx,%xmm1\n\t"
383 "movq %r8,%xmm2\n\t"
384 "movq %r9,%xmm3\n\t"
385 "callq *%rax\n\t"
386 "leaq -16(%rbp),%rsp\n\t"
387 "popq %rdi\n\t"
388 __ASM_CFI(".cfi_same_value %rdi\n\t")
389 "popq %rsi\n\t"
390 __ASM_CFI(".cfi_same_value %rsi\n\t")
391 __ASM_CFI(".cfi_def_cfa_register %rsp\n\t")
392 "popq %rbp\n\t"
393 __ASM_CFI(".cfi_adjust_cfa_offset -8\n\t")
394 __ASM_CFI(".cfi_same_value %rbp\n\t")
395 "ret")
396 #endif
399 /***********************************************************************
400 * relay_call
402 * stack points to the return address, i.e. the first argument is stack[1].
404 static LONGLONG WINAPI relay_call( struct relay_descr *descr, unsigned int idx, const INT_PTR *stack )
406 LONGLONG ret;
407 WORD ordinal = LOWORD(idx);
408 BYTE nb_args = LOBYTE(HIWORD(idx));
409 BYTE flags = HIBYTE(HIWORD(idx));
410 struct relay_private_data *data = descr->private;
411 struct relay_entry_point *entry_point = data->entry_points + ordinal;
413 if (!TRACE_ON(relay))
414 ret = call_entry_point( entry_point->orig_func, nb_args, stack + 1, flags );
415 else
417 if (entry_point->name)
418 DPRINTF( "%04x:Call %s.%s(", GetCurrentThreadId(), data->dllname, entry_point->name );
419 else
420 DPRINTF( "%04x:Call %s.%u(", GetCurrentThreadId(), data->dllname, data->base + ordinal );
421 RELAY_PrintArgs( stack + 1, nb_args, descr->arg_types[ordinal] );
422 DPRINTF( ") ret=%08lx\n", stack[0] );
424 ret = call_entry_point( entry_point->orig_func, nb_args, stack + 1, flags );
426 if (entry_point->name)
427 DPRINTF( "%04x:Ret %s.%s()", GetCurrentThreadId(), data->dllname, entry_point->name );
428 else
429 DPRINTF( "%04x:Ret %s.%u()", GetCurrentThreadId(), data->dllname, data->base + ordinal );
431 if (flags & 1) /* 64-bit return value */
432 DPRINTF( " retval=%08x%08x ret=%08lx\n",
433 (UINT)(ret >> 32), (UINT)ret, stack[0] );
434 else
435 DPRINTF( " retval=%08lx ret=%08lx\n", (UINT_PTR)ret, stack[0] );
437 return ret;
441 /***********************************************************************
442 * relay_call_regs
444 #ifdef __i386__
445 void WINAPI __regs_relay_call_regs( struct relay_descr *descr, unsigned int idx,
446 unsigned int orig_eax, unsigned int ret_addr,
447 CONTEXT *context )
449 WORD ordinal = LOWORD(idx);
450 BYTE nb_args = LOBYTE(HIWORD(idx));
451 struct relay_private_data *data = descr->private;
452 struct relay_entry_point *entry_point = data->entry_points + ordinal;
453 BYTE *orig_func = entry_point->orig_func;
454 INT_PTR *args = (INT_PTR *)context->Esp;
455 INT_PTR args_copy[32];
457 /* restore the context to what it was before the relay thunk */
458 context->Eax = orig_eax;
459 context->Eip = ret_addr;
460 context->Esp += nb_args * sizeof(int);
462 if (TRACE_ON(relay))
464 if (entry_point->name)
465 DPRINTF( "%04x:Call %s.%s(", GetCurrentThreadId(), data->dllname, entry_point->name );
466 else
467 DPRINTF( "%04x:Call %s.%u(", GetCurrentThreadId(), data->dllname, data->base + ordinal );
468 RELAY_PrintArgs( args, nb_args, descr->arg_types[ordinal] );
469 DPRINTF( ") ret=%08x\n", ret_addr );
471 DPRINTF( "%04x: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x "
472 "ebp=%08x esp=%08x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
473 GetCurrentThreadId(), context->Eax, context->Ebx, context->Ecx,
474 context->Edx, context->Esi, context->Edi, context->Ebp, context->Esp,
475 context->SegDs, context->SegEs, context->SegFs, context->SegGs, context->EFlags );
477 assert( orig_func[0] == 0x68 /* pushl func */ );
478 assert( orig_func[5] == 0x6a /* pushl args */ );
479 assert( orig_func[7] == 0xe8 /* call */ );
482 /* now call the real function */
484 memcpy( args_copy, args, nb_args * sizeof(args[0]) );
485 args_copy[nb_args++] = (INT_PTR)context; /* append context argument */
487 call_entry_point( orig_func + 12 + *(int *)(orig_func + 1), nb_args, args_copy, 0 );
490 if (TRACE_ON(relay))
492 if (entry_point->name)
493 DPRINTF( "%04x:Ret %s.%s() retval=%08x ret=%08x\n",
494 GetCurrentThreadId(), data->dllname, entry_point->name,
495 context->Eax, context->Eip );
496 else
497 DPRINTF( "%04x:Ret %s.%u() retval=%08x ret=%08x\n",
498 GetCurrentThreadId(), data->dllname, data->base + ordinal,
499 context->Eax, context->Eip );
500 DPRINTF( "%04x: eax=%08x ebx=%08x ecx=%08x edx=%08x esi=%08x edi=%08x "
501 "ebp=%08x esp=%08x ds=%04x es=%04x fs=%04x gs=%04x flags=%08x\n",
502 GetCurrentThreadId(), context->Eax, context->Ebx, context->Ecx,
503 context->Edx, context->Esi, context->Edi, context->Ebp, context->Esp,
504 context->SegDs, context->SegEs, context->SegFs, context->SegGs, context->EFlags );
507 extern void WINAPI relay_call_regs(void);
508 DEFINE_REGS_ENTRYPOINT( relay_call_regs, 4 )
510 #else /* __i386__ */
512 void WINAPI relay_call_regs( struct relay_descr *descr, INT_PTR idx, INT_PTR *stack )
514 assert(0); /* should never be called */
517 #endif /* __i386__ */
520 /***********************************************************************
521 * RELAY_GetProcAddress
523 * Return the proc address to use for a given function.
525 FARPROC RELAY_GetProcAddress( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
526 DWORD exp_size, FARPROC proc, DWORD ordinal, const WCHAR *user )
528 struct relay_private_data *data;
529 const struct relay_descr *descr = (const struct relay_descr *)((const char *)exports + exp_size);
531 if (descr->magic != RELAY_DESCR_MAGIC || !(data = descr->private)) return proc; /* no relay data */
532 if (!data->entry_points[ordinal].orig_func) return proc; /* not a relayed function */
533 if (check_from_module( debug_from_relay_includelist, debug_from_relay_excludelist, user ))
534 return proc; /* we want to relay it */
535 return data->entry_points[ordinal].orig_func;
539 /***********************************************************************
540 * RELAY_SetupDLL
542 * Setup relay debugging for a built-in dll.
544 void RELAY_SetupDLL( HMODULE module )
546 IMAGE_EXPORT_DIRECTORY *exports;
547 DWORD *funcs;
548 unsigned int i, len;
549 DWORD size, entry_point_rva;
550 struct relay_descr *descr;
551 struct relay_private_data *data;
552 const WORD *ordptr;
554 if (!init_done) init_debug_lists();
556 exports = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size );
557 if (!exports) return;
559 descr = (struct relay_descr *)((char *)exports + size);
560 if (descr->magic != RELAY_DESCR_MAGIC) return;
562 if (!(data = RtlAllocateHeap( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*data) +
563 (exports->NumberOfFunctions-1) * sizeof(data->entry_points) )))
564 return;
566 descr->relay_call = relay_call;
567 descr->relay_call_regs = relay_call_regs;
568 descr->private = data;
570 data->module = module;
571 data->base = exports->Base;
572 len = strlen( (char *)module + exports->Name );
573 if (len > 4 && !strcasecmp( (char *)module + exports->Name + len - 4, ".dll" )) len -= 4;
574 len = min( len, sizeof(data->dllname) - 1 );
575 memcpy( data->dllname, (char *)module + exports->Name, len );
576 data->dllname[len] = 0;
578 /* fetch name pointer for all entry points and store them in the private structure */
580 ordptr = (const WORD *)((char *)module + exports->AddressOfNameOrdinals);
581 for (i = 0; i < exports->NumberOfNames; i++, ordptr++)
583 DWORD name_rva = ((DWORD*)((char *)module + exports->AddressOfNames))[i];
584 data->entry_points[*ordptr].name = (const char *)module + name_rva;
587 /* patch the functions in the export table to point to the relay thunks */
589 funcs = (DWORD *)((char *)module + exports->AddressOfFunctions);
590 entry_point_rva = descr->entry_point_base - (const char *)module;
591 for (i = 0; i < exports->NumberOfFunctions; i++, funcs++)
593 if (!descr->entry_point_offsets[i]) continue; /* not a normal function */
594 if (!check_relay_include( data->dllname, i + exports->Base, data->entry_points[i].name ))
595 continue; /* don't include this entry point */
597 data->entry_points[i].orig_func = (char *)module + *funcs;
598 *funcs = entry_point_rva + descr->entry_point_offsets[i];
602 #else /* __i386__ || __x86_64__ */
604 FARPROC RELAY_GetProcAddress( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
605 DWORD exp_size, FARPROC proc, DWORD ordinal, const WCHAR *user )
607 return proc;
610 void RELAY_SetupDLL( HMODULE module )
614 #endif /* __i386__ || __x86_64__ */
617 /***********************************************************************/
618 /* snoop support */
619 /***********************************************************************/
621 #ifdef __i386__
623 WINE_DECLARE_DEBUG_CHANNEL(seh);
624 WINE_DECLARE_DEBUG_CHANNEL(snoop);
626 #include "pshpack1.h"
628 typedef struct
630 /* code part */
631 BYTE lcall; /* 0xe8 call snoopentry (relative) */
632 /* NOTE: If you move snoopentry OR nrofargs fix the relative offset
633 * calculation!
635 DWORD snoopentry; /* SNOOP_Entry relative */
636 /* unreached */
637 int nrofargs;
638 FARPROC origfun;
639 const char *name;
640 } SNOOP_FUN;
642 typedef struct tagSNOOP_DLL {
643 HMODULE hmod;
644 SNOOP_FUN *funs;
645 DWORD ordbase;
646 DWORD nrofordinals;
647 struct tagSNOOP_DLL *next;
648 char name[1];
649 } SNOOP_DLL;
651 typedef struct
653 /* code part */
654 BYTE lcall; /* 0xe8 call snoopret relative*/
655 /* NOTE: If you move snoopret OR origreturn fix the relative offset
656 * calculation!
658 DWORD snoopret; /* SNOOP_Ret relative */
659 /* unreached */
660 FARPROC origreturn;
661 SNOOP_DLL *dll;
662 DWORD ordinal;
663 DWORD origESP;
664 DWORD *args; /* saved args across a stdcall */
665 } SNOOP_RETURNENTRY;
667 typedef struct tagSNOOP_RETURNENTRIES {
668 SNOOP_RETURNENTRY entry[4092/sizeof(SNOOP_RETURNENTRY)];
669 struct tagSNOOP_RETURNENTRIES *next;
670 } SNOOP_RETURNENTRIES;
672 #include "poppack.h"
674 extern void WINAPI SNOOP_Entry(void);
675 extern void WINAPI SNOOP_Return(void);
677 static SNOOP_DLL *firstdll;
678 static SNOOP_RETURNENTRIES *firstrets;
681 /***********************************************************************
682 * SNOOP_ShowDebugmsgSnoop
684 * Simple function to decide if a particular debugging message is
685 * wanted.
687 static BOOL SNOOP_ShowDebugmsgSnoop(const char *module, int ordinal, const char *func)
689 if (debug_snoop_excludelist && check_list( module, ordinal, func, debug_snoop_excludelist ))
690 return FALSE;
691 if (debug_snoop_includelist && !check_list( module, ordinal, func, debug_snoop_includelist ))
692 return FALSE;
693 return TRUE;
697 /***********************************************************************
698 * SNOOP_SetupDLL
700 * Setup snoop debugging for a native dll.
702 void SNOOP_SetupDLL(HMODULE hmod)
704 SNOOP_DLL **dll = &firstdll;
705 char *p, *name;
706 void *addr;
707 SIZE_T size;
708 ULONG size32;
709 IMAGE_EXPORT_DIRECTORY *exports;
711 if (!init_done) init_debug_lists();
713 exports = RtlImageDirectoryEntryToData( hmod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &size32 );
714 if (!exports || !exports->NumberOfFunctions) return;
715 name = (char *)hmod + exports->Name;
716 size = size32;
718 TRACE_(snoop)("hmod=%p, name=%s\n", hmod, name);
720 while (*dll) {
721 if ((*dll)->hmod == hmod)
723 /* another dll, loaded at the same address */
724 addr = (*dll)->funs;
725 size = (*dll)->nrofordinals * sizeof(SNOOP_FUN);
726 NtFreeVirtualMemory(NtCurrentProcess(), &addr, &size, MEM_RELEASE);
727 break;
729 dll = &((*dll)->next);
731 if (*dll)
732 *dll = RtlReAllocateHeap(GetProcessHeap(),
733 HEAP_ZERO_MEMORY, *dll,
734 sizeof(SNOOP_DLL) + strlen(name));
735 else
736 *dll = RtlAllocateHeap(GetProcessHeap(),
737 HEAP_ZERO_MEMORY,
738 sizeof(SNOOP_DLL) + strlen(name));
739 (*dll)->hmod = hmod;
740 (*dll)->ordbase = exports->Base;
741 (*dll)->nrofordinals = exports->NumberOfFunctions;
742 strcpy( (*dll)->name, name );
743 p = (*dll)->name + strlen((*dll)->name) - 4;
744 if (p > (*dll)->name && !strcasecmp( p, ".dll" )) *p = 0;
746 size = exports->NumberOfFunctions * sizeof(SNOOP_FUN);
747 addr = NULL;
748 NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size,
749 MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
750 if (!addr) {
751 RtlFreeHeap(GetProcessHeap(),0,*dll);
752 FIXME("out of memory\n");
753 return;
755 (*dll)->funs = addr;
756 memset((*dll)->funs,0,size);
760 /***********************************************************************
761 * SNOOP_GetProcAddress
763 * Return the proc address to use for a given function.
765 FARPROC SNOOP_GetProcAddress( HMODULE hmod, const IMAGE_EXPORT_DIRECTORY *exports,
766 DWORD exp_size, FARPROC origfun, DWORD ordinal,
767 const WCHAR *user)
769 unsigned int i;
770 const char *ename;
771 const WORD *ordinals;
772 const DWORD *names;
773 SNOOP_DLL *dll = firstdll;
774 SNOOP_FUN *fun;
775 const IMAGE_SECTION_HEADER *sec;
777 if (!TRACE_ON(snoop)) return origfun;
778 if (!check_from_module( debug_from_snoop_includelist, debug_from_snoop_excludelist, user ))
779 return origfun; /* the calling module was explicitly excluded */
781 if (!*(LPBYTE)origfun) /* 0x00 is an impossible opcode, possible dataref. */
782 return origfun;
784 sec = RtlImageRvaToSection( RtlImageNtHeader(hmod), hmod, (char *)origfun - (char *)hmod );
786 if (!sec || !(sec->Characteristics & IMAGE_SCN_CNT_CODE))
787 return origfun; /* most likely a data reference */
789 while (dll) {
790 if (hmod == dll->hmod)
791 break;
792 dll = dll->next;
794 if (!dll) /* probably internal */
795 return origfun;
797 /* try to find a name for it */
798 ename = NULL;
799 names = (const DWORD *)((const char *)hmod + exports->AddressOfNames);
800 ordinals = (const WORD *)((const char *)hmod + exports->AddressOfNameOrdinals);
801 if (names) for (i = 0; i < exports->NumberOfNames; i++)
803 if (ordinals[i] == ordinal)
805 ename = (const char *)hmod + names[i];
806 break;
809 if (!SNOOP_ShowDebugmsgSnoop(dll->name,ordinal,ename))
810 return origfun;
811 assert(ordinal < dll->nrofordinals);
812 fun = dll->funs + ordinal;
813 if (!fun->name)
815 fun->name = ename;
816 fun->lcall = 0xe8;
817 /* NOTE: origreturn struct member MUST come directly after snoopentry */
818 fun->snoopentry = (char*)SNOOP_Entry-((char*)(&fun->nrofargs));
819 fun->origfun = origfun;
820 fun->nrofargs = -1;
822 return (FARPROC)&(fun->lcall);
825 static void SNOOP_PrintArg(DWORD x)
827 int i,nostring;
829 DPRINTF("%08x",x);
830 if (IS_INTARG(x) || TRACE_ON(seh)) return; /* trivial reject to avoid faults */
831 __TRY
833 LPBYTE s=(LPBYTE)x;
834 i=0;nostring=0;
835 while (i<80) {
836 if (s[i]==0) break;
837 if (s[i]<0x20) {nostring=1;break;}
838 if (s[i]>=0x80) {nostring=1;break;}
839 i++;
841 if (!nostring && i > 5)
842 DPRINTF(" %s",debugstr_an((LPSTR)x,i));
843 else /* try unicode */
845 LPWSTR s=(LPWSTR)x;
846 i=0;nostring=0;
847 while (i<80) {
848 if (s[i]==0) break;
849 if (s[i]<0x20) {nostring=1;break;}
850 if (s[i]>0x100) {nostring=1;break;}
851 i++;
853 if (!nostring && i > 5) DPRINTF(" %s",debugstr_wn((LPWSTR)x,i));
856 __EXCEPT_PAGE_FAULT
859 __ENDTRY
862 #define CALLER1REF (*(DWORD*)context->Esp)
864 void WINAPI __regs_SNOOP_Entry( CONTEXT *context )
866 DWORD ordinal=0,entry = context->Eip - 5;
867 SNOOP_DLL *dll = firstdll;
868 SNOOP_FUN *fun = NULL;
869 SNOOP_RETURNENTRIES **rets = &firstrets;
870 SNOOP_RETURNENTRY *ret;
871 int i=0, max;
873 while (dll) {
874 if ( ((char*)entry>=(char*)dll->funs) &&
875 ((char*)entry<=(char*)(dll->funs+dll->nrofordinals))
877 fun = (SNOOP_FUN*)entry;
878 ordinal = fun-dll->funs;
879 break;
881 dll=dll->next;
883 if (!dll) {
884 FIXME("entrypoint 0x%08x not found\n",entry);
885 return; /* oops */
887 /* guess cdecl ... */
888 if (fun->nrofargs<0) {
889 /* Typical cdecl return frame is:
890 * add esp, xxxxxxxx
891 * which has (for xxxxxxxx up to 255 the opcode "83 C4 xx".
892 * (after that 81 C2 xx xx xx xx)
894 LPBYTE reteip = (LPBYTE)CALLER1REF;
896 if (reteip) {
897 if ((reteip[0]==0x83)&&(reteip[1]==0xc4))
898 fun->nrofargs=reteip[2]/4;
903 while (*rets) {
904 for (i=0;i<sizeof((*rets)->entry)/sizeof((*rets)->entry[0]);i++)
905 if (!(*rets)->entry[i].origreturn)
906 break;
907 if (i!=sizeof((*rets)->entry)/sizeof((*rets)->entry[0]))
908 break;
909 rets = &((*rets)->next);
911 if (!*rets) {
912 SIZE_T size = 4096;
913 VOID* addr = NULL;
915 NtAllocateVirtualMemory(NtCurrentProcess(), &addr, 0, &size,
916 MEM_COMMIT | MEM_RESERVE,
917 PAGE_EXECUTE_READWRITE);
918 if (!addr) return;
919 *rets = addr;
920 memset(*rets,0,4096);
921 i = 0; /* entry 0 is free */
923 ret = &((*rets)->entry[i]);
924 ret->lcall = 0xe8;
925 /* NOTE: origreturn struct member MUST come directly after snoopret */
926 ret->snoopret = ((char*)SNOOP_Return)-(char*)(&ret->origreturn);
927 ret->origreturn = (FARPROC)CALLER1REF;
928 CALLER1REF = (DWORD)&ret->lcall;
929 ret->dll = dll;
930 ret->args = NULL;
931 ret->ordinal = ordinal;
932 ret->origESP = context->Esp;
934 context->Eip = (DWORD)fun->origfun;
936 if (fun->name) DPRINTF("%04x:CALL %s.%s(",GetCurrentThreadId(),dll->name,fun->name);
937 else DPRINTF("%04x:CALL %s.%d(",GetCurrentThreadId(),dll->name,dll->ordbase+ordinal);
938 if (fun->nrofargs>0) {
939 max = fun->nrofargs; if (max>16) max=16;
940 for (i=0;i<max;i++)
942 SNOOP_PrintArg(*(DWORD*)(context->Esp + 4 + sizeof(DWORD)*i));
943 if (i<fun->nrofargs-1) DPRINTF(",");
945 if (max!=fun->nrofargs)
946 DPRINTF(" ...");
947 } else if (fun->nrofargs<0) {
948 DPRINTF("<unknown, check return>");
949 ret->args = RtlAllocateHeap(GetProcessHeap(),
950 0,16*sizeof(DWORD));
951 memcpy(ret->args,(LPBYTE)(context->Esp + 4),sizeof(DWORD)*16);
953 DPRINTF(") ret=%08x\n",(DWORD)ret->origreturn);
957 void WINAPI __regs_SNOOP_Return( CONTEXT *context )
959 SNOOP_RETURNENTRY *ret = (SNOOP_RETURNENTRY*)(context->Eip - 5);
960 SNOOP_FUN *fun = &ret->dll->funs[ret->ordinal];
962 /* We haven't found out the nrofargs yet. If we called a cdecl
963 * function it is too late anyway and we can just set '0' (which
964 * will be the difference between orig and current ESP
965 * If stdcall -> everything ok.
967 if (ret->dll->funs[ret->ordinal].nrofargs<0)
968 ret->dll->funs[ret->ordinal].nrofargs=(context->Esp - ret->origESP-4)/4;
969 context->Eip = (DWORD)ret->origreturn;
970 if (ret->args) {
971 int i,max;
973 if (fun->name)
974 DPRINTF("%04x:RET %s.%s(", GetCurrentThreadId(), ret->dll->name, fun->name);
975 else
976 DPRINTF("%04x:RET %s.%d(", GetCurrentThreadId(),
977 ret->dll->name,ret->dll->ordbase+ret->ordinal);
979 max = fun->nrofargs;
980 if (max>16) max=16;
982 for (i=0;i<max;i++)
984 SNOOP_PrintArg(ret->args[i]);
985 if (i<max-1) DPRINTF(",");
987 DPRINTF(") retval=%08x ret=%08x\n",
988 context->Eax,(DWORD)ret->origreturn );
989 RtlFreeHeap(GetProcessHeap(),0,ret->args);
990 ret->args = NULL;
992 else
994 if (fun->name)
995 DPRINTF("%04x:RET %s.%s() retval=%08x ret=%08x\n",
996 GetCurrentThreadId(),
997 ret->dll->name, fun->name, context->Eax, (DWORD)ret->origreturn);
998 else
999 DPRINTF("%04x:RET %s.%d() retval=%08x ret=%08x\n",
1000 GetCurrentThreadId(),
1001 ret->dll->name,ret->dll->ordbase+ret->ordinal,
1002 context->Eax, (DWORD)ret->origreturn);
1004 ret->origreturn = NULL; /* mark as empty */
1007 /* assembly wrappers that save the context */
1008 DEFINE_REGS_ENTRYPOINT( SNOOP_Entry, 0 )
1009 DEFINE_REGS_ENTRYPOINT( SNOOP_Return, 0 )
1011 #else /* __i386__ */
1013 FARPROC SNOOP_GetProcAddress( HMODULE hmod, const IMAGE_EXPORT_DIRECTORY *exports, DWORD exp_size,
1014 FARPROC origfun, DWORD ordinal, const WCHAR *user )
1016 return origfun;
1019 void SNOOP_SetupDLL( HMODULE hmod )
1021 FIXME("snooping works only on i386 for now.\n");
1024 #endif /* __i386__ */