kernel32: Exclude unused headers.
[wine] / dlls / kernel32 / wowthunk.c
1 /*
2  * Win32 WOW Generic Thunk API
3  *
4  * Copyright 1999 Ulrich Weigand
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <stdarg.h>
26
27 #include "wine/winbase16.h"
28 #include "windef.h"
29 #include "winbase.h"
30 #include "winerror.h"
31 #include "wownt32.h"
32 #include "excpt.h"
33 #include "thread.h"
34 #include "winternl.h"
35 #include "kernel_private.h"
36 #include "kernel16_private.h"
37 #include "wine/exception.h"
38 #include "wine/debug.h"
39
40 WINE_DEFAULT_DEBUG_CHANNEL(thunk);
41 WINE_DECLARE_DEBUG_CHANNEL(relay);
42 WINE_DECLARE_DEBUG_CHANNEL(snoop);
43
44 /*
45  * These are the 16-bit side WOW routines.  They reside in wownt16.h
46  * in the SDK; since we don't support Win16 source code anyway, I've
47  * placed them here for compilation with Wine ...
48  */
49
50 DWORD WINAPI GetVDMPointer32W16(SEGPTR,UINT16);
51
52 DWORD WINAPI LoadLibraryEx32W16(LPCSTR,DWORD,DWORD);
53 DWORD WINAPI GetProcAddress32W16(DWORD,LPCSTR);
54 DWORD WINAPI FreeLibrary32W16(DWORD);
55
56 #define CPEX_DEST_STDCALL   0x00000000L
57 #define CPEX_DEST_CDECL     0x80000000L
58
59
60 #ifdef __i386__
61
62 /* symbols exported from relay16.s */
63 extern DWORD WINAPI wine_call_to_16( FARPROC16 target, DWORD cbArgs, PEXCEPTION_HANDLER handler );
64 extern void WINAPI wine_call_to_16_regs( CONTEXT86 *context, DWORD cbArgs, PEXCEPTION_HANDLER handler );
65 extern void __wine_call_to_16_ret(void);
66 extern void CALL32_CBClient_Ret();
67 extern void CALL32_CBClientEx_Ret();
68 extern void DPMI_PendingEventCheck();
69 extern void DPMI_PendingEventCheck_Cleanup();
70 extern void DPMI_PendingEventCheck_Return();
71 extern BYTE __wine_call16_start[];
72 extern BYTE __wine_call16_end[];
73
74 extern void RELAY16_InitDebugLists(void);
75
76 static SEGPTR call16_ret_addr;  /* segptr to __wine_call_to_16_ret routine */
77
78 static WORD  dpmi_checker_selector;
79 static DWORD dpmi_checker_offset_call;
80 static DWORD dpmi_checker_offset_cleanup;
81 static DWORD dpmi_checker_offset_return;
82
83 /***********************************************************************
84  *           WOWTHUNK_Init
85  */
86 BOOL WOWTHUNK_Init(void)
87 {
88     /* allocate the code selector for CallTo16 routines */
89     LDT_ENTRY entry;
90     WORD codesel = wine_ldt_alloc_entries(1);
91
92     if (!codesel) return FALSE;
93     wine_ldt_set_base( &entry, __wine_call16_start );
94     wine_ldt_set_limit( &entry, (BYTE *)(&CallTo16_TebSelector + 1) - __wine_call16_start - 1 );
95     wine_ldt_set_flags( &entry, WINE_LDT_FLAGS_CODE | WINE_LDT_FLAGS_32BIT );
96     wine_ldt_set_entry( codesel, &entry );
97
98       /* Patch the return addresses for CallTo16 routines */
99
100     CallTo16_DataSelector = wine_get_ds();
101     call16_ret_addr = MAKESEGPTR( codesel, (BYTE *)__wine_call_to_16_ret - __wine_call16_start );
102     CALL32_CBClient_RetAddr =
103         MAKESEGPTR( codesel, (BYTE *)CALL32_CBClient_Ret - __wine_call16_start );
104     CALL32_CBClientEx_RetAddr =
105         MAKESEGPTR( codesel, (BYTE *)CALL32_CBClientEx_Ret - __wine_call16_start );
106
107     /* Prepare selector and offsets for DPMI event checking. */
108     dpmi_checker_selector = codesel;
109     dpmi_checker_offset_call = (BYTE *)DPMI_PendingEventCheck - __wine_call16_start;
110     dpmi_checker_offset_cleanup = (BYTE *)DPMI_PendingEventCheck_Cleanup - __wine_call16_start;
111     dpmi_checker_offset_return = (BYTE *)DPMI_PendingEventCheck_Return - __wine_call16_start;
112
113     if (TRACE_ON(relay) || TRACE_ON(snoop)) RELAY16_InitDebugLists();
114
115     return TRUE;
116 }
117
118
119 /*************************************************************
120  *            fix_selector
121  *
122  * Fix a selector load that caused an exception if it's in the
123  * 16-bit relay code.
124  */
125 static BOOL fix_selector( CONTEXT *context )
126 {
127     WORD *stack;
128     BYTE *instr = (BYTE *)context->Eip;
129
130     if (instr < __wine_call16_start || instr >= __wine_call16_end) return FALSE;
131
132     /* skip prefixes */
133     while (*instr == 0x66 || *instr == 0x67) instr++;
134
135     switch(instr[0])
136     {
137     case 0x07: /* pop es */
138     case 0x17: /* pop ss */
139     case 0x1f: /* pop ds */
140         break;
141     case 0x0f: /* extended instruction */
142         switch(instr[1])
143         {
144         case 0xa1: /* pop fs */
145         case 0xa9: /* pop gs */
146             break;
147         default:
148             return FALSE;
149         }
150         break;
151     default:
152         return FALSE;
153     }
154     stack = wine_ldt_get_ptr( context->SegSs, context->Esp );
155     TRACE( "fixing up selector %x for pop instruction\n", *stack );
156     *stack = 0;
157     return TRUE;
158 }
159
160
161 /*************************************************************
162  *            insert_event_check
163  *
164  * Make resuming the context check for pending DPMI events
165  * before the original context is restored. This is required
166  * because DPMI events are asynchronous, they are blocked while 
167  * Wine 32-bit code is being executed and we want to prevent 
168  * a race when returning back to 16-bit or 32-bit DPMI context.
169  */
170 static void insert_event_check( CONTEXT *context )
171 {
172     char *stack = wine_ldt_get_ptr( context->SegSs, context->Esp );
173
174     /* don't do event check while in system code */
175     if (wine_ldt_is_system(context->SegCs))
176         return;
177
178     if(context->SegCs == dpmi_checker_selector &&
179        context->Eip   >= dpmi_checker_offset_call && 
180        context->Eip   <= dpmi_checker_offset_cleanup)
181     {
182         /*
183          * Nested call. Stack will be preserved. 
184          */
185     }
186     else if(context->SegCs == dpmi_checker_selector &&
187             context->Eip   == dpmi_checker_offset_return)
188     {
189         /*
190          * Nested call. We have just finished popping the fs
191          * register, lets put it back into stack.
192          */
193
194         stack -= sizeof(WORD);
195         *(WORD*)stack = context->SegFs;
196
197         context->Esp -= 2;
198     }
199     else
200     {
201         /*
202          * Call is not nested.
203          * Push modified registers into stack.
204          * These will be popped by the assembler stub.
205          */
206
207         stack -= sizeof(DWORD);
208         *(DWORD*)stack = context->EFlags;
209    
210         stack -= sizeof(DWORD);
211         *(DWORD*)stack = context->SegCs;
212
213         stack -= sizeof(DWORD);
214         *(DWORD*)stack = context->Eip;
215
216         stack -= sizeof(WORD);
217         *(WORD*)stack = context->SegFs;
218
219         context->Esp  -= 14;
220     }
221
222     /*
223      * Modify the context so that we jump into assembler stub.
224      * TEB access is made easier by providing the stub
225      * with the correct fs register value.
226      */
227
228     context->SegCs = dpmi_checker_selector;
229     context->Eip   = dpmi_checker_offset_call;
230     context->SegFs = wine_get_fs();
231 }
232
233
234 /*************************************************************
235  *            call16_handler
236  *
237  * Handler for exceptions occurring in 16-bit code.
238  */
239 static DWORD call16_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
240                              CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
241 {
242     if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
243     {
244         /* unwinding: restore the stack pointer in the TEB, and leave the Win16 mutex */
245         STACK32FRAME *frame32 = (STACK32FRAME *)((char *)frame - offsetof(STACK32FRAME,frame));
246         NtCurrentTeb()->WOW32Reserved = (void *)frame32->frame16;
247         _LeaveWin16Lock();
248     }
249     else if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION ||
250              record->ExceptionCode == EXCEPTION_PRIV_INSTRUCTION)
251     {
252         if (wine_ldt_is_system(context->SegCs))
253         {
254             if (fix_selector( context )) return ExceptionContinueExecution;
255         }
256         else
257         {
258             SEGPTR gpHandler;
259             DWORD ret = INSTR_EmulateInstruction( record, context );
260
261             /*
262              * Insert check for pending DPMI events. Note that this 
263              * check must be inserted after instructions have been 
264              * emulated because the instruction emulation requires
265              * original CS:IP and the emulation may change TEB.dpmi_vif.
266              */
267             if(NtCurrentTeb()->dpmi_vif)
268                 insert_event_check( context );
269
270             if (ret != ExceptionContinueSearch) return ret;
271
272             /* check for Win16 __GP handler */
273             if ((gpHandler = HasGPHandler16( MAKESEGPTR( context->SegCs, context->Eip ) )))
274             {
275                 WORD *stack = wine_ldt_get_ptr( context->SegSs, context->Esp );
276                 *--stack = context->SegCs;
277                 *--stack = context->Eip;
278
279                 if (!IS_SELECTOR_32BIT(context->SegSs))
280                     context->Esp = MAKELONG( LOWORD(context->Esp - 2*sizeof(WORD)),
281                                              HIWORD(context->Esp) );
282                 else
283                     context->Esp -= 2*sizeof(WORD);
284
285                 context->SegCs = SELECTOROF( gpHandler );
286                 context->Eip   = OFFSETOF( gpHandler );
287                 return ExceptionContinueExecution;
288             }
289         }
290     }
291     else if (record->ExceptionCode == EXCEPTION_VM86_STI)
292     {
293         insert_event_check( context );
294     }
295     return ExceptionContinueSearch;
296 }
297
298
299 /*************************************************************
300  *            vm86_handler
301  *
302  * Handler for exceptions occurring in vm86 code.
303  */
304 static DWORD vm86_handler( EXCEPTION_RECORD *record, EXCEPTION_REGISTRATION_RECORD *frame,
305                            CONTEXT *context, EXCEPTION_REGISTRATION_RECORD **pdispatcher )
306 {
307     if (record->ExceptionFlags & (EH_UNWINDING | EH_EXIT_UNWIND))
308         return ExceptionContinueSearch;
309
310     if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION ||
311         record->ExceptionCode == EXCEPTION_PRIV_INSTRUCTION)
312     {
313         return INSTR_EmulateInstruction( record, context );
314     }
315
316     return ExceptionContinueSearch;
317 }
318
319
320 #else  /* __i386__ */
321
322 BOOL WOWTHUNK_Init(void)
323 {
324     return TRUE;
325 }
326
327 #endif  /* __i386__ */
328
329
330 /*
331  *  32-bit WOW routines (in WOW32, but actually forwarded to KERNEL32)
332  */
333
334 /**********************************************************************
335  *           K32WOWGetDescriptor        (KERNEL32.70)
336  */
337 BOOL WINAPI K32WOWGetDescriptor( SEGPTR segptr, LPLDT_ENTRY ldtent )
338 {
339     return GetThreadSelectorEntry( GetCurrentThread(),
340                                    segptr >> 16, ldtent );
341 }
342
343 /**********************************************************************
344  *           K32WOWGetVDMPointer        (KERNEL32.56)
345  */
346 LPVOID WINAPI K32WOWGetVDMPointer( DWORD vp, DWORD dwBytes, BOOL fProtectedMode )
347 {
348     /* FIXME: add size check too */
349
350     if ( fProtectedMode )
351         return MapSL( vp );
352     else
353         return DOSMEM_MapRealToLinear( vp );
354 }
355
356 /**********************************************************************
357  *           K32WOWGetVDMPointerFix     (KERNEL32.68)
358  */
359 LPVOID WINAPI K32WOWGetVDMPointerFix( DWORD vp, DWORD dwBytes, BOOL fProtectedMode )
360 {
361     /*
362      * Hmmm. According to the docu, we should call:
363      *
364      *          GlobalFix16( SELECTOROF(vp) );
365      *
366      * But this is unnecessary under Wine, as we never move global
367      * memory segments in linear memory anyway.
368      *
369      * (I'm not so sure what we are *supposed* to do if
370      *  fProtectedMode is TRUE, anyway ...)
371      */
372
373     return K32WOWGetVDMPointer( vp, dwBytes, fProtectedMode );
374 }
375
376 /**********************************************************************
377  *           K32WOWGetVDMPointerUnfix   (KERNEL32.69)
378  */
379 VOID WINAPI K32WOWGetVDMPointerUnfix( DWORD vp )
380 {
381     /*
382      * See above why we don't call:
383      *
384      * GlobalUnfix16( SELECTOROF(vp) );
385      *
386      */
387 }
388
389 /**********************************************************************
390  *           K32WOWGlobalAlloc16        (KERNEL32.59)
391  */
392 WORD WINAPI K32WOWGlobalAlloc16( WORD wFlags, DWORD cb )
393 {
394     return (WORD)GlobalAlloc16( wFlags, cb );
395 }
396
397 /**********************************************************************
398  *           K32WOWGlobalFree16         (KERNEL32.62)
399  */
400 WORD WINAPI K32WOWGlobalFree16( WORD hMem )
401 {
402     return (WORD)GlobalFree16( (HGLOBAL16)hMem );
403 }
404
405 /**********************************************************************
406  *           K32WOWGlobalUnlock16       (KERNEL32.61)
407  */
408 BOOL WINAPI K32WOWGlobalUnlock16( WORD hMem )
409 {
410     return (BOOL)GlobalUnlock16( (HGLOBAL16)hMem );
411 }
412
413 /**********************************************************************
414  *           K32WOWGlobalAllocLock16    (KERNEL32.63)
415  */
416 DWORD WINAPI K32WOWGlobalAllocLock16( WORD wFlags, DWORD cb, WORD *phMem )
417 {
418     WORD hMem = K32WOWGlobalAlloc16( wFlags, cb );
419     if (phMem) *phMem = hMem;
420
421     return K32WOWGlobalLock16( hMem );
422 }
423
424 /**********************************************************************
425  *           K32WOWGlobalLockSize16     (KERNEL32.65)
426  */
427 DWORD WINAPI K32WOWGlobalLockSize16( WORD hMem, PDWORD pcb )
428 {
429     if ( pcb )
430         *pcb = GlobalSize16( (HGLOBAL16)hMem );
431
432     return K32WOWGlobalLock16( hMem );
433 }
434
435 /**********************************************************************
436  *           K32WOWGlobalUnlockFree16   (KERNEL32.64)
437  */
438 WORD WINAPI K32WOWGlobalUnlockFree16( DWORD vpMem )
439 {
440     if ( !K32WOWGlobalUnlock16( HIWORD(vpMem) ) )
441         return FALSE;
442
443     return K32WOWGlobalFree16( HIWORD(vpMem) );
444 }
445
446
447 /**********************************************************************
448  *           K32WOWYield16              (KERNEL32.66)
449  */
450 VOID WINAPI K32WOWYield16( void )
451 {
452     /*
453      * This does the right thing for both Win16 and Win32 tasks.
454      * More or less, at least :-/
455      */
456     Yield16();
457 }
458
459 /**********************************************************************
460  *           K32WOWDirectedYield16       (KERNEL32.67)
461  */
462 VOID WINAPI K32WOWDirectedYield16( WORD htask16 )
463 {
464     /*
465      * Argh.  Our scheduler doesn't like DirectedYield by Win32
466      * tasks at all.  So we do hope that this routine is indeed
467      * only ever called by Win16 tasks that have thunked up ...
468      */
469     DirectedYield16( (HTASK16)htask16 );
470 }
471
472
473 /***********************************************************************
474  *           K32WOWHandle32              (KERNEL32.57)
475  */
476 HANDLE WINAPI K32WOWHandle32( WORD handle, WOW_HANDLE_TYPE type )
477 {
478     switch ( type )
479     {
480     case WOW_TYPE_HWND:
481     case WOW_TYPE_HMENU:
482     case WOW_TYPE_HDWP:
483     case WOW_TYPE_HDROP:
484     case WOW_TYPE_HDC:
485     case WOW_TYPE_HFONT:
486     case WOW_TYPE_HRGN:
487     case WOW_TYPE_HBITMAP:
488     case WOW_TYPE_HBRUSH:
489     case WOW_TYPE_HPALETTE:
490     case WOW_TYPE_HPEN:
491     case WOW_TYPE_HACCEL:
492         return (HANDLE)(ULONG_PTR)handle;
493
494     case WOW_TYPE_HMETAFILE:
495         FIXME( "conversion of metafile handles not supported yet\n" );
496         return (HANDLE)(ULONG_PTR)handle;
497
498     case WOW_TYPE_HTASK:
499         return ((TDB *)GlobalLock16(handle))->teb->ClientId.UniqueThread;
500
501     case WOW_TYPE_FULLHWND:
502         FIXME( "conversion of full window handles not supported yet\n" );
503         return (HANDLE)(ULONG_PTR)handle;
504
505     default:
506         ERR( "handle 0x%04x of unknown type %d\n", handle, type );
507         return (HANDLE)(ULONG_PTR)handle;
508     }
509 }
510
511 /***********************************************************************
512  *           K32WOWHandle16              (KERNEL32.58)
513  */
514 WORD WINAPI K32WOWHandle16( HANDLE handle, WOW_HANDLE_TYPE type )
515 {
516     switch ( type )
517     {
518     case WOW_TYPE_HWND:
519     case WOW_TYPE_HMENU:
520     case WOW_TYPE_HDWP:
521     case WOW_TYPE_HDROP:
522     case WOW_TYPE_HDC:
523     case WOW_TYPE_HFONT:
524     case WOW_TYPE_HRGN:
525     case WOW_TYPE_HBITMAP:
526     case WOW_TYPE_HBRUSH:
527     case WOW_TYPE_HPALETTE:
528     case WOW_TYPE_HPEN:
529     case WOW_TYPE_HACCEL:
530     case WOW_TYPE_FULLHWND:
531         if ( HIWORD(handle ) )
532                 ERR( "handle %p of type %d has non-zero HIWORD\n", handle, type );
533         return LOWORD(handle);
534
535     case WOW_TYPE_HMETAFILE:
536         FIXME( "conversion of metafile handles not supported yet\n" );
537         return LOWORD(handle);
538
539     case WOW_TYPE_HTASK:
540         return TASK_GetTaskFromThread( (DWORD)handle );
541
542     default:
543         ERR( "handle %p of unknown type %d\n", handle, type );
544         return LOWORD(handle);
545     }
546 }
547
548 /**********************************************************************
549  *           K32WOWCallback16Ex         (KERNEL32.55)
550  */
551 BOOL WINAPI K32WOWCallback16Ex( DWORD vpfn16, DWORD dwFlags,
552                                 DWORD cbArgs, LPVOID pArgs, LPDWORD pdwRetCode )
553 {
554 #ifdef __i386__
555     /*
556      * Arguments must be prepared in the correct order by the caller
557      * (both for PASCAL and CDECL calling convention), so we simply
558      * copy them to the 16-bit stack ...
559      */
560     char *stack = (char *)CURRENT_STACK16 - cbArgs;
561
562     memcpy( stack, pArgs, cbArgs );
563
564     if (dwFlags & (WCB16_REGS|WCB16_REGS_LONG))
565     {
566         CONTEXT *context = (CONTEXT *)pdwRetCode;
567
568         if (TRACE_ON(relay))
569         {
570             DWORD count = cbArgs / sizeof(WORD);
571             WORD * wstack = (WORD *)stack;
572
573             DPRINTF("%04x:CallTo16(func=%04x:%04x,ds=%04x",
574                     GetCurrentThreadId(),
575                     context->SegCs, LOWORD(context->Eip), context->SegDs );
576             while (count) DPRINTF( ",%04x", wstack[--count] );
577             DPRINTF(") ss:sp=%04x:%04x",
578                     SELECTOROF(NtCurrentTeb()->WOW32Reserved), OFFSETOF(NtCurrentTeb()->WOW32Reserved) );
579             DPRINTF(" ax=%04x bx=%04x cx=%04x dx=%04x si=%04x di=%04x bp=%04x es=%04x fs=%04x\n",
580                     (WORD)context->Eax, (WORD)context->Ebx, (WORD)context->Ecx,
581                     (WORD)context->Edx, (WORD)context->Esi, (WORD)context->Edi,
582                     (WORD)context->Ebp, (WORD)context->SegEs, (WORD)context->SegFs );
583             SYSLEVEL_CheckNotLevel( 2 );
584         }
585
586         if (context->EFlags & 0x00020000)  /* v86 mode */
587         {
588             EXCEPTION_REGISTRATION_RECORD frame;
589             frame.Handler = vm86_handler;
590             __wine_push_frame( &frame );
591             __wine_enter_vm86( context );
592             __wine_pop_frame( &frame );
593         }
594         else
595         {
596             /* push return address */
597             if (dwFlags & WCB16_REGS_LONG)
598             {
599                 stack -= sizeof(DWORD);
600                 *((DWORD *)stack) = HIWORD(call16_ret_addr);
601                 stack -= sizeof(DWORD);
602                 *((DWORD *)stack) = LOWORD(call16_ret_addr);
603                 cbArgs += 2 * sizeof(DWORD);
604             }
605             else
606             {
607                 stack -= sizeof(SEGPTR);
608                 *((SEGPTR *)stack) = call16_ret_addr;
609                 cbArgs += sizeof(SEGPTR);
610             }
611
612             /*
613              * Start call by checking for pending events.
614              * Note that wine_call_to_16_regs overwrites context stack
615              * pointer so we may modify it here without a problem.
616              */
617             if (NtCurrentTeb()->dpmi_vif)
618             {
619                 context->SegSs = wine_get_ds();
620                 context->Esp   = (DWORD)stack;
621                 insert_event_check( context );
622                 cbArgs += (DWORD)stack - context->Esp;
623             }
624
625             _EnterWin16Lock();
626             wine_call_to_16_regs( context, cbArgs, call16_handler );
627             _LeaveWin16Lock();
628         }
629
630         if (TRACE_ON(relay))
631         {
632             DPRINTF("%04x:RetFrom16() ss:sp=%04x:%04x ",
633                     GetCurrentThreadId(), SELECTOROF(NtCurrentTeb()->WOW32Reserved),
634                     OFFSETOF(NtCurrentTeb()->WOW32Reserved));
635             DPRINTF(" ax=%04x bx=%04x cx=%04x dx=%04x bp=%04x sp=%04x\n",
636                     (WORD)context->Eax, (WORD)context->Ebx, (WORD)context->Ecx,
637                     (WORD)context->Edx, (WORD)context->Ebp, (WORD)context->Esp );
638             SYSLEVEL_CheckNotLevel( 2 );
639         }
640     }
641     else
642     {
643         DWORD ret;
644
645         if (TRACE_ON(relay))
646         {
647             DWORD count = cbArgs / sizeof(WORD);
648             WORD * wstack = (WORD *)stack;
649
650             DPRINTF("%04x:CallTo16(func=%04x:%04x,ds=%04x",
651                     GetCurrentThreadId(), HIWORD(vpfn16), LOWORD(vpfn16),
652                     SELECTOROF(NtCurrentTeb()->WOW32Reserved) );
653             while (count) DPRINTF( ",%04x", wstack[--count] );
654             DPRINTF(") ss:sp=%04x:%04x\n",
655                     SELECTOROF(NtCurrentTeb()->WOW32Reserved), OFFSETOF(NtCurrentTeb()->WOW32Reserved) );
656             SYSLEVEL_CheckNotLevel( 2 );
657         }
658
659         /* push return address */
660         stack -= sizeof(SEGPTR);
661         *((SEGPTR *)stack) = call16_ret_addr;
662         cbArgs += sizeof(SEGPTR);
663
664         /*
665          * Actually, we should take care whether the called routine cleans up
666          * its stack or not.  Fortunately, our wine_call_to_16 core doesn't rely on
667          * the callee to do so; after the routine has returned, the 16-bit
668          * stack pointer is always reset to the position it had before.
669          */
670         _EnterWin16Lock();
671         ret = wine_call_to_16( (FARPROC16)vpfn16, cbArgs, call16_handler );
672         if (pdwRetCode) *pdwRetCode = ret;
673         _LeaveWin16Lock();
674
675         if (TRACE_ON(relay))
676         {
677             DPRINTF("%04x:RetFrom16() ss:sp=%04x:%04x retval=%08x\n",
678                     GetCurrentThreadId(), SELECTOROF(NtCurrentTeb()->WOW32Reserved),
679                     OFFSETOF(NtCurrentTeb()->WOW32Reserved), ret);
680             SYSLEVEL_CheckNotLevel( 2 );
681         }
682     }
683 #else
684     assert(0);  /* cannot call to 16-bit on non-Intel architectures */
685 #endif  /* __i386__ */
686
687     return TRUE;  /* success */
688 }
689
690 /**********************************************************************
691  *           K32WOWCallback16            (KERNEL32.54)
692  */
693 DWORD WINAPI K32WOWCallback16( DWORD vpfn16, DWORD dwParam )
694 {
695     DWORD ret;
696
697     if ( !K32WOWCallback16Ex( vpfn16, WCB16_PASCAL,
698                            sizeof(DWORD), &dwParam, &ret ) )
699         ret = 0L;
700
701     return ret;
702 }
703
704
705 /*
706  *  16-bit WOW routines (in KERNEL)
707  */
708
709 /**********************************************************************
710  *           GetVDMPointer32W      (KERNEL.516)
711  */
712 DWORD WINAPI GetVDMPointer32W16( SEGPTR vp, UINT16 fMode )
713 {
714     GlobalPageLock16(GlobalHandle16(SELECTOROF(vp)));
715     return (DWORD)K32WOWGetVDMPointer( vp, 0, (DWORD)fMode );
716 }
717
718 /***********************************************************************
719  *           LoadLibraryEx32W      (KERNEL.513)
720  */
721 DWORD WINAPI LoadLibraryEx32W16( LPCSTR lpszLibFile, DWORD hFile, DWORD dwFlags )
722 {
723     HMODULE hModule;
724     DWORD mutex_count;
725     OFSTRUCT ofs;
726     const char *p;
727
728     if (!lpszLibFile)
729     {
730         SetLastError(ERROR_INVALID_PARAMETER);
731         return 0;
732     }
733
734     /* if the file cannot be found, call LoadLibraryExA anyway, since it might be
735        a builtin module. This case is handled in MODULE_LoadLibraryExA */
736
737     if ((p = strrchr( lpszLibFile, '.' )) && !strchr( p, '\\' ))  /* got an extension */
738     {
739         if (OpenFile16( lpszLibFile, &ofs, OF_EXIST ) != HFILE_ERROR16)
740             lpszLibFile = ofs.szPathName;
741     }
742     else
743     {
744         char buffer[MAX_PATH+4];
745         strcpy( buffer, lpszLibFile );
746         strcat( buffer, ".dll" );
747         if (OpenFile16( buffer, &ofs, OF_EXIST ) != HFILE_ERROR16)
748             lpszLibFile = ofs.szPathName;
749     }
750
751     ReleaseThunkLock( &mutex_count );
752     hModule = LoadLibraryExA( lpszLibFile, (HANDLE)hFile, dwFlags );
753     RestoreThunkLock( mutex_count );
754
755     return (DWORD)hModule;
756 }
757
758 /***********************************************************************
759  *           GetProcAddress32W     (KERNEL.515)
760  */
761 DWORD WINAPI GetProcAddress32W16( DWORD hModule, LPCSTR lpszProc )
762 {
763     return (DWORD)GetProcAddress( (HMODULE)hModule, lpszProc );
764 }
765
766 /***********************************************************************
767  *           FreeLibrary32W        (KERNEL.514)
768  */
769 DWORD WINAPI FreeLibrary32W16( DWORD hLibModule )
770 {
771     BOOL retv;
772     DWORD mutex_count;
773
774     ReleaseThunkLock( &mutex_count );
775     retv = FreeLibrary( (HMODULE)hLibModule );
776     RestoreThunkLock( mutex_count );
777     return (DWORD)retv;
778 }
779
780
781 /**********************************************************************
782  *           WOW_CallProc32W
783  */
784 static DWORD WOW_CallProc32W16( FARPROC proc32, DWORD nrofargs, DWORD *args )
785 {
786     DWORD ret;
787     DWORD mutex_count;
788
789     ReleaseThunkLock( &mutex_count );
790
791     /*
792      * FIXME:  If ( nrofargs & CPEX_DEST_CDECL ) != 0, we should call a
793      *         32-bit CDECL routine ...
794      */
795
796     if (!proc32) ret = 0;
797     else switch (nrofargs)
798     {
799     case 0: ret = proc32();
800             break;
801     case 1: ret = proc32(args[0]);
802             break;
803     case 2: ret = proc32(args[0],args[1]);
804             break;
805     case 3: ret = proc32(args[0],args[1],args[2]);
806             break;
807     case 4: ret = proc32(args[0],args[1],args[2],args[3]);
808             break;
809     case 5: ret = proc32(args[0],args[1],args[2],args[3],args[4]);
810             break;
811     case 6: ret = proc32(args[0],args[1],args[2],args[3],args[4],args[5]);
812             break;
813     case 7: ret = proc32(args[0],args[1],args[2],args[3],args[4],args[5],args[6]);
814             break;
815     case 8: ret = proc32(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7]);
816             break;
817     case 9: ret = proc32(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]);
818             break;
819     case 10:ret = proc32(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9]);
820             break;
821     case 11:ret = proc32(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10]);
822             break;
823     case 12:ret = proc32(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11]);
824             break;
825     case 13:ret = proc32(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12]);
826             break;
827     case 14:ret = proc32(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13]);
828             break;
829     case 15:ret = proc32(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11],args[12],args[13],args[14]);
830             break;
831     default:
832             /* FIXME: should go up to 32  arguments */
833             ERR("Unsupported number of arguments %d, please report.\n",nrofargs);
834             ret = 0;
835             break;
836     }
837
838     RestoreThunkLock( mutex_count );
839
840     TRACE("returns %08x\n",ret);
841     return ret;
842 }
843
844 /**********************************************************************
845  *           CallProc32W           (KERNEL.517)
846  */
847 DWORD WINAPIV CallProc32W16( DWORD nrofargs, DWORD argconvmask, FARPROC proc32, VA_LIST16 valist )
848 {
849     DWORD args[32];
850     unsigned int i;
851
852     TRACE("(%d,%d,%p args[",nrofargs,argconvmask,proc32);
853
854     for (i=0;i<nrofargs;i++)
855     {
856         if (argconvmask & (1<<i))
857         {
858             SEGPTR ptr = VA_ARG16( valist, SEGPTR );
859             /* pascal convention, have to reverse the arguments order */
860             args[nrofargs - i - 1] = (DWORD)MapSL(ptr);
861             TRACE("%08x(%p),",ptr,MapSL(ptr));
862         }
863         else
864         {
865             DWORD arg = VA_ARG16( valist, DWORD );
866             /* pascal convention, have to reverse the arguments order */
867             args[nrofargs - i - 1] = arg;
868             TRACE("%d,", arg);
869         }
870     }
871     TRACE("])\n");
872
873     /* POP nrofargs DWORD arguments and 3 DWORD parameters */
874     stack16_pop( (3 + nrofargs) * sizeof(DWORD) );
875
876     return WOW_CallProc32W16( proc32, nrofargs, args );
877 }
878
879 /**********************************************************************
880  *           _CallProcEx32W         (KERNEL.518)
881  */
882 DWORD WINAPIV CallProcEx32W16( DWORD nrofargs, DWORD argconvmask, FARPROC proc32, VA_LIST16 valist )
883 {
884     DWORD args[32];
885     unsigned int i;
886
887     TRACE("(%d,%d,%p args[",nrofargs,argconvmask,proc32);
888
889     for (i=0;i<nrofargs;i++)
890     {
891         if (argconvmask & (1<<i))
892         {
893             SEGPTR ptr = VA_ARG16( valist, SEGPTR );
894             args[i] = (DWORD)MapSL(ptr);
895             TRACE("%08x(%p),",ptr,MapSL(ptr));
896         }
897         else
898         {
899             DWORD arg = VA_ARG16( valist, DWORD );
900             args[i] = arg;
901             TRACE("%d,", arg);
902         }
903     }
904     TRACE("])\n");
905     return WOW_CallProc32W16( proc32, nrofargs, args );
906 }
907
908
909 /**********************************************************************
910  *           WOW16Call               (KERNEL.500)
911  *
912  * FIXME!!!
913  *
914  */
915 DWORD WINAPIV WOW16Call(WORD x, WORD y, WORD z, VA_LIST16 args)
916 {
917         int     i;
918         DWORD   calladdr;
919         FIXME("(0x%04x,0x%04x,%d),calling (",x,y,z);
920
921         for (i=0;i<x/2;i++) {
922                 WORD    a = VA_ARG16(args,WORD);
923                 DPRINTF("%04x ",a);
924         }
925         calladdr = VA_ARG16(args,DWORD);
926         stack16_pop( 3*sizeof(WORD) + x + sizeof(DWORD) );
927         DPRINTF(") calling address was 0x%08x\n",calladdr);
928         return 0;
929 }