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