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