winmm: Have xyzGetDevCaps return MMSYSERR_BADDEVICEID, not INVALHANDLE.
[wine] / dlls / krnl386.exe16 / thunk.c
1 /*
2  * KERNEL32 thunks and other undocumented stuff
3  *
4  * Copyright 1996, 1997 Alexandre Julliard
5  * Copyright 1997, 1998 Marcus Meissner
6  * Copyright 1998       Ulrich Weigand
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <string.h>
27 #include <sys/types.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33
34 #include "windef.h"
35 #include "winbase.h"
36 #include "winerror.h"
37 #include "winternl.h"
38 #include "wownt32.h"
39 #include "wine/winbase16.h"
40
41 #include "wine/debug.h"
42 #include "wine/library.h"
43 #include "kernel16_private.h"
44
45 WINE_DEFAULT_DEBUG_CHANNEL(thunk);
46
47 struct ThunkDataCommon
48 {
49     char                   magic[4];         /* 00 */
50     DWORD                  checksum;         /* 04 */
51 };
52
53 struct ThunkDataLS16
54 {
55     struct ThunkDataCommon common;           /* 00 */
56     SEGPTR                 targetTable;      /* 08 */
57     DWORD                  firstTime;        /* 0C */
58 };
59
60 struct ThunkDataLS32
61 {
62     struct ThunkDataCommon common;           /* 00 */
63     DWORD *                targetTable;      /* 08 */
64     char                   lateBinding[4];   /* 0C */
65     DWORD                  flags;            /* 10 */
66     DWORD                  reserved1;        /* 14 */
67     DWORD                  reserved2;        /* 18 */
68     DWORD                  offsetQTThunk;    /* 1C */
69     DWORD                  offsetFTProlog;   /* 20 */
70 };
71
72 struct ThunkDataSL16
73 {
74     struct ThunkDataCommon common;            /* 00 */
75     DWORD                  flags1;            /* 08 */
76     DWORD                  reserved1;         /* 0C */
77     struct ThunkDataSL *   fpData;            /* 10 */
78     SEGPTR                 spData;            /* 14 */
79     DWORD                  reserved2;         /* 18 */
80     char                   lateBinding[4];    /* 1C */
81     DWORD                  flags2;            /* 20 */
82     DWORD                  reserved3;         /* 20 */
83     SEGPTR                 apiDatabase;       /* 28 */
84 };
85
86 struct ThunkDataSL32
87 {
88     struct ThunkDataCommon common;            /* 00 */
89     DWORD                  reserved1;         /* 08 */
90     struct ThunkDataSL *   data;              /* 0C */
91     char                   lateBinding[4];    /* 10 */
92     DWORD                  flags;             /* 14 */
93     DWORD                  reserved2;         /* 18 */
94     DWORD                  reserved3;         /* 1C */
95     DWORD                  offsetTargetTable; /* 20 */
96 };
97
98 struct ThunkDataSL
99 {
100 #if 0
101     This structure differs from the Win95 original,
102     but this should not matter since it is strictly internal to
103     the thunk handling routines in KRNL386 / KERNEL32.
104
105     For reference, here is the Win95 layout:
106
107     struct ThunkDataCommon common;            /* 00 */
108     DWORD                  flags1;            /* 08 */
109     SEGPTR                 apiDatabase;       /* 0C */
110     WORD                   exePtr;            /* 10 */
111     WORD                   segMBA;            /* 12 */
112     DWORD                  lenMBATotal;       /* 14 */
113     DWORD                  lenMBAUsed;        /* 18 */
114     DWORD                  flags2;            /* 1C */
115     char                   pszDll16[256];     /* 20 */
116     char                   pszDll32[256];     /*120 */
117
118     We do it differently since all our thunk handling is done
119     by 32-bit code. Therefore we do not need to provide
120     easy access to this data, especially the process target
121     table database, for 16-bit code.
122 #endif
123
124     struct ThunkDataCommon common;
125     DWORD                  flags1;
126     struct SLApiDB *       apiDB;
127     struct SLTargetDB *    targetDB;
128     DWORD                  flags2;
129     char                   pszDll16[256];
130     char                   pszDll32[256];
131 };
132
133 struct SLTargetDB
134 {
135      struct SLTargetDB *   next;
136      DWORD                 process;
137      DWORD *               targetTable;
138 };
139
140 struct SLApiDB
141 {
142     DWORD                  nrArgBytes;
143     DWORD                  errorReturnValue;
144 };
145
146 SEGPTR CALL32_CBClient_RetAddr = 0;
147 SEGPTR CALL32_CBClientEx_RetAddr = 0;
148
149 extern int call_entry_point( void *func, int nb_args, const DWORD *args );
150 extern void __wine_call_from_16_thunk(void);
151 extern void FT_Prolog(void);
152 extern void FT_PrologPrime(void);
153 extern void QT_Thunk(void);
154 extern void QT_ThunkPrime(void);
155
156 /* Push a DWORD on the 32-bit stack */
157 static inline void stack32_push( CONTEXT86 *context, DWORD val )
158 {
159     context->Esp -= sizeof(DWORD);
160     *(DWORD *)context->Esp = val;
161 }
162
163 /* Pop a DWORD from the 32-bit stack */
164 static inline DWORD stack32_pop( CONTEXT86 *context )
165 {
166     DWORD ret = *(DWORD *)context->Esp;
167     context->Esp += sizeof(DWORD);
168     return ret;
169 }
170
171 /***********************************************************************
172  *                                                                     *
173  *                 Win95 internal thunks                               *
174  *                                                                     *
175  ***********************************************************************/
176
177 /***********************************************************************
178  *           LogApiThk    (KERNEL.423)
179  */
180 void WINAPI LogApiThk( LPSTR func )
181 {
182     TRACE( "%s\n", debugstr_a(func) );
183 }
184
185 /***********************************************************************
186  *           LogApiThkLSF    (KERNEL32.42)
187  *
188  * NOTE: needs to preserve all registers!
189  */
190 void WINAPI __regs_LogApiThkLSF( LPSTR func, CONTEXT86 *context )
191 {
192     TRACE( "%s\n", debugstr_a(func) );
193 }
194 DEFINE_REGS_ENTRYPOINT( LogApiThkLSF, 1 )
195
196 /***********************************************************************
197  *           LogApiThkSL    (KERNEL32.44)
198  *
199  * NOTE: needs to preserve all registers!
200  */
201 void WINAPI __regs_LogApiThkSL( LPSTR func, CONTEXT86 *context )
202 {
203     TRACE( "%s\n", debugstr_a(func) );
204 }
205 DEFINE_REGS_ENTRYPOINT( LogApiThkSL, 1 )
206
207 /***********************************************************************
208  *           LogCBThkSL    (KERNEL32.47)
209  *
210  * NOTE: needs to preserve all registers!
211  */
212 void WINAPI __regs_LogCBThkSL( LPSTR func, CONTEXT86 *context )
213 {
214     TRACE( "%s\n", debugstr_a(func) );
215 }
216 DEFINE_REGS_ENTRYPOINT( LogCBThkSL, 1 )
217
218 /***********************************************************************
219  * Generates a FT_Prolog call.
220  *
221  *  0FB6D1                  movzbl edx,cl
222  *  8B1495xxxxxxxx          mov edx,[4*edx + targetTable]
223  *  68xxxxxxxx              push FT_Prolog
224  *  C3                      lret
225  */
226 static void _write_ftprolog(LPBYTE relayCode ,DWORD *targetTable) {
227         LPBYTE  x;
228
229         x       = relayCode;
230         *x++    = 0x0f;*x++=0xb6;*x++=0xd1; /* movzbl edx,cl */
231         *x++    = 0x8B;*x++=0x14;*x++=0x95;*(DWORD**)x= targetTable;
232         x+=4;   /* mov edx, [4*edx + targetTable] */
233         *x++    = 0x68; *(void **)x = FT_Prolog;
234         x+=4;   /* push FT_Prolog */
235         *x++    = 0xC3;         /* lret */
236         /* fill rest with 0xCC / int 3 */
237 }
238
239 /***********************************************************************
240  *      _write_qtthunk                                  (internal)
241  * Generates a QT_Thunk style call.
242  *
243  *  33C9                    xor ecx, ecx
244  *  8A4DFC                  mov cl , [ebp-04]
245  *  8B148Dxxxxxxxx          mov edx, [4*ecx + targetTable]
246  *  B8yyyyyyyy              mov eax, QT_Thunk
247  *  FFE0                    jmp eax
248  */
249 static void _write_qtthunk(
250         LPBYTE relayCode,       /* [in] start of QT_Thunk stub */
251         DWORD *targetTable      /* [in] start of thunk (for index lookup) */
252 ) {
253         LPBYTE  x;
254
255         x       = relayCode;
256         *x++    = 0x33;*x++=0xC9; /* xor ecx,ecx */
257         *x++    = 0x8A;*x++=0x4D;*x++=0xFC; /* movb cl,[ebp-04] */
258         *x++    = 0x8B;*x++=0x14;*x++=0x8D;*(DWORD**)x= targetTable;
259         x+=4;   /* mov edx, [4*ecx + targetTable */
260         *x++    = 0xB8; *(void **)x = QT_Thunk;
261         x+=4;   /* mov eax , QT_Thunk */
262         *x++    = 0xFF; *x++ = 0xE0;    /* jmp eax */
263         /* should fill the rest of the 32 bytes with 0xCC */
264 }
265
266 /***********************************************************************
267  *           _loadthunk
268  */
269 static LPVOID _loadthunk(LPCSTR module, LPCSTR func, LPCSTR module32,
270                          struct ThunkDataCommon *TD32, DWORD checksum)
271 {
272     struct ThunkDataCommon *TD16;
273     HMODULE16 hmod;
274     int ordinal;
275
276     if ((hmod = LoadLibrary16(module)) <= 32)
277     {
278         ERR("(%s, %s, %s): Unable to load '%s', error %d\n",
279                    module, func, module32, module, hmod);
280         return 0;
281     }
282
283     if (   !(ordinal = NE_GetOrdinal(hmod, func))
284         || !(TD16 = MapSL((SEGPTR)NE_GetEntryPointEx(hmod, ordinal, FALSE))))
285     {
286         ERR("Unable to find thunk data '%s' in %s, required by %s (conflicting/incorrect DLL versions !?).\n",
287                    func, module, module32);
288         return 0;
289     }
290
291     if (TD32 && memcmp(TD16->magic, TD32->magic, 4))
292     {
293         ERR("(%s, %s, %s): Bad magic %c%c%c%c (should be %c%c%c%c)\n",
294                    module, func, module32,
295                    TD16->magic[0], TD16->magic[1], TD16->magic[2], TD16->magic[3],
296                    TD32->magic[0], TD32->magic[1], TD32->magic[2], TD32->magic[3]);
297         return 0;
298     }
299
300     if (TD32 && TD16->checksum != TD32->checksum)
301     {
302         ERR("(%s, %s, %s): Wrong checksum %08x (should be %08x)\n",
303                    module, func, module32, TD16->checksum, TD32->checksum);
304         return 0;
305     }
306
307     if (!TD32 && checksum && checksum != *(LPDWORD)TD16)
308     {
309         ERR("(%s, %s, %s): Wrong checksum %08x (should be %08x)\n",
310                    module, func, module32, *(LPDWORD)TD16, checksum);
311         return 0;
312     }
313
314     return TD16;
315 }
316
317 /***********************************************************************
318  *           GetThunkStuff    (KERNEL32.53)
319  */
320 LPVOID WINAPI GetThunkStuff(LPCSTR module, LPCSTR func)
321 {
322     return _loadthunk(module, func, "<kernel>", NULL, 0L);
323 }
324
325 /***********************************************************************
326  *           GetThunkBuff    (KERNEL32.52)
327  * Returns a pointer to ThkBuf in the 16bit library SYSTHUNK.DLL.
328  */
329 LPVOID WINAPI GetThunkBuff(void)
330 {
331     return GetThunkStuff("SYSTHUNK.DLL", "ThkBuf");
332 }
333
334 /***********************************************************************
335  *              ThunkConnect32          (KERNEL32.@)
336  * Connects a 32bit and a 16bit thunkbuffer.
337  */
338 UINT WINAPI ThunkConnect32(
339         struct ThunkDataCommon *TD,  /* [in/out] thunkbuffer */
340         LPSTR thunkfun16,            /* [in] win16 thunkfunction */
341         LPSTR module16,              /* [in] name of win16 dll */
342         LPSTR module32,              /* [in] name of win32 dll */
343         HMODULE hmod32,            /* [in] hmodule of win32 dll */
344         DWORD dwReason               /* [in] initialisation argument */
345 ) {
346     BOOL directionSL;
347
348     if (!strncmp(TD->magic, "SL01", 4))
349     {
350         directionSL = TRUE;
351
352         TRACE("SL01 thunk %s (%p) <- %s (%s), Reason: %d\n",
353               module32, TD, module16, thunkfun16, dwReason);
354     }
355     else if (!strncmp(TD->magic, "LS01", 4))
356     {
357         directionSL = FALSE;
358
359         TRACE("LS01 thunk %s (%p) -> %s (%s), Reason: %d\n",
360               module32, TD, module16, thunkfun16, dwReason);
361     }
362     else
363     {
364         ERR("Invalid magic %c%c%c%c\n",
365                    TD->magic[0], TD->magic[1], TD->magic[2], TD->magic[3]);
366         return 0;
367     }
368
369     switch (dwReason)
370     {
371         case DLL_PROCESS_ATTACH:
372         {
373             struct ThunkDataCommon *TD16;
374             if (!(TD16 = _loadthunk(module16, thunkfun16, module32, TD, 0L)))
375                 return 0;
376
377             if (directionSL)
378             {
379                 struct ThunkDataSL32 *SL32 = (struct ThunkDataSL32 *)TD;
380                 struct ThunkDataSL16 *SL16 = (struct ThunkDataSL16 *)TD16;
381                 struct SLTargetDB *tdb;
382
383                 if (SL16->fpData == NULL)
384                 {
385                     ERR("ThunkConnect16 was not called!\n");
386                     return 0;
387                 }
388
389                 SL32->data = SL16->fpData;
390
391                 tdb = HeapAlloc(GetProcessHeap(), 0, sizeof(*tdb));
392                 tdb->process = GetCurrentProcessId();
393                 tdb->targetTable = (DWORD *)(thunkfun16 + SL32->offsetTargetTable);
394
395                 tdb->next = SL32->data->targetDB;   /* FIXME: not thread-safe! */
396                 SL32->data->targetDB = tdb;
397
398                 TRACE("Process %08x allocated TargetDB entry for ThunkDataSL %p\n",
399                       GetCurrentProcessId(), SL32->data);
400             }
401             else
402             {
403                 struct ThunkDataLS32 *LS32 = (struct ThunkDataLS32 *)TD;
404                 struct ThunkDataLS16 *LS16 = (struct ThunkDataLS16 *)TD16;
405
406                 LS32->targetTable = MapSL(LS16->targetTable);
407
408                 /* write QT_Thunk and FT_Prolog stubs */
409                 _write_qtthunk ((LPBYTE)TD + LS32->offsetQTThunk,  LS32->targetTable);
410                 _write_ftprolog((LPBYTE)TD + LS32->offsetFTProlog, LS32->targetTable);
411             }
412             break;
413         }
414
415         case DLL_PROCESS_DETACH:
416             /* FIXME: cleanup */
417             break;
418     }
419
420     return 1;
421 }
422
423 /**********************************************************************
424  *              QT_Thunk                        (KERNEL32.@)
425  *
426  * The target address is in EDX.
427  * The 16bit arguments start at ESP.
428  * The number of 16bit argument bytes is EBP-ESP-0x40 (64 Byte thunksetup).
429  * So the stack layout is 16bit argument bytes and then the 64 byte
430  * scratch buffer.
431  * The scratch buffer is used as work space by Windows' QT_Thunk
432  * function.
433  * As the programs unfortunately don't always provide a fixed size
434  * scratch buffer (danger, stack corruption ahead !!), we simply resort
435  * to copying over the whole EBP-ESP range to the 16bit stack
436  * (as there's no way to safely figure out the param count
437  * due to this misbehaviour of some programs).
438  * [ok]
439  *
440  * See DDJ article 9614c for a very good description of QT_Thunk (also
441  * available online !).
442  *
443  * FIXME: DDJ talks of certain register usage rules; I'm not sure
444  * whether we cover this 100%.
445  */
446 void WINAPI __regs_QT_Thunk( CONTEXT86 *context )
447 {
448     CONTEXT86 context16;
449     DWORD argsize;
450
451     context16 = *context;
452
453     context16.SegFs = wine_get_fs();
454     context16.SegGs = wine_get_gs();
455     context16.SegCs = HIWORD(context->Edx);
456     context16.Eip   = LOWORD(context->Edx);
457     /* point EBP to the STACK16FRAME on the stack
458      * for the call_to_16 to set up the register content on calling */
459     context16.Ebp   = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + FIELD_OFFSET(STACK16FRAME,bp);
460
461     /*
462      * used to be (problematic):
463      * argsize = context->Ebp - context->Esp - 0x40;
464      * due to some programs abusing the API, we better assume the full
465      * EBP - ESP range for copying instead: */
466     argsize = context->Ebp - context->Esp;
467
468     /* ok, too much is insane; let's limit param count a bit again */
469     if (argsize > 64)
470         argsize = 64; /* 32 WORDs */
471
472     WOWCallback16Ex( 0, WCB16_REGS, argsize, (void *)context->Esp, (DWORD *)&context16 );
473     context->Eax = context16.Eax;
474     context->Edx = context16.Edx;
475     context->Ecx = context16.Ecx;
476
477     /* make sure to update the Win32 ESP, too, in order to throw away
478      * the number of parameters that the Win16 function
479      * accepted (that it popped from the corresponding Win16 stack) */
480     context->Esp +=   LOWORD(context16.Esp) -
481                         ( OFFSETOF(NtCurrentTeb()->WOW32Reserved) - argsize );
482 }
483 DEFINE_REGS_ENTRYPOINT( QT_Thunk, 0 )
484
485
486 /**********************************************************************
487  *              FT_Prolog                       (KERNEL32.@)
488  *
489  * The set of FT_... thunk routines is used instead of QT_Thunk,
490  * if structures have to be converted from 32-bit to 16-bit
491  * (change of member alignment, conversion of members).
492  *
493  * The thunk function (as created by the thunk compiler) calls
494  * FT_Prolog at the beginning, to set up a stack frame and
495  * allocate a 64 byte buffer on the stack.
496  * The input parameters (target address and some flags) are
497  * saved for later use by FT_Thunk.
498  *
499  * Input:  EDX  16-bit target address (SEGPTR)
500  *         CX   bits  0..7   target number (in target table)
501  *              bits  8..9   some flags (unclear???)
502  *              bits 10..15  number of DWORD arguments
503  *
504  * Output: A new stackframe is created, and a 64 byte buffer
505  *         allocated on the stack. The layout of the stack
506  *         on return is as follows:
507  *
508  *  (ebp+4)  return address to caller of thunk function
509  *  (ebp)    old EBP
510  *  (ebp-4)  saved EBX register of caller
511  *  (ebp-8)  saved ESI register of caller
512  *  (ebp-12) saved EDI register of caller
513  *  (ebp-16) saved ECX register, containing flags
514  *  (ebp-20) bitmap containing parameters that are to be converted
515  *           by FT_Thunk; it is initialized to 0 by FT_Prolog and
516  *           filled in by the thunk code before calling FT_Thunk
517  *  (ebp-24)
518  *    ...    (unclear)
519  *  (ebp-44)
520  *  (ebp-48) saved EAX register of caller (unclear, never restored???)
521  *  (ebp-52) saved EDX register, containing 16-bit thunk target
522  *  (ebp-56)
523  *    ...    (unclear)
524  *  (ebp-64)
525  *
526  *  ESP is EBP-64 after return.
527  *
528  */
529 void WINAPI __regs_FT_Prolog( CONTEXT86 *context )
530 {
531     /* Build stack frame */
532     stack32_push(context, context->Ebp);
533     context->Ebp = context->Esp;
534
535     /* Allocate 64-byte Thunk Buffer */
536     context->Esp -= 64;
537     memset((char *)context->Esp, '\0', 64);
538
539     /* Store Flags (ECX) and Target Address (EDX) */
540     /* Save other registers to be restored later */
541     *(DWORD *)(context->Ebp -  4) = context->Ebx;
542     *(DWORD *)(context->Ebp -  8) = context->Esi;
543     *(DWORD *)(context->Ebp - 12) = context->Edi;
544     *(DWORD *)(context->Ebp - 16) = context->Ecx;
545
546     *(DWORD *)(context->Ebp - 48) = context->Eax;
547     *(DWORD *)(context->Ebp - 52) = context->Edx;
548 }
549 DEFINE_REGS_ENTRYPOINT( FT_Prolog, 0 )
550
551 /**********************************************************************
552  *              FT_Thunk                        (KERNEL32.@)
553  *
554  * This routine performs the actual call to 16-bit code,
555  * similar to QT_Thunk. The differences are:
556  *  - The call target is taken from the buffer created by FT_Prolog
557  *  - Those arguments requested by the thunk code (by setting the
558  *    corresponding bit in the bitmap at EBP-20) are converted
559  *    from 32-bit pointers to segmented pointers (those pointers
560  *    are guaranteed to point to structures copied to the stack
561  *    by the thunk code, so we always use the 16-bit stack selector
562  *    for those addresses).
563  *
564  *    The bit #i of EBP-20 corresponds here to the DWORD starting at
565  *    ESP+4 + 2*i.
566  *
567  * FIXME: It is unclear what happens if there are more than 32 WORDs
568  *        of arguments, so that the single DWORD bitmap is no longer
569  *        sufficient ...
570  */
571 void WINAPI __regs_FT_Thunk( CONTEXT86 *context )
572 {
573     DWORD mapESPrelative = *(DWORD *)(context->Ebp - 20);
574     DWORD callTarget     = *(DWORD *)(context->Ebp - 52);
575
576     CONTEXT86 context16;
577     DWORD i, argsize;
578     DWORD newstack[32];
579     LPBYTE oldstack;
580
581     context16 = *context;
582
583     context16.SegFs = wine_get_fs();
584     context16.SegGs = wine_get_gs();
585     context16.SegCs = HIWORD(callTarget);
586     context16.Eip   = LOWORD(callTarget);
587     context16.Ebp   = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + FIELD_OFFSET(STACK16FRAME,bp);
588
589     argsize  = context->Ebp-context->Esp-0x40;
590     if (argsize > sizeof(newstack)) argsize = sizeof(newstack);
591     oldstack = (LPBYTE)context->Esp;
592
593     memcpy( newstack, oldstack, argsize );
594
595     for (i = 0; i < 32; i++)    /* NOTE: What about > 32 arguments? */
596         if (mapESPrelative & (1 << i))
597         {
598             SEGPTR *arg = (SEGPTR *)newstack[i];
599             *arg = MAKESEGPTR(SELECTOROF(NtCurrentTeb()->WOW32Reserved),
600                               OFFSETOF(NtCurrentTeb()->WOW32Reserved) - argsize
601                               + (*(LPBYTE *)arg - oldstack));
602         }
603
604     WOWCallback16Ex( 0, WCB16_REGS, argsize, newstack, (DWORD *)&context16 );
605     context->Eax = context16.Eax;
606     context->Edx = context16.Edx;
607     context->Ecx = context16.Ecx;
608
609     context->Esp +=   LOWORD(context16.Esp) -
610                         ( OFFSETOF(NtCurrentTeb()->WOW32Reserved) - argsize );
611
612     /* Copy modified buffers back to 32-bit stack */
613     memcpy( oldstack, newstack, argsize );
614 }
615 DEFINE_REGS_ENTRYPOINT( FT_Thunk, 0 )
616
617 /***********************************************************************
618  *              FT_Exit0 (KERNEL32.@)
619  *              FT_Exit4 (KERNEL32.@)
620  *              FT_Exit8 (KERNEL32.@)
621  *              FT_Exit12 (KERNEL32.@)
622  *              FT_Exit16 (KERNEL32.@)
623  *              FT_Exit20 (KERNEL32.@)
624  *              FT_Exit24 (KERNEL32.@)
625  *              FT_Exit28 (KERNEL32.@)
626  *              FT_Exit32 (KERNEL32.@)
627  *              FT_Exit36 (KERNEL32.@)
628  *              FT_Exit40 (KERNEL32.@)
629  *              FT_Exit44 (KERNEL32.@)
630  *              FT_Exit48 (KERNEL32.@)
631  *              FT_Exit52 (KERNEL32.@)
632  *              FT_Exit56 (KERNEL32.@)
633  *
634  * One of the FT_ExitNN functions is called at the end of the thunk code.
635  * It removes the stack frame created by FT_Prolog, moves the function
636  * return from EBX to EAX (yes, FT_Thunk did use EAX for the return
637  * value, but the thunk code has moved it from EAX to EBX in the
638  * meantime ... :-), restores the caller's EBX, ESI, and EDI registers,
639  * and perform a return to the CALLER of the thunk code (while removing
640  * the given number of arguments from the caller's stack).
641  */
642 #define FT_EXIT_RESTORE_REGS \
643     "movl %ebx,%eax\n\t" \
644     "movl -4(%ebp),%ebx\n\t" \
645     "movl -8(%ebp),%esi\n\t" \
646     "movl -12(%ebp),%edi\n\t" \
647     "leave\n\t"
648
649 #define DEFINE_FT_Exit(n) \
650     __ASM_STDCALL_FUNC( FT_Exit ## n, 0, FT_EXIT_RESTORE_REGS "ret $" #n )
651
652 DEFINE_FT_Exit(0)
653 DEFINE_FT_Exit(4)
654 DEFINE_FT_Exit(8)
655 DEFINE_FT_Exit(12)
656 DEFINE_FT_Exit(16)
657 DEFINE_FT_Exit(20)
658 DEFINE_FT_Exit(24)
659 DEFINE_FT_Exit(28)
660 DEFINE_FT_Exit(32)
661 DEFINE_FT_Exit(36)
662 DEFINE_FT_Exit(40)
663 DEFINE_FT_Exit(44)
664 DEFINE_FT_Exit(48)
665 DEFINE_FT_Exit(52)
666 DEFINE_FT_Exit(56)
667
668
669 /***********************************************************************
670  *              ThunkInitLS     (KERNEL32.43)
671  * A thunkbuffer link routine
672  * The thunkbuf looks like:
673  *
674  *      00: DWORD       length          ? don't know exactly
675  *      04: SEGPTR      ptr             ? where does it point to?
676  * The pointer ptr is written into the first DWORD of 'thunk'.
677  * (probably correctly implemented)
678  * [ok probably]
679  * RETURNS
680  *      segmented pointer to thunk?
681  */
682 DWORD WINAPI ThunkInitLS(
683         LPDWORD thunk,  /* [in] win32 thunk */
684         LPCSTR thkbuf,  /* [in] thkbuffer name in win16 dll */
685         DWORD len,      /* [in] thkbuffer length */
686         LPCSTR dll16,   /* [in] name of win16 dll */
687         LPCSTR dll32    /* [in] name of win32 dll (FIXME: not used?) */
688 ) {
689         LPDWORD         addr;
690
691         if (!(addr = _loadthunk( dll16, thkbuf, dll32, NULL, len )))
692                 return 0;
693
694         if (!addr[1])
695                 return 0;
696         *thunk = addr[1];
697
698         return addr[1];
699 }
700
701 /***********************************************************************
702  *              Common32ThkLS   (KERNEL32.45)
703  *
704  * This is another 32->16 thunk, independent of the QT_Thunk/FT_Thunk
705  * style thunks. The basic difference is that the parameter conversion
706  * is done completely on the *16-bit* side here. Thus we do not call
707  * the 16-bit target directly, but call a common entry point instead.
708  * This entry function then calls the target according to the target
709  * number passed in the DI register.
710  *
711  * Input:  EAX    SEGPTR to the common 16-bit entry point
712  *         CX     offset in thunk table (target number * 4)
713  *         DX     error return value if execution fails (unclear???)
714  *         EDX.HI number of DWORD parameters
715  *
716  * (Note that we need to move the thunk table offset from CX to DI !)
717  *
718  * The called 16-bit stub expects its stack to look like this:
719  *     ...
720  *   (esp+40)  32-bit arguments
721  *     ...
722  *   (esp+8)   32 byte of stack space available as buffer
723  *   (esp)     8 byte return address for use with 0x66 lret
724  *
725  * The called 16-bit stub uses a 0x66 lret to return to 32-bit code,
726  * and uses the EAX register to return a DWORD return value.
727  * Thus we need to use a special assembly glue routine
728  * (CallRegisterLongProc instead of CallRegisterShortProc).
729  *
730  * Finally, we return to the caller, popping the arguments off
731  * the stack.  The number of arguments to be popped is returned
732  * in the BL register by the called 16-bit routine.
733  *
734  */
735 void WINAPI __regs_Common32ThkLS( CONTEXT86 *context )
736 {
737     CONTEXT86 context16;
738     DWORD argsize;
739
740     context16 = *context;
741
742     context16.SegFs = wine_get_fs();
743     context16.SegGs = wine_get_gs();
744     context16.Edi   = LOWORD(context->Ecx);
745     context16.SegCs = HIWORD(context->Eax);
746     context16.Eip   = LOWORD(context->Eax);
747     context16.Ebp   = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + FIELD_OFFSET(STACK16FRAME,bp);
748
749     argsize = HIWORD(context->Edx) * 4;
750
751     /* FIXME: hack for stupid USER32 CallbackGlueLS routine */
752     if (context->Edx == context->Eip)
753         argsize = 6 * 4;
754
755     /* Note: the first 32 bytes we copy are just garbage from the 32-bit stack, in order to reserve
756      *       the space. It is safe to do that since the register function prefix has reserved
757      *       a lot more space than that below context->Esp.
758      */
759     WOWCallback16Ex( 0, WCB16_REGS, argsize + 32, (LPBYTE)context->Esp - 32, (DWORD *)&context16 );
760     context->Eax = context16.Eax;
761
762     /* Clean up caller's stack frame */
763     context->Esp += LOBYTE(context16.Ebx);
764 }
765 DEFINE_REGS_ENTRYPOINT( Common32ThkLS, 0 )
766
767 /***********************************************************************
768  *              OT_32ThkLSF     (KERNEL32.40)
769  *
770  * YET Another 32->16 thunk. The difference to Common32ThkLS is that
771  * argument processing is done on both the 32-bit and the 16-bit side:
772  * The 32-bit side prepares arguments, copying them onto the stack.
773  *
774  * When this routine is called, the first word on the stack is the
775  * number of argument bytes prepared by the 32-bit code, and EDX
776  * contains the 16-bit target address.
777  *
778  * The called 16-bit routine is another relaycode, doing further
779  * argument processing and then calling the real 16-bit target
780  * whose address is stored at [bp-04].
781  *
782  * The call proceeds using a normal CallRegisterShortProc.
783  * After return from the 16-bit relaycode, the arguments need
784  * to be copied *back* to the 32-bit stack, since the 32-bit
785  * relaycode processes output parameters.
786  *
787  * Note that we copy twice the number of arguments, since some of the
788  * 16-bit relaycodes in SYSTHUNK.DLL directly access the original
789  * arguments of the caller!
790  *
791  * (Note that this function seems only to be used for
792  *  OLECLI32 -> OLECLI and OLESVR32 -> OLESVR thunking.)
793  */
794 void WINAPI __regs_OT_32ThkLSF( CONTEXT86 *context )
795 {
796     CONTEXT86 context16;
797     DWORD argsize;
798
799     context16 = *context;
800
801     context16.SegFs = wine_get_fs();
802     context16.SegGs = wine_get_gs();
803     context16.SegCs = HIWORD(context->Edx);
804     context16.Eip   = LOWORD(context->Edx);
805     context16.Ebp   = OFFSETOF(NtCurrentTeb()->WOW32Reserved) + FIELD_OFFSET(STACK16FRAME,bp);
806
807     argsize = 2 * *(WORD *)context->Esp + 2;
808
809     WOWCallback16Ex( 0, WCB16_REGS, argsize, (void *)context->Esp, (DWORD *)&context16 );
810     context->Eax = context16.Eax;
811     context->Edx = context16.Edx;
812
813     /* Copy modified buffers back to 32-bit stack */
814     memcpy( (LPBYTE)context->Esp,
815             (LPBYTE)CURRENT_STACK16 - argsize, argsize );
816
817     context->Esp +=   LOWORD(context16.Esp) -
818                         ( OFFSETOF(NtCurrentTeb()->WOW32Reserved) - argsize );
819 }
820 DEFINE_REGS_ENTRYPOINT( OT_32ThkLSF, 0 )
821
822 /***********************************************************************
823  *              ThunkInitLSF            (KERNEL32.41)
824  * A thunk setup routine.
825  * Expects a pointer to a preinitialized thunkbuffer in the first argument
826  * looking like:
827  *|     00..03:         unknown (pointer, check _41, _43, _46)
828  *|     04: EB1E                jmp +0x20
829  *|
830  *|     06..23:         unknown (space for replacement code, check .90)
831  *|
832  *|     24:>E800000000          call offset 29
833  *|     29:>58                  pop eax            ( target of call )
834  *|     2A: 2D25000000          sub eax,0x00000025 ( now points to offset 4 )
835  *|     2F: BAxxxxxxxx          mov edx,xxxxxxxx
836  *|     34: 68yyyyyyyy          push KERNEL32.90
837  *|     39: C3                  ret
838  *|
839  *|     3A: EB1E                jmp +0x20
840  *|     3E ... 59:      unknown (space for replacement code?)
841  *|     5A: E8xxxxxxxx          call <32bitoffset xxxxxxxx>
842  *|     5F: 5A                  pop edx
843  *|     60: 81EA25xxxxxx        sub edx, 0x25xxxxxx
844  *|     66: 52                  push edx
845  *|     67: 68xxxxxxxx          push xxxxxxxx
846  *|     6C: 68yyyyyyyy          push KERNEL32.89
847  *|     71: C3                  ret
848  *|     72: end?
849  * This function checks if the code is there, and replaces the yyyyyyyy entries
850  * by the functionpointers.
851  * The thunkbuf looks like:
852  *
853  *|     00: DWORD       length          ? don't know exactly
854  *|     04: SEGPTR      ptr             ? where does it point to?
855  * The segpointer ptr is written into the first DWORD of 'thunk'.
856  * [ok probably]
857  * RETURNS
858  *      unclear, pointer to win16 thkbuffer?
859  */
860 LPVOID WINAPI ThunkInitLSF(
861         LPBYTE thunk,   /* [in] win32 thunk */
862         LPCSTR thkbuf,  /* [in] thkbuffer name in win16 dll */
863         DWORD len,      /* [in] length of thkbuffer */
864         LPCSTR dll16,   /* [in] name of win16 dll */
865         LPCSTR dll32    /* [in] name of win32 dll */
866 ) {
867         LPDWORD         addr,addr2;
868
869         /* FIXME: add checks for valid code ... */
870         /* write pointers to kernel32.89 and kernel32.90 (+ordinal base of 1) */
871         *(void **)(thunk+0x35) = QT_ThunkPrime;
872         *(void **)(thunk+0x6D) = FT_PrologPrime;
873
874         if (!(addr = _loadthunk( dll16, thkbuf, dll32, NULL, len )))
875                 return 0;
876
877         addr2 = MapSL(addr[1]);
878         if (HIWORD(addr2))
879                 *(DWORD*)thunk = (DWORD)addr2;
880
881         return addr2;
882 }
883
884 /***********************************************************************
885  *              FT_PrologPrime                  (KERNEL32.89)
886  *
887  * This function is called from the relay code installed by
888  * ThunkInitLSF. It replaces the location from where it was
889  * called by a standard FT_Prolog call stub (which is 'primed'
890  * by inserting the correct target table pointer).
891  * Finally, it calls that stub.
892  *
893  * Input:  ECX    target number + flags (passed through to FT_Prolog)
894  *        (ESP)   offset of location where target table pointer
895  *                is stored, relative to the start of the relay code
896  *        (ESP+4) pointer to start of relay code
897  *                (this is where the FT_Prolog call stub gets written to)
898  *
899  * Note: The two DWORD arguments get popped off the stack.
900  *
901  */
902 void WINAPI __regs_FT_PrologPrime( CONTEXT86 *context )
903 {
904     DWORD  targetTableOffset;
905     LPBYTE relayCode;
906
907     /* Compensate for the fact that the Wine register relay code thought
908        we were being called, although we were in fact jumped to */
909     context->Esp -= 4;
910
911     /* Write FT_Prolog call stub */
912     targetTableOffset = stack32_pop(context);
913     relayCode = (LPBYTE)stack32_pop(context);
914     _write_ftprolog( relayCode, *(DWORD **)(relayCode+targetTableOffset) );
915
916     /* Jump to the call stub just created */
917     context->Eip = (DWORD)relayCode;
918 }
919 DEFINE_REGS_ENTRYPOINT( FT_PrologPrime, 0 )
920
921 /***********************************************************************
922  *              QT_ThunkPrime                   (KERNEL32.90)
923  *
924  * This function corresponds to FT_PrologPrime, but installs a
925  * call stub for QT_Thunk instead.
926  *
927  * Input: (EBP-4) target number (passed through to QT_Thunk)
928  *         EDX    target table pointer location offset
929  *         EAX    start of relay code
930  *
931  */
932 void WINAPI __regs_QT_ThunkPrime( CONTEXT86 *context )
933 {
934     DWORD  targetTableOffset;
935     LPBYTE relayCode;
936
937     /* Compensate for the fact that the Wine register relay code thought
938        we were being called, although we were in fact jumped to */
939     context->Esp -= 4;
940
941     /* Write QT_Thunk call stub */
942     targetTableOffset = context->Edx;
943     relayCode = (LPBYTE)context->Eax;
944     _write_qtthunk( relayCode, *(DWORD **)(relayCode+targetTableOffset) );
945
946     /* Jump to the call stub just created */
947     context->Eip = (DWORD)relayCode;
948 }
949 DEFINE_REGS_ENTRYPOINT( QT_ThunkPrime, 0 )
950
951 /***********************************************************************
952  *              ThunkInitSL (KERNEL32.46)
953  * Another thunkbuf link routine.
954  * The start of the thunkbuf looks like this:
955  *      00: DWORD       length
956  *      04: SEGPTR      address for thunkbuffer pointer
957  * [ok probably]
958  *
959  * RETURNS
960  *  Nothing.
961  */
962 VOID WINAPI ThunkInitSL(
963         LPBYTE thunk,           /* [in] start of thunkbuffer */
964         LPCSTR thkbuf,          /* [in] name/ordinal of thunkbuffer in win16 dll */
965         DWORD len,              /* [in] length of thunkbuffer */
966         LPCSTR dll16,           /* [in] name of win16 dll containing the thkbuf */
967         LPCSTR dll32            /* [in] win32 dll. FIXME: strange, unused */
968 ) {
969         LPDWORD         addr;
970
971         if (!(addr = _loadthunk( dll16, thkbuf, dll32, NULL, len )))
972                 return;
973
974         *(DWORD*)MapSL(addr[1]) = (DWORD)thunk;
975 }
976
977 /**********************************************************************
978  *           SSInit             (KERNEL.700)
979  * RETURNS
980  *      TRUE for success.
981  */
982 BOOL WINAPI SSInit16(void)
983 {
984     return TRUE;
985 }
986
987 /**********************************************************************
988  *           SSOnBigStack       (KERNEL32.87)
989  * Check if thunking is initialized (ss selector set up etc.)
990  * We do that differently, so just return TRUE.
991  * [ok]
992  * RETURNS
993  *      TRUE for success.
994  */
995 BOOL WINAPI SSOnBigStack(void)
996 {
997     TRACE("Yes, thunking is initialized\n");
998     return TRUE;
999 }
1000
1001 /**********************************************************************
1002  *           SSConfirmSmallStack     (KERNEL.704)
1003  *
1004  * Abort if not on small stack.
1005  *
1006  * This must be a register routine as it has to preserve *all* registers.
1007  */
1008 void WINAPI SSConfirmSmallStack( CONTEXT86 *context )
1009 {
1010     /* We are always on the small stack while in 16-bit code ... */
1011 }
1012
1013 /**********************************************************************
1014  *           SSCall (KERNEL32.88)
1015  * One of the real thunking functions. This one seems to be for 32<->32
1016  * thunks. It should probably be capable of crossing processboundaries.
1017  *
1018  * And YES, I've seen nr=48 (somewhere in the Win95 32<->16 OLE coupling)
1019  * [ok]
1020  *
1021  * RETURNS
1022  *  Thunked function result.
1023  */
1024 DWORD WINAPIV SSCall(
1025         DWORD nr,       /* [in] number of argument bytes */
1026         DWORD flags,    /* [in] FIXME: flags ? */
1027         FARPROC fun,    /* [in] function to call */
1028         ...             /* [in/out] arguments */
1029 ) {
1030     DWORD i,ret;
1031     DWORD *args = ((DWORD *)&fun) + 1;
1032
1033     if(TRACE_ON(thunk))
1034     {
1035       DPRINTF("(%d,0x%08x,%p,[",nr,flags,fun);
1036       for (i=0;i<nr/4;i++)
1037           DPRINTF("0x%08x,",args[i]);
1038       DPRINTF("])\n");
1039     }
1040     ret = call_entry_point( fun, nr / sizeof(DWORD), args );
1041     TRACE(" returning %d ...\n",ret);
1042     return ret;
1043 }
1044
1045 /**********************************************************************
1046  *           W32S_BackTo32                      (KERNEL32.51)
1047  */
1048 void WINAPI __regs_W32S_BackTo32( CONTEXT86 *context )
1049 {
1050     LPDWORD stack = (LPDWORD)context->Esp;
1051     FARPROC proc = (FARPROC)context->Eip;
1052
1053     context->Eax = call_entry_point( proc, 10, stack + 1 );
1054     context->Eip = stack32_pop(context);
1055 }
1056 DEFINE_REGS_ENTRYPOINT( W32S_BackTo32, 0 )
1057
1058 /**********************************************************************
1059  *                      AllocSLCallback         (KERNEL32.@)
1060  *
1061  * Allocate a 16->32 callback.
1062  *
1063  * NOTES
1064  * Win95 uses some structchains for callbacks. It allocates them
1065  * in blocks of 100 entries, size 32 bytes each, layout:
1066  * blockstart:
1067  *|     0:      PTR     nextblockstart
1068  *|     4:      entry   *first;
1069  *|     8:      WORD    sel ( start points to blockstart)
1070  *|     A:      WORD    unknown
1071  * 100xentry:
1072  *|     00..17:         Code
1073  *|     18:     PDB     *owning_process;
1074  *|     1C:     PTR     blockstart
1075  *
1076  * We ignore this for now. (Just a note for further developers)
1077  * FIXME: use this method, so we don't waste selectors...
1078  *
1079  * Following code is then generated by AllocSLCallback. The code is 16 bit, so
1080  * the 0x66 prefix switches from word->long registers.
1081  *
1082  *|     665A            pop     edx
1083  *|     6668x arg2 x    pushl   <arg2>
1084  *|     6652            push    edx
1085  *|     EAx arg1 x      jmpf    <arg1>
1086  *
1087  * returns the startaddress of this thunk.
1088  *
1089  * Note, that they look very similar to the ones allocates by THUNK_Alloc.
1090  * RETURNS
1091  *      A segmented pointer to the start of the thunk
1092  */
1093 DWORD WINAPI
1094 AllocSLCallback(
1095         DWORD finalizer,        /* [in] Finalizer function */
1096         DWORD callback          /* [in] Callback function */
1097 ) {
1098         LPBYTE  x,thunk = HeapAlloc( GetProcessHeap(), 0, 32 );
1099         WORD    sel;
1100
1101         x=thunk;
1102         *x++=0x66;*x++=0x5a;                            /* popl edx */
1103         *x++=0x66;*x++=0x68;*(DWORD*)x=finalizer;x+=4;  /* pushl finalizer */
1104         *x++=0x66;*x++=0x52;                            /* pushl edx */
1105         *x++=0xea;*(DWORD*)x=callback;x+=4;             /* jmpf callback */
1106
1107         *(DWORD*)(thunk+18) = GetCurrentProcessId();
1108
1109         sel = SELECTOR_AllocBlock( thunk, 32, WINE_LDT_FLAGS_CODE );
1110         return (sel<<16)|0;
1111 }
1112
1113 /**********************************************************************
1114  *              FreeSLCallback          (KERNEL32.@)
1115  * Frees the specified 16->32 callback
1116  *
1117  * RETURNS
1118  *  Nothing.
1119  */
1120 void WINAPI
1121 FreeSLCallback(
1122         DWORD x /* [in] 16 bit callback (segmented pointer?) */
1123 ) {
1124         FIXME("(0x%08x): stub\n",x);
1125 }
1126
1127 /**********************************************************************
1128  *              AllocMappedBuffer       (KERNEL32.38)
1129  *
1130  * This is an undocumented KERNEL32 function that
1131  * SMapLS's a GlobalAlloc'ed buffer.
1132  *
1133  * RETURNS
1134  *       EDI register: pointer to buffer
1135  *
1136  * NOTES
1137  *       The buffer is preceded by 8 bytes:
1138  *        ...
1139  *       edi+0   buffer
1140  *       edi-4   SEGPTR to buffer
1141  *       edi-8   some magic Win95 needs for SUnMapLS
1142  *               (we use it for the memory handle)
1143  *
1144  *       The SEGPTR is used by the caller!
1145  */
1146 void WINAPI __regs_AllocMappedBuffer(
1147               CONTEXT86 *context /* [in] EDI register: size of buffer to allocate */
1148 ) {
1149     HGLOBAL handle = GlobalAlloc(0, context->Edi + 8);
1150     DWORD *buffer = GlobalLock(handle);
1151     DWORD ptr = 0;
1152
1153     if (buffer)
1154         if (!(ptr = MapLS(buffer + 2)))
1155         {
1156             GlobalUnlock(handle);
1157             GlobalFree(handle);
1158         }
1159
1160     if (!ptr)
1161         context->Eax = context->Edi = 0;
1162     else
1163     {
1164         buffer[0] = (DWORD)handle;
1165         buffer[1] = ptr;
1166
1167         context->Eax = ptr;
1168         context->Edi = (DWORD)(buffer + 2);
1169     }
1170 }
1171 DEFINE_REGS_ENTRYPOINT( AllocMappedBuffer, 0 )
1172
1173 /**********************************************************************
1174  *              FreeMappedBuffer        (KERNEL32.39)
1175  *
1176  * Free a buffer allocated by AllocMappedBuffer
1177  *
1178  * RETURNS
1179  *  Nothing.
1180  */
1181 void WINAPI __regs_FreeMappedBuffer(
1182               CONTEXT86 *context /* [in] EDI register: pointer to buffer */
1183 ) {
1184     if (context->Edi)
1185     {
1186         DWORD *buffer = (DWORD *)context->Edi - 2;
1187
1188         UnMapLS(buffer[1]);
1189
1190         GlobalUnlock((HGLOBAL)buffer[0]);
1191         GlobalFree((HGLOBAL)buffer[0]);
1192     }
1193 }
1194 DEFINE_REGS_ENTRYPOINT( FreeMappedBuffer, 0 )
1195
1196 /**********************************************************************
1197  *              GetTEBSelectorFS        (KERNEL.475)
1198  *      Set the 16-bit %fs to the 32-bit %fs (current TEB selector)
1199  */
1200 void WINAPI GetTEBSelectorFS16(void)
1201 {
1202     CURRENT_STACK16->fs = wine_get_fs();
1203 }
1204
1205 /**********************************************************************
1206  *              IsPeFormat              (KERNEL.431)
1207  *
1208  * Determine if a file is a PE format executable.
1209  *
1210  * RETURNS
1211  *  TRUE, if it is.
1212  *  FALSE if the file could not be opened or is not a PE file.
1213  *
1214  * NOTES
1215  *  If fn is given as NULL then the function expects hf16 to be valid.
1216  */
1217 BOOL16 WINAPI IsPeFormat16(
1218         LPSTR   fn,     /* [in] Filename to the executable */
1219         HFILE16 hf16)   /* [in] An open file handle */
1220 {
1221     BOOL ret = FALSE;
1222     IMAGE_DOS_HEADER mzh;
1223     OFSTRUCT ofs;
1224     DWORD xmagic;
1225
1226     if (fn) hf16 = OpenFile16(fn,&ofs,OF_READ);
1227     if (hf16 == HFILE_ERROR16) return FALSE;
1228     _llseek16(hf16,0,SEEK_SET);
1229     if (sizeof(mzh)!=_lread16(hf16,&mzh,sizeof(mzh))) goto done;
1230     if (mzh.e_magic!=IMAGE_DOS_SIGNATURE) goto done;
1231     _llseek16(hf16,mzh.e_lfanew,SEEK_SET);
1232     if (sizeof(DWORD)!=_lread16(hf16,&xmagic,sizeof(DWORD))) goto done;
1233     ret = (xmagic == IMAGE_NT_SIGNATURE);
1234  done:
1235     _lclose16(hf16);
1236     return ret;
1237 }
1238
1239
1240 /***********************************************************************
1241  *           K32Thk1632Prolog                   (KERNEL32.@)
1242  */
1243 void WINAPI __regs_K32Thk1632Prolog( CONTEXT86 *context )
1244 {
1245    LPBYTE code = (LPBYTE)context->Eip - 5;
1246
1247    /* Arrrgh! SYSTHUNK.DLL just has to re-implement another method
1248       of 16->32 thunks instead of using one of the standard methods!
1249       This means that SYSTHUNK.DLL itself switches to a 32-bit stack,
1250       and does a far call to the 32-bit code segment of OLECLI32/OLESVR32.
1251       Unfortunately, our CallTo/CallFrom mechanism is therefore completely
1252       bypassed, which means it will crash the next time the 32-bit OLE
1253       code thunks down again to 16-bit (this *will* happen!).
1254
1255       The following hack tries to recognize this situation.
1256       This is possible since the called stubs in OLECLI32/OLESVR32 all
1257       look exactly the same:
1258         00   E8xxxxxxxx    call K32Thk1632Prolog
1259         05   FF55FC        call [ebp-04]
1260         08   E8xxxxxxxx    call K32Thk1632Epilog
1261         0D   66CB          retf
1262
1263       If we recognize this situation, we try to simulate the actions
1264       of our CallTo/CallFrom mechanism by copying the 16-bit stack
1265       to our 32-bit stack, creating a proper STACK16FRAME and
1266       updating cur_stack. */
1267
1268    if (   code[5] == 0xFF && code[6] == 0x55 && code[7] == 0xFC
1269        && code[13] == 0x66 && code[14] == 0xCB)
1270    {
1271       DWORD argSize = context->Ebp - context->Esp;
1272       char *stack16 = (char *)context->Esp - 4;
1273       STACK16FRAME *frame16 = (STACK16FRAME *)stack16 - 1;
1274       STACK32FRAME *frame32 = NtCurrentTeb()->WOW32Reserved;
1275       char *stack32 = (char *)frame32 - argSize;
1276       WORD  stackSel  = SELECTOROF(frame32->frame16);
1277       DWORD stackBase = GetSelectorBase(stackSel);
1278
1279       TRACE("before SYSTHUNK hack: EBP: %08x ESP: %08x cur_stack: %p\n",
1280             context->Ebp, context->Esp, NtCurrentTeb()->WOW32Reserved);
1281
1282       memset(frame16, '\0', sizeof(STACK16FRAME));
1283       frame16->frame32 = frame32;
1284       frame16->ebp = context->Ebp;
1285
1286       memcpy(stack32, stack16, argSize);
1287       NtCurrentTeb()->WOW32Reserved = (void *)MAKESEGPTR(stackSel, (DWORD)frame16 - stackBase);
1288
1289       context->Esp = (DWORD)stack32 + 4;
1290       context->Ebp = context->Esp + argSize;
1291
1292       TRACE("after  SYSTHUNK hack: EBP: %08x ESP: %08x cur_stack: %p\n",
1293             context->Ebp, context->Esp, NtCurrentTeb()->WOW32Reserved);
1294    }
1295
1296     /* entry_point is never used again once the entry point has
1297        been called.  Thus we re-use it to hold the Win16Lock count */
1298    ReleaseThunkLock(&CURRENT_STACK16->entry_point);
1299 }
1300 DEFINE_REGS_ENTRYPOINT( K32Thk1632Prolog, 0 )
1301
1302 /***********************************************************************
1303  *           K32Thk1632Epilog                   (KERNEL32.@)
1304  */
1305 void WINAPI __regs_K32Thk1632Epilog( CONTEXT86 *context )
1306 {
1307    LPBYTE code = (LPBYTE)context->Eip - 13;
1308
1309    RestoreThunkLock(CURRENT_STACK16->entry_point);
1310
1311    /* We undo the SYSTHUNK hack if necessary. See K32Thk1632Prolog. */
1312
1313    if (   code[5] == 0xFF && code[6] == 0x55 && code[7] == 0xFC
1314        && code[13] == 0x66 && code[14] == 0xCB)
1315    {
1316       STACK16FRAME *frame16 = MapSL((SEGPTR)NtCurrentTeb()->WOW32Reserved);
1317       char *stack16 = (char *)(frame16 + 1);
1318       DWORD argSize = frame16->ebp - (DWORD)stack16;
1319       char *stack32 = (char *)frame16->frame32 - argSize;
1320
1321       DWORD nArgsPopped = context->Esp - (DWORD)stack32;
1322
1323       TRACE("before SYSTHUNK hack: EBP: %08x ESP: %08x cur_stack: %p\n",
1324             context->Ebp, context->Esp, NtCurrentTeb()->WOW32Reserved);
1325
1326       NtCurrentTeb()->WOW32Reserved = frame16->frame32;
1327
1328       context->Esp = (DWORD)stack16 + nArgsPopped;
1329       context->Ebp = frame16->ebp;
1330
1331       TRACE("after  SYSTHUNK hack: EBP: %08x ESP: %08x cur_stack: %p\n",
1332             context->Ebp, context->Esp, NtCurrentTeb()->WOW32Reserved);
1333    }
1334 }
1335 DEFINE_REGS_ENTRYPOINT( K32Thk1632Epilog, 0 )
1336
1337 /*********************************************************************
1338  *                   PK16FNF [KERNEL32.91]
1339  *
1340  *  This routine fills in the supplied 13-byte (8.3 plus terminator)
1341  *  string buffer with the 8.3 filename of a recently loaded 16-bit
1342  *  module.  It is unknown exactly what modules trigger this
1343  *  mechanism or what purpose this serves.  Win98 Explorer (and
1344  *  probably also Win95 with IE 4 shell integration) calls this
1345  *  several times during initialization.
1346  *
1347  *  FIXME: find out what this really does and make it work.
1348  */
1349 void WINAPI PK16FNF(LPSTR strPtr)
1350 {
1351        FIXME("(%p): stub\n", strPtr);
1352
1353        /* fill in a fake filename that'll be easy to recognize */
1354        strcpy(strPtr, "WINESTUB.FIX");
1355 }
1356
1357 /***********************************************************************
1358  * 16->32 Flat Thunk routines:
1359  */
1360
1361 /***********************************************************************
1362  *              ThunkConnect16          (KERNEL.651)
1363  * Connects a 32bit and a 16bit thunkbuffer.
1364  */
1365 UINT WINAPI ThunkConnect16(
1366         LPSTR module16,              /* [in] name of win16 dll */
1367         LPSTR module32,              /* [in] name of win32 dll */
1368         HINSTANCE16 hInst16,         /* [in] hInst of win16 dll */
1369         DWORD dwReason,              /* [in] initialisation argument */
1370         struct ThunkDataCommon *TD,  /* [in/out] thunkbuffer */
1371         LPSTR thunkfun32,            /* [in] win32 thunkfunction */
1372         WORD cs                      /* [in] CS of win16 dll */
1373 ) {
1374     BOOL directionSL;
1375
1376     if (!strncmp(TD->magic, "SL01", 4))
1377     {
1378         directionSL = TRUE;
1379
1380         TRACE("SL01 thunk %s (%p) -> %s (%s), Reason: %d\n",
1381               module16, TD, module32, thunkfun32, dwReason);
1382     }
1383     else if (!strncmp(TD->magic, "LS01", 4))
1384     {
1385         directionSL = FALSE;
1386
1387         TRACE("LS01 thunk %s (%p) <- %s (%s), Reason: %d\n",
1388               module16, TD, module32, thunkfun32, dwReason);
1389     }
1390     else
1391     {
1392         ERR("Invalid magic %c%c%c%c\n",
1393             TD->magic[0], TD->magic[1], TD->magic[2], TD->magic[3]);
1394         return 0;
1395     }
1396
1397     switch (dwReason)
1398     {
1399         case DLL_PROCESS_ATTACH:
1400             if (directionSL)
1401             {
1402                 struct ThunkDataSL16 *SL16 = (struct ThunkDataSL16 *)TD;
1403                 struct ThunkDataSL   *SL   = SL16->fpData;
1404
1405                 if (SL == NULL)
1406                 {
1407                     SL = HeapAlloc(GetProcessHeap(), 0, sizeof(*SL));
1408
1409                     SL->common   = SL16->common;
1410                     SL->flags1   = SL16->flags1;
1411                     SL->flags2   = SL16->flags2;
1412
1413                     SL->apiDB    = MapSL(SL16->apiDatabase);
1414                     SL->targetDB = NULL;
1415
1416                     lstrcpynA(SL->pszDll16, module16, 255);
1417                     lstrcpynA(SL->pszDll32, module32, 255);
1418
1419                     /* We should create a SEGPTR to the ThunkDataSL,
1420                        but since the contents are not in the original format,
1421                        any access to this by 16-bit code would crash anyway. */
1422                     SL16->spData = 0;
1423                     SL16->fpData = SL;
1424                 }
1425
1426
1427                 if (SL->flags2 & 0x80000000)
1428                 {
1429                     TRACE("Preloading 32-bit library\n");
1430                     LoadLibraryA(module32);
1431                 }
1432             }
1433             else
1434             {
1435                 /* nothing to do */
1436             }
1437             break;
1438
1439         case DLL_PROCESS_DETACH:
1440             /* FIXME: cleanup */
1441             break;
1442     }
1443
1444     return 1;
1445 }
1446
1447
1448 /***********************************************************************
1449  *           C16ThkSL                           (KERNEL.630)
1450  */
1451
1452 void WINAPI C16ThkSL(CONTEXT86 *context)
1453 {
1454     LPBYTE stub = MapSL(context->Eax), x = stub;
1455     WORD cs = wine_get_cs();
1456     WORD ds = wine_get_ds();
1457
1458     /* We produce the following code:
1459      *
1460      *   mov ax, __FLATDS
1461      *   mov es, ax
1462      *   movzx ecx, cx
1463      *   mov edx, es:[ecx + $EDX]
1464      *   push bp
1465      *   push edx
1466      *   push dx
1467      *   push edx
1468      *   call __FLATCS:__wine_call_from_16_thunk
1469      */
1470
1471     *x++ = 0xB8; *(WORD *)x = ds; x += sizeof(WORD);
1472     *x++ = 0x8E; *x++ = 0xC0;
1473     *x++ = 0x66; *x++ = 0x0F; *x++ = 0xB7; *x++ = 0xC9;
1474     *x++ = 0x67; *x++ = 0x66; *x++ = 0x26; *x++ = 0x8B;
1475                  *x++ = 0x91; *(DWORD *)x = context->Edx; x += sizeof(DWORD);
1476
1477     *x++ = 0x55;
1478     *x++ = 0x66; *x++ = 0x52;
1479     *x++ = 0x52;
1480     *x++ = 0x66; *x++ = 0x52;
1481     *x++ = 0x66; *x++ = 0x9A;
1482     *(void **)x = __wine_call_from_16_thunk; x += sizeof(void *);
1483     *(WORD *)x = cs; x += sizeof(WORD);
1484
1485     /* Jump to the stub code just created */
1486     context->Eip = LOWORD(context->Eax);
1487     context->SegCs  = HIWORD(context->Eax);
1488
1489     /* Since C16ThkSL got called by a jmp, we need to leave the
1490        original return address on the stack */
1491     context->Esp -= 4;
1492 }
1493
1494 /***********************************************************************
1495  *           C16ThkSL01                         (KERNEL.631)
1496  */
1497
1498 void WINAPI C16ThkSL01(CONTEXT86 *context)
1499 {
1500     LPBYTE stub = MapSL(context->Eax), x = stub;
1501
1502     if (stub)
1503     {
1504         struct ThunkDataSL16 *SL16 = MapSL(context->Edx);
1505         struct ThunkDataSL *td = SL16->fpData;
1506
1507         DWORD procAddress = (DWORD)GetProcAddress16(GetModuleHandle16("KERNEL"), (LPCSTR)631);
1508         WORD cs = wine_get_cs();
1509
1510         if (!td)
1511         {
1512             ERR("ThunkConnect16 was not called!\n");
1513             return;
1514         }
1515
1516         TRACE("Creating stub for ThunkDataSL %p\n", td);
1517
1518
1519         /* We produce the following code:
1520          *
1521          *   xor eax, eax
1522          *   mov edx, $td
1523          *   call C16ThkSL01
1524          *   push bp
1525          *   push edx
1526          *   push dx
1527          *   push edx
1528          *   call __FLATCS:__wine_call_from_16_thunk
1529          */
1530
1531         *x++ = 0x66; *x++ = 0x33; *x++ = 0xC0;
1532         *x++ = 0x66; *x++ = 0xBA; *(void **)x = td; x += sizeof(void *);
1533         *x++ = 0x9A; *(DWORD *)x = procAddress; x += sizeof(DWORD);
1534
1535         *x++ = 0x55;
1536         *x++ = 0x66; *x++ = 0x52;
1537         *x++ = 0x52;
1538         *x++ = 0x66; *x++ = 0x52;
1539         *x++ = 0x66; *x++ = 0x9A;
1540         *(void **)x = __wine_call_from_16_thunk; x += sizeof(void *);
1541         *(WORD *)x = cs; x += sizeof(WORD);
1542
1543         /* Jump to the stub code just created */
1544         context->Eip = LOWORD(context->Eax);
1545         context->SegCs  = HIWORD(context->Eax);
1546
1547         /* Since C16ThkSL01 got called by a jmp, we need to leave the
1548            original return address on the stack */
1549         context->Esp -= 4;
1550     }
1551     else
1552     {
1553         struct ThunkDataSL *td = (struct ThunkDataSL *)context->Edx;
1554         DWORD targetNr = LOWORD(context->Ecx) / 4;
1555         struct SLTargetDB *tdb;
1556
1557         TRACE("Process %08x calling target %d of ThunkDataSL %p\n",
1558               GetCurrentProcessId(), targetNr, td);
1559
1560         for (tdb = td->targetDB; tdb; tdb = tdb->next)
1561             if (tdb->process == GetCurrentProcessId())
1562                 break;
1563
1564         if (!tdb)
1565         {
1566             TRACE("Loading 32-bit library %s\n", td->pszDll32);
1567             LoadLibraryA(td->pszDll32);
1568
1569             for (tdb = td->targetDB; tdb; tdb = tdb->next)
1570                 if (tdb->process == GetCurrentProcessId())
1571                     break;
1572         }
1573
1574         if (tdb)
1575         {
1576             context->Edx = tdb->targetTable[targetNr];
1577
1578             TRACE("Call target is %08x\n", context->Edx);
1579         }
1580         else
1581         {
1582             WORD *stack = MapSL( MAKESEGPTR(context->SegSs, LOWORD(context->Esp)) );
1583             context->Edx = (context->Edx & ~0xffff) | HIWORD(td->apiDB[targetNr].errorReturnValue);
1584             context->Eax = (context->Eax & ~0xffff) | LOWORD(td->apiDB[targetNr].errorReturnValue);
1585             context->Eip = stack[2];
1586             context->SegCs  = stack[3];
1587             context->Esp += td->apiDB[targetNr].nrArgBytes + 4;
1588
1589             ERR("Process %08x did not ThunkConnect32 %s to %s\n",
1590                 GetCurrentProcessId(), td->pszDll32, td->pszDll16);
1591         }
1592     }
1593 }
1594
1595
1596 /***********************************************************************
1597  * 16<->32 Thunklet/Callback API:
1598  */
1599
1600 #include "pshpack1.h"
1601 typedef struct _THUNKLET
1602 {
1603     BYTE        prefix_target;
1604     BYTE        pushl_target;
1605     DWORD       target;
1606
1607     BYTE        prefix_relay;
1608     BYTE        pushl_relay;
1609     DWORD       relay;
1610
1611     BYTE        jmp_glue;
1612     DWORD       glue;
1613
1614     BYTE        type;
1615     HINSTANCE16 owner;
1616     struct _THUNKLET *next;
1617 } THUNKLET;
1618 #include "poppack.h"
1619
1620 #define THUNKLET_TYPE_LS  1
1621 #define THUNKLET_TYPE_SL  2
1622
1623 static HANDLE  ThunkletHeap = 0;
1624 static WORD ThunkletCodeSel;
1625 static THUNKLET *ThunkletAnchor = NULL;
1626
1627 static FARPROC ThunkletSysthunkGlueLS = 0;
1628 static SEGPTR    ThunkletSysthunkGlueSL = 0;
1629
1630 static FARPROC ThunkletCallbackGlueLS = 0;
1631 static SEGPTR    ThunkletCallbackGlueSL = 0;
1632
1633
1634 /* map a thunk allocated on ThunkletHeap to a 16-bit pointer */
1635 static inline SEGPTR get_segptr( void *thunk )
1636 {
1637     if (!thunk) return 0;
1638     return MAKESEGPTR( ThunkletCodeSel, (char *)thunk - (char *)ThunkletHeap );
1639 }
1640
1641 /***********************************************************************
1642  *           THUNK_Init
1643  */
1644 static BOOL THUNK_Init(void)
1645 {
1646     LPBYTE thunk;
1647
1648     ThunkletHeap = HeapCreate( HEAP_CREATE_ENABLE_EXECUTE, 0x10000, 0x10000 );
1649     if (!ThunkletHeap) return FALSE;
1650
1651     ThunkletCodeSel = SELECTOR_AllocBlock( ThunkletHeap, 0x10000, WINE_LDT_FLAGS_CODE );
1652
1653     thunk = HeapAlloc( ThunkletHeap, 0, 5 );
1654     if (!thunk) return FALSE;
1655
1656     ThunkletSysthunkGlueLS = (FARPROC)thunk;
1657     *thunk++ = 0x58;                             /* popl eax */
1658     *thunk++ = 0xC3;                             /* ret      */
1659
1660     ThunkletSysthunkGlueSL = get_segptr( thunk );
1661     *thunk++ = 0x66; *thunk++ = 0x58;            /* popl eax */
1662     *thunk++ = 0xCB;                             /* lret     */
1663
1664     return TRUE;
1665 }
1666
1667 /***********************************************************************
1668  *     SetThunkletCallbackGlue             (KERNEL.560)
1669  */
1670 void WINAPI SetThunkletCallbackGlue16( FARPROC glueLS, SEGPTR glueSL )
1671 {
1672     ThunkletCallbackGlueLS = glueLS;
1673     ThunkletCallbackGlueSL = glueSL;
1674 }
1675
1676
1677 /***********************************************************************
1678  *     THUNK_FindThunklet
1679  */
1680 static THUNKLET *THUNK_FindThunklet( DWORD target, DWORD relay,
1681                                      DWORD glue, BYTE type )
1682 {
1683     THUNKLET *thunk;
1684
1685     for (thunk = ThunkletAnchor; thunk; thunk = thunk->next)
1686         if (    thunk->type   == type
1687              && thunk->target == target
1688              && thunk->relay  == relay
1689              && ( type == THUNKLET_TYPE_LS ?
1690                     ( thunk->glue == glue - (DWORD)&thunk->type )
1691                   : ( thunk->glue == glue ) ) )
1692             return thunk;
1693
1694      return NULL;
1695 }
1696
1697 /***********************************************************************
1698  *     THUNK_AllocLSThunklet
1699  */
1700 static FARPROC THUNK_AllocLSThunklet( SEGPTR target, DWORD relay,
1701                                       FARPROC glue, HTASK16 owner )
1702 {
1703     THUNKLET *thunk = THUNK_FindThunklet( (DWORD)target, relay, (DWORD)glue,
1704                                           THUNKLET_TYPE_LS );
1705     if (!thunk)
1706     {
1707         TDB *pTask = GlobalLock16( owner );
1708
1709         if (!ThunkletHeap) THUNK_Init();
1710         if ( !(thunk = HeapAlloc( ThunkletHeap, 0, sizeof(THUNKLET) )) )
1711             return 0;
1712
1713         thunk->prefix_target = thunk->prefix_relay = 0x90;
1714         thunk->pushl_target  = thunk->pushl_relay  = 0x68;
1715         thunk->jmp_glue = 0xE9;
1716
1717         thunk->target  = (DWORD)target;
1718         thunk->relay   = relay;
1719         thunk->glue    = (DWORD)glue - (DWORD)&thunk->type;
1720
1721         thunk->type    = THUNKLET_TYPE_LS;
1722         thunk->owner   = pTask? pTask->hInstance : 0;
1723
1724         thunk->next    = ThunkletAnchor;
1725         ThunkletAnchor = thunk;
1726     }
1727
1728     return (FARPROC)thunk;
1729 }
1730
1731 /***********************************************************************
1732  *     THUNK_AllocSLThunklet
1733  */
1734 static SEGPTR THUNK_AllocSLThunklet( FARPROC target, DWORD relay,
1735                                      SEGPTR glue, HTASK16 owner )
1736 {
1737     THUNKLET *thunk = THUNK_FindThunklet( (DWORD)target, relay, (DWORD)glue,
1738                                           THUNKLET_TYPE_SL );
1739     if (!thunk)
1740     {
1741         TDB *pTask = GlobalLock16( owner );
1742
1743         if (!ThunkletHeap) THUNK_Init();
1744         if ( !(thunk = HeapAlloc( ThunkletHeap, 0, sizeof(THUNKLET) )) )
1745             return 0;
1746
1747         thunk->prefix_target = thunk->prefix_relay = 0x66;
1748         thunk->pushl_target  = thunk->pushl_relay  = 0x68;
1749         thunk->jmp_glue = 0xEA;
1750
1751         thunk->target  = (DWORD)target;
1752         thunk->relay   = relay;
1753         thunk->glue    = (DWORD)glue;
1754
1755         thunk->type    = THUNKLET_TYPE_SL;
1756         thunk->owner   = pTask? pTask->hInstance : 0;
1757
1758         thunk->next    = ThunkletAnchor;
1759         ThunkletAnchor = thunk;
1760     }
1761
1762     return get_segptr( thunk );
1763 }
1764
1765 /**********************************************************************
1766  *     IsLSThunklet
1767  */
1768 static BOOL16 IsLSThunklet( THUNKLET *thunk )
1769 {
1770     return    thunk->prefix_target == 0x90 && thunk->pushl_target == 0x68
1771            && thunk->prefix_relay  == 0x90 && thunk->pushl_relay  == 0x68
1772            && thunk->jmp_glue == 0xE9 && thunk->type == THUNKLET_TYPE_LS;
1773 }
1774
1775 /**********************************************************************
1776  *     IsSLThunklet                        (KERNEL.612)
1777  */
1778 BOOL16 WINAPI IsSLThunklet16( THUNKLET *thunk )
1779 {
1780     return    thunk->prefix_target == 0x66 && thunk->pushl_target == 0x68
1781            && thunk->prefix_relay  == 0x66 && thunk->pushl_relay  == 0x68
1782            && thunk->jmp_glue == 0xEA && thunk->type == THUNKLET_TYPE_SL;
1783 }
1784
1785
1786
1787 /***********************************************************************
1788  *     AllocLSThunkletSysthunk             (KERNEL.607)
1789  */
1790 FARPROC WINAPI AllocLSThunkletSysthunk16( SEGPTR target,
1791                                           FARPROC relay, DWORD dummy )
1792 {
1793     if (!ThunkletSysthunkGlueLS) THUNK_Init();
1794     return THUNK_AllocLSThunklet( (SEGPTR)relay, (DWORD)target,
1795                                   ThunkletSysthunkGlueLS, GetCurrentTask() );
1796 }
1797
1798 /***********************************************************************
1799  *     AllocSLThunkletSysthunk             (KERNEL.608)
1800  */
1801 SEGPTR WINAPI AllocSLThunkletSysthunk16( FARPROC target,
1802                                        SEGPTR relay, DWORD dummy )
1803 {
1804     if (!ThunkletSysthunkGlueSL) THUNK_Init();
1805     return THUNK_AllocSLThunklet( (FARPROC)relay, (DWORD)target,
1806                                   ThunkletSysthunkGlueSL, GetCurrentTask() );
1807 }
1808
1809
1810 /***********************************************************************
1811  *     AllocLSThunkletCallbackEx           (KERNEL.567)
1812  */
1813 FARPROC WINAPI AllocLSThunkletCallbackEx16( SEGPTR target,
1814                                             DWORD relay, HTASK16 task )
1815 {
1816     THUNKLET *thunk = MapSL( target );
1817     if ( !thunk ) return NULL;
1818
1819     if (   IsSLThunklet16( thunk ) && thunk->relay == relay
1820         && thunk->glue == (DWORD)ThunkletCallbackGlueSL )
1821         return (FARPROC)thunk->target;
1822
1823     return THUNK_AllocLSThunklet( target, relay,
1824                                   ThunkletCallbackGlueLS, task );
1825 }
1826
1827 /***********************************************************************
1828  *     AllocSLThunkletCallbackEx           (KERNEL.568)
1829  */
1830 SEGPTR WINAPI AllocSLThunkletCallbackEx16( FARPROC target,
1831                                          DWORD relay, HTASK16 task )
1832 {
1833     THUNKLET *thunk = (THUNKLET *)target;
1834     if ( !thunk ) return 0;
1835
1836     if (   IsLSThunklet( thunk ) && thunk->relay == relay
1837         && thunk->glue == (DWORD)ThunkletCallbackGlueLS - (DWORD)&thunk->type )
1838         return (SEGPTR)thunk->target;
1839
1840     return THUNK_AllocSLThunklet( target, relay,
1841                                   ThunkletCallbackGlueSL, task );
1842 }
1843
1844 /***********************************************************************
1845  *     AllocLSThunkletCallback             (KERNEL.561)
1846  *     AllocLSThunkletCallback_dup         (KERNEL.606)
1847  */
1848 FARPROC WINAPI AllocLSThunkletCallback16( SEGPTR target, DWORD relay )
1849 {
1850     return AllocLSThunkletCallbackEx16( target, relay, GetCurrentTask() );
1851 }
1852
1853 /***********************************************************************
1854  *     AllocSLThunkletCallback             (KERNEL.562)
1855  *     AllocSLThunkletCallback_dup         (KERNEL.605)
1856  */
1857 SEGPTR WINAPI AllocSLThunkletCallback16( FARPROC target, DWORD relay )
1858 {
1859     return AllocSLThunkletCallbackEx16( target, relay, GetCurrentTask() );
1860 }
1861
1862 /***********************************************************************
1863  *     FindLSThunkletCallback              (KERNEL.563)
1864  *     FindLSThunkletCallback_dup          (KERNEL.609)
1865  */
1866 FARPROC WINAPI FindLSThunkletCallback( SEGPTR target, DWORD relay )
1867 {
1868     THUNKLET *thunk = MapSL( target );
1869     if (   thunk && IsSLThunklet16( thunk ) && thunk->relay == relay
1870         && thunk->glue == (DWORD)ThunkletCallbackGlueSL )
1871         return (FARPROC)thunk->target;
1872
1873     thunk = THUNK_FindThunklet( (DWORD)target, relay,
1874                                 (DWORD)ThunkletCallbackGlueLS,
1875                                 THUNKLET_TYPE_LS );
1876     return (FARPROC)thunk;
1877 }
1878
1879 /***********************************************************************
1880  *     FindSLThunkletCallback              (KERNEL.564)
1881  *     FindSLThunkletCallback_dup          (KERNEL.610)
1882  */
1883 SEGPTR WINAPI FindSLThunkletCallback( FARPROC target, DWORD relay )
1884 {
1885     THUNKLET *thunk = (THUNKLET *)target;
1886     if (   thunk && IsLSThunklet( thunk ) && thunk->relay == relay
1887         && thunk->glue == (DWORD)ThunkletCallbackGlueLS - (DWORD)&thunk->type )
1888         return (SEGPTR)thunk->target;
1889
1890     thunk = THUNK_FindThunklet( (DWORD)target, relay,
1891                                 (DWORD)ThunkletCallbackGlueSL,
1892                                 THUNKLET_TYPE_SL );
1893     return get_segptr( thunk );
1894 }
1895
1896
1897 /***********************************************************************
1898  *     FreeThunklet            (KERNEL.611)
1899  */
1900 BOOL16 WINAPI FreeThunklet16( DWORD unused1, DWORD unused2 )
1901 {
1902     return FALSE;
1903 }
1904
1905
1906 /***********************************************************************
1907  * Callback Client API
1908  */
1909
1910 #define N_CBC_FIXED    20
1911 #define N_CBC_VARIABLE 10
1912 #define N_CBC_TOTAL    (N_CBC_FIXED + N_CBC_VARIABLE)
1913
1914 static SEGPTR CBClientRelay16[ N_CBC_TOTAL ];
1915 static FARPROC *CBClientRelay32[ N_CBC_TOTAL ];
1916
1917 /***********************************************************************
1918  *     RegisterCBClient                    (KERNEL.619)
1919  */
1920 INT16 WINAPI RegisterCBClient16( INT16 wCBCId,
1921                                  SEGPTR relay16, FARPROC *relay32 )
1922 {
1923     /* Search for free Callback ID */
1924     if ( wCBCId == -1 )
1925         for ( wCBCId = N_CBC_FIXED; wCBCId < N_CBC_TOTAL; wCBCId++ )
1926             if ( !CBClientRelay16[ wCBCId ] )
1927                 break;
1928
1929     /* Register Callback ID */
1930     if ( wCBCId > 0 && wCBCId < N_CBC_TOTAL )
1931     {
1932         CBClientRelay16[ wCBCId ] = relay16;
1933         CBClientRelay32[ wCBCId ] = relay32;
1934     }
1935     else
1936         wCBCId = 0;
1937
1938     return wCBCId;
1939 }
1940
1941 /***********************************************************************
1942  *     UnRegisterCBClient                  (KERNEL.622)
1943  */
1944 INT16 WINAPI UnRegisterCBClient16( INT16 wCBCId,
1945                                    SEGPTR relay16, FARPROC *relay32 )
1946 {
1947     if (    wCBCId >= N_CBC_FIXED && wCBCId < N_CBC_TOTAL
1948          && CBClientRelay16[ wCBCId ] == relay16
1949          && CBClientRelay32[ wCBCId ] == relay32 )
1950     {
1951         CBClientRelay16[ wCBCId ] = 0;
1952         CBClientRelay32[ wCBCId ] = 0;
1953     }
1954     else
1955         wCBCId = 0;
1956
1957     return wCBCId;
1958 }
1959
1960
1961 /***********************************************************************
1962  *     InitCBClient                        (KERNEL.623)
1963  */
1964 void WINAPI InitCBClient16( FARPROC glueLS )
1965 {
1966     HMODULE16 kernel = GetModuleHandle16( "KERNEL" );
1967     SEGPTR glueSL = (SEGPTR)GetProcAddress16( kernel, (LPCSTR)604 );
1968
1969     SetThunkletCallbackGlue16( glueLS, glueSL );
1970 }
1971
1972 /***********************************************************************
1973  *     CBClientGlueSL                      (KERNEL.604)
1974  */
1975 void WINAPI CBClientGlueSL( CONTEXT86 *context )
1976 {
1977     /* Create stack frame */
1978     SEGPTR stackSeg = stack16_push( 12 );
1979     LPWORD stackLin = MapSL( stackSeg );
1980     SEGPTR glue, *glueTab;
1981
1982     stackLin[3] = (WORD)context->Ebp;
1983     stackLin[2] = (WORD)context->Esi;
1984     stackLin[1] = (WORD)context->Edi;
1985     stackLin[0] = (WORD)context->SegDs;
1986
1987     context->Ebp = OFFSETOF( stackSeg ) + 6;
1988     context->Esp = OFFSETOF( stackSeg ) - 4;
1989     context->SegGs = 0;
1990
1991     /* Jump to 16-bit relay code */
1992     glueTab = MapSL( CBClientRelay16[ stackLin[5] ] );
1993     glue = glueTab[ stackLin[4] ];
1994     context->SegCs = SELECTOROF( glue );
1995     context->Eip   = OFFSETOF  ( glue );
1996 }
1997
1998 /***********************************************************************
1999  *     CBClientThunkSL                      (KERNEL.620)
2000  */
2001 extern DWORD CALL32_CBClient( FARPROC proc, LPWORD args, WORD *stackLin, DWORD *esi );
2002 void WINAPI CBClientThunkSL( CONTEXT86 *context )
2003 {
2004     /* Call 32-bit relay code */
2005
2006     LPWORD args = MapSL( MAKESEGPTR( context->SegSs, LOWORD(context->Ebp) ) );
2007     FARPROC proc = CBClientRelay32[ args[2] ][ args[1] ];
2008
2009     /* fill temporary area for the asm code (see comments in winebuild) */
2010     SEGPTR stack = stack16_push( 12 );
2011     LPWORD stackLin = MapSL(stack);
2012     /* stackLin[0] and stackLin[1] reserved for the 32-bit stack ptr */
2013     stackLin[2] = wine_get_ss();
2014     stackLin[3] = 0;
2015     stackLin[4] = OFFSETOF(stack) + 12;
2016     stackLin[5] = SELECTOROF(stack);
2017     stackLin[6] = OFFSETOF(CALL32_CBClientEx_RetAddr);  /* overwrite return address */
2018     stackLin[7] = SELECTOROF(CALL32_CBClientEx_RetAddr);
2019     context->Eax = CALL32_CBClient( proc, args, stackLin + 4, &context->Esi );
2020     stack16_pop( 12 );
2021 }
2022
2023 /***********************************************************************
2024  *     CBClientThunkSLEx                    (KERNEL.621)
2025  */
2026 extern DWORD CALL32_CBClientEx( FARPROC proc, LPWORD args, WORD *stackLin, DWORD *esi, INT *nArgs );
2027 void WINAPI CBClientThunkSLEx( CONTEXT86 *context )
2028 {
2029     /* Call 32-bit relay code */
2030
2031     LPWORD args = MapSL( MAKESEGPTR( context->SegSs, LOWORD(context->Ebp) ) );
2032     FARPROC proc = CBClientRelay32[ args[2] ][ args[1] ];
2033     INT nArgs;
2034     LPWORD stackLin;
2035
2036     /* fill temporary area for the asm code (see comments in winebuild) */
2037     SEGPTR stack = stack16_push( 24 );
2038     stackLin = MapSL(stack);
2039     stackLin[0] = OFFSETOF(stack) + 4;
2040     stackLin[1] = SELECTOROF(stack);
2041     stackLin[2] = wine_get_ds();
2042     stackLin[5] = OFFSETOF(stack) + 24;
2043     /* stackLin[6] and stackLin[7] reserved for the 32-bit stack ptr */
2044     stackLin[8] = wine_get_ss();
2045     stackLin[9] = 0;
2046     stackLin[10] = OFFSETOF(CALL32_CBClientEx_RetAddr);
2047     stackLin[11] = SELECTOROF(CALL32_CBClientEx_RetAddr);
2048
2049     context->Eax = CALL32_CBClientEx( proc, args, stackLin, &context->Esi, &nArgs );
2050     stack16_pop( 24 );
2051
2052     /* Restore registers saved by CBClientGlueSL */
2053     stackLin = (LPWORD)((LPBYTE)CURRENT_STACK16 + sizeof(STACK16FRAME) - 4);
2054     context->Ebp = (context->Ebp & ~0xffff) | stackLin[3];
2055     context->Esi = (context->Esi & ~0xffff) | stackLin[2];
2056     context->Edi = (context->Edi & ~0xffff) | stackLin[1];
2057     context->SegDs = stackLin[0];
2058     context->Esp += 16+nArgs;
2059
2060     /* Return to caller of CBClient thunklet */
2061     context->SegCs = stackLin[9];
2062     context->Eip   = stackLin[8];
2063 }
2064
2065
2066 /***********************************************************************
2067  *           Get16DLLAddress       (KERNEL32.@)
2068  *
2069  * This function is used by a Win32s DLL if it wants to call a Win16 function.
2070  * A 16:16 segmented pointer to the function is returned.
2071  * Written without any docu.
2072  */
2073 SEGPTR WINAPI Get16DLLAddress(HMODULE16 handle, LPSTR func_name)
2074 {
2075     static WORD code_sel32;
2076     FARPROC16 proc_16;
2077     LPBYTE thunk;
2078
2079     if (!code_sel32)
2080     {
2081         if (!ThunkletHeap) THUNK_Init();
2082         code_sel32 = SELECTOR_AllocBlock( ThunkletHeap, 0x10000,
2083                                           WINE_LDT_FLAGS_CODE | WINE_LDT_FLAGS_32BIT );
2084         if (!code_sel32) return 0;
2085     }
2086     if (!(thunk = HeapAlloc( ThunkletHeap, 0, 32 ))) return 0;
2087
2088     if (!handle) handle = GetModuleHandle16("WIN32S16");
2089     proc_16 = GetProcAddress16(handle, func_name);
2090
2091     /* movl proc_16, $edx */
2092     *thunk++ = 0xba;
2093     *(FARPROC16 *)thunk = proc_16;
2094     thunk += sizeof(FARPROC16);
2095
2096      /* jmpl QT_Thunk */
2097     *thunk++ = 0xea;
2098     *(void **)thunk = QT_Thunk;
2099     thunk += sizeof(FARPROC16);
2100     *(WORD *)thunk = wine_get_cs();
2101
2102     return MAKESEGPTR( code_sel32, (char *)thunk - (char *)ThunkletHeap );
2103 }
2104
2105
2106 /***********************************************************************
2107  *              GetWin16DOSEnv                  (KERNEL32.34)
2108  * Returns some internal value.... probably the default environment database?
2109  */
2110 DWORD WINAPI GetWin16DOSEnv(void)
2111 {
2112         FIXME("stub, returning 0\n");
2113         return 0;
2114 }
2115
2116 /**********************************************************************
2117  *           GetPK16SysVar    (KERNEL32.92)
2118  */
2119 LPVOID WINAPI GetPK16SysVar(void)
2120 {
2121     static BYTE PK16SysVar[128];
2122
2123     FIXME("()\n");
2124     return PK16SysVar;
2125 }
2126
2127 /**********************************************************************
2128  *           CommonUnimpStub    (KERNEL32.17)
2129  */
2130 void WINAPI __regs_CommonUnimpStub( CONTEXT86 *context )
2131 {
2132     FIXME("generic stub: %s\n", ((LPSTR)context->Eax ? (LPSTR)context->Eax : "?"));
2133
2134     switch ((context->Ecx >> 4) & 0x0f)
2135     {
2136     case 15:  context->Eax = -1;   break;
2137     case 14:  context->Eax = 0x78; break;
2138     case 13:  context->Eax = 0x32; break;
2139     case 1:   context->Eax = 1;    break;
2140     default:  context->Eax = 0;    break;
2141     }
2142
2143     context->Esp += (context->Ecx & 0x0f) * 4;
2144 }
2145 DEFINE_REGS_ENTRYPOINT( CommonUnimpStub, 0 )
2146
2147 /**********************************************************************
2148  *           HouseCleanLogicallyDeadHandles    (KERNEL32.33)
2149  */
2150 void WINAPI HouseCleanLogicallyDeadHandles(void)
2151 {
2152     /* Whatever this is supposed to do, our handles probably
2153        don't need it :-) */
2154 }
2155
2156 /**********************************************************************
2157  *              @ (KERNEL32.100)
2158  */
2159 BOOL WINAPI _KERNEL32_100(HANDLE threadid,DWORD exitcode,DWORD x)
2160 {
2161         FIXME("(%p,%d,0x%08x): stub\n",threadid,exitcode,x);
2162         return TRUE;
2163 }
2164
2165 /**********************************************************************
2166  *              @ (KERNEL32.99)
2167  *
2168  * Checks whether the clock has to be switched from daylight
2169  * savings time to standard time or vice versa.
2170  *
2171  */
2172 DWORD WINAPI _KERNEL32_99(DWORD x)
2173 {
2174         FIXME("(0x%08x): stub\n",x);
2175         return 1;
2176 }
2177
2178
2179 /***********************************************************************
2180  * Helper for k32 family functions
2181  */
2182 static void *user32_proc_address(const char *proc_name)
2183 {
2184     static HMODULE hUser32;
2185
2186     if(!hUser32) hUser32 = LoadLibraryA("user32.dll");
2187     return GetProcAddress(hUser32, proc_name);
2188 }
2189
2190 /***********************************************************************
2191  *              k32CharToOemBuffA   (KERNEL32.11)
2192  */
2193 BOOL WINAPI k32CharToOemBuffA(LPCSTR s, LPSTR d, DWORD len)
2194 {
2195     WCHAR *bufW;
2196
2197     if ((bufW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2198     {
2199         MultiByteToWideChar( CP_ACP, 0, s, len, bufW, len );
2200         WideCharToMultiByte( CP_OEMCP, 0, bufW, len, d, len, NULL, NULL );
2201         HeapFree( GetProcessHeap(), 0, bufW );
2202     }
2203     return TRUE;
2204 }
2205
2206 /***********************************************************************
2207  *              k32CharToOemA   (KERNEL32.10)
2208  */
2209 BOOL WINAPI k32CharToOemA(LPCSTR s, LPSTR d)
2210 {
2211     if (!s || !d) return TRUE;
2212     return k32CharToOemBuffA( s, d, strlen(s) + 1 );
2213 }
2214
2215 /***********************************************************************
2216  *              k32OemToCharBuffA   (KERNEL32.13)
2217  */
2218 BOOL WINAPI k32OemToCharBuffA(LPCSTR s, LPSTR d, DWORD len)
2219 {
2220     WCHAR *bufW;
2221
2222     if ((bufW = HeapAlloc( GetProcessHeap(), 0, len * sizeof(WCHAR) )))
2223     {
2224         MultiByteToWideChar( CP_OEMCP, 0, s, len, bufW, len );
2225         WideCharToMultiByte( CP_ACP, 0, bufW, len, d, len, NULL, NULL );
2226         HeapFree( GetProcessHeap(), 0, bufW );
2227     }
2228     return TRUE;
2229 }
2230
2231 /***********************************************************************
2232  *              k32OemToCharA   (KERNEL32.12)
2233  */
2234 BOOL WINAPI k32OemToCharA(LPCSTR s, LPSTR d)
2235 {
2236     return k32OemToCharBuffA( s, d, strlen(s) + 1 );
2237 }
2238
2239 /**********************************************************************
2240  *              k32LoadStringA   (KERNEL32.14)
2241  */
2242 INT WINAPI k32LoadStringA(HINSTANCE instance, UINT resource_id,
2243                           LPSTR buffer, INT buflen)
2244 {
2245     static INT (WINAPI *pLoadStringA)(HINSTANCE, UINT, LPSTR, INT);
2246
2247     if(!pLoadStringA) pLoadStringA = user32_proc_address("LoadStringA");
2248     return pLoadStringA(instance, resource_id, buffer, buflen);
2249 }
2250
2251 /***********************************************************************
2252  *              k32wvsprintfA   (KERNEL32.16)
2253  */
2254 INT WINAPI k32wvsprintfA(LPSTR buffer, LPCSTR spec, __ms_va_list args)
2255 {
2256     static INT (WINAPI *pwvsprintfA)(LPSTR, LPCSTR, __ms_va_list);
2257
2258     if(!pwvsprintfA) pwvsprintfA = user32_proc_address("wvsprintfA");
2259     return (*pwvsprintfA)(buffer, spec, args);
2260 }
2261
2262 /***********************************************************************
2263  *              k32wsprintfA   (KERNEL32.15)
2264  */
2265 INT WINAPIV k32wsprintfA(LPSTR buffer, LPCSTR spec, ...)
2266 {
2267     __ms_va_list args;
2268     INT res;
2269
2270     __ms_va_start(args, spec);
2271     res = k32wvsprintfA(buffer, spec, args);
2272     __ms_va_end(args);
2273     return res;
2274 }
2275
2276 /**********************************************************************
2277  *           Catch    (KERNEL.55)
2278  *
2279  * Real prototype is:
2280  *   INT16 WINAPI Catch( LPCATCHBUF lpbuf );
2281  */
2282 void WINAPI Catch16( LPCATCHBUF lpbuf, CONTEXT86 *context )
2283 {
2284     /* Note: we don't save the current ss, as the catch buffer is */
2285     /* only 9 words long. Hopefully no one will have the silly    */
2286     /* idea to change the current stack before calling Throw()... */
2287
2288     /* Windows uses:
2289      * lpbuf[0] = ip
2290      * lpbuf[1] = cs
2291      * lpbuf[2] = sp
2292      * lpbuf[3] = bp
2293      * lpbuf[4] = si
2294      * lpbuf[5] = di
2295      * lpbuf[6] = ds
2296      * lpbuf[7] = unused
2297      * lpbuf[8] = ss
2298      */
2299
2300     lpbuf[0] = LOWORD(context->Eip);
2301     lpbuf[1] = context->SegCs;
2302     /* Windows pushes 4 more words before saving sp */
2303     lpbuf[2] = LOWORD(context->Esp) - 4 * sizeof(WORD);
2304     lpbuf[3] = LOWORD(context->Ebp);
2305     lpbuf[4] = LOWORD(context->Esi);
2306     lpbuf[5] = LOWORD(context->Edi);
2307     lpbuf[6] = context->SegDs;
2308     lpbuf[7] = 0;
2309     lpbuf[8] = context->SegSs;
2310     context->Eax &= ~0xffff;  /* Return 0 */
2311 }
2312
2313
2314 /**********************************************************************
2315  *           Throw    (KERNEL.56)
2316  *
2317  * Real prototype is:
2318  *   INT16 WINAPI Throw( LPCATCHBUF lpbuf, INT16 retval );
2319  */
2320 void WINAPI Throw16( LPCATCHBUF lpbuf, INT16 retval, CONTEXT86 *context )
2321 {
2322     STACK16FRAME *pFrame;
2323     STACK32FRAME *frame32;
2324
2325     context->Eax = (context->Eax & ~0xffff) | (WORD)retval;
2326
2327     /* Find the frame32 corresponding to the frame16 we are jumping to */
2328     pFrame = CURRENT_STACK16;
2329     frame32 = pFrame->frame32;
2330     while (frame32 && frame32->frame16)
2331     {
2332         if (OFFSETOF(frame32->frame16) < OFFSETOF(NtCurrentTeb()->WOW32Reserved))
2333             break;  /* Something strange is going on */
2334         if (OFFSETOF(frame32->frame16) > lpbuf[2])
2335         {
2336             /* We found the right frame */
2337             pFrame->frame32 = frame32;
2338             break;
2339         }
2340         frame32 = ((STACK16FRAME *)MapSL(frame32->frame16))->frame32;
2341     }
2342     RtlUnwind( &pFrame->frame32->frame, NULL, NULL, 0 );
2343
2344     context->Eip = lpbuf[0];
2345     context->SegCs  = lpbuf[1];
2346     context->Esp = lpbuf[2] + 4 * sizeof(WORD) - sizeof(WORD) /*extra arg*/;
2347     context->Ebp = lpbuf[3];
2348     context->Esi = lpbuf[4];
2349     context->Edi = lpbuf[5];
2350     context->SegDs  = lpbuf[6];
2351
2352     if (lpbuf[8] != context->SegSs)
2353         ERR("Switching stack segment with Throw() not supported; expect crash now\n" );
2354 }
2355
2356
2357 /*
2358  *  16-bit WOW routines (in KERNEL)
2359  */
2360
2361 /**********************************************************************
2362  *           GetVDMPointer32W      (KERNEL.516)
2363  */
2364 DWORD WINAPI GetVDMPointer32W16( SEGPTR vp, UINT16 fMode )
2365 {
2366     GlobalPageLock16(GlobalHandle16(SELECTOROF(vp)));
2367     return (DWORD)K32WOWGetVDMPointer( vp, 0, (DWORD)fMode );
2368 }
2369
2370 /***********************************************************************
2371  *           LoadLibraryEx32W      (KERNEL.513)
2372  */
2373 DWORD WINAPI LoadLibraryEx32W16( LPCSTR lpszLibFile, DWORD hFile, DWORD dwFlags )
2374 {
2375     HMODULE hModule;
2376     DWORD mutex_count;
2377     OFSTRUCT ofs;
2378     const char *p;
2379
2380     if (!lpszLibFile)
2381     {
2382         SetLastError(ERROR_INVALID_PARAMETER);
2383         return 0;
2384     }
2385
2386     /* if the file cannot be found, call LoadLibraryExA anyway, since it might be
2387        a builtin module. This case is handled in MODULE_LoadLibraryExA */
2388
2389     if ((p = strrchr( lpszLibFile, '.' )) && !strchr( p, '\\' ))  /* got an extension */
2390     {
2391         if (OpenFile16( lpszLibFile, &ofs, OF_EXIST ) != HFILE_ERROR16)
2392             lpszLibFile = ofs.szPathName;
2393     }
2394     else
2395     {
2396         char buffer[MAX_PATH+4];
2397         strcpy( buffer, lpszLibFile );
2398         strcat( buffer, ".dll" );
2399         if (OpenFile16( buffer, &ofs, OF_EXIST ) != HFILE_ERROR16)
2400             lpszLibFile = ofs.szPathName;
2401     }
2402
2403     ReleaseThunkLock( &mutex_count );
2404     hModule = LoadLibraryExA( lpszLibFile, (HANDLE)hFile, dwFlags );
2405     RestoreThunkLock( mutex_count );
2406
2407     return (DWORD)hModule;
2408 }
2409
2410 /***********************************************************************
2411  *           GetProcAddress32W     (KERNEL.515)
2412  */
2413 DWORD WINAPI GetProcAddress32W16( DWORD hModule, LPCSTR lpszProc )
2414 {
2415     return (DWORD)GetProcAddress( (HMODULE)hModule, lpszProc );
2416 }
2417
2418 /***********************************************************************
2419  *           FreeLibrary32W        (KERNEL.514)
2420  */
2421 DWORD WINAPI FreeLibrary32W16( DWORD hLibModule )
2422 {
2423     BOOL retv;
2424     DWORD mutex_count;
2425
2426     ReleaseThunkLock( &mutex_count );
2427     retv = FreeLibrary( (HMODULE)hLibModule );
2428     RestoreThunkLock( mutex_count );
2429     return (DWORD)retv;
2430 }
2431
2432
2433 #define CPEX_DEST_STDCALL   0x00000000
2434 #define CPEX_DEST_CDECL     0x80000000
2435
2436 /**********************************************************************
2437  *           WOW_CallProc32W
2438  */
2439 static DWORD WOW_CallProc32W16( FARPROC proc32, DWORD nrofargs, DWORD *args )
2440 {
2441     DWORD ret;
2442     DWORD mutex_count;
2443
2444     ReleaseThunkLock( &mutex_count );
2445     if (!proc32) ret = 0;
2446     else ret = call_entry_point( proc32, nrofargs & ~CPEX_DEST_CDECL, args );
2447     RestoreThunkLock( mutex_count );
2448
2449     TRACE("returns %08x\n",ret);
2450     return ret;
2451 }
2452
2453 /**********************************************************************
2454  *           CallProc32W           (KERNEL.517)
2455  */
2456 DWORD WINAPIV CallProc32W16( DWORD nrofargs, DWORD argconvmask, FARPROC proc32, VA_LIST16 valist )
2457 {
2458     DWORD args[32];
2459     unsigned int i;
2460
2461     TRACE("(%d,%d,%p args[",nrofargs,argconvmask,proc32);
2462
2463     for (i=0;i<nrofargs;i++)
2464     {
2465         if (argconvmask & (1<<i))
2466         {
2467             SEGPTR ptr = VA_ARG16( valist, SEGPTR );
2468             /* pascal convention, have to reverse the arguments order */
2469             args[nrofargs - i - 1] = (DWORD)MapSL(ptr);
2470             TRACE("%08x(%p),",ptr,MapSL(ptr));
2471         }
2472         else
2473         {
2474             DWORD arg = VA_ARG16( valist, DWORD );
2475             /* pascal convention, have to reverse the arguments order */
2476             args[nrofargs - i - 1] = arg;
2477             TRACE("%d,", arg);
2478         }
2479     }
2480     TRACE("])\n");
2481
2482     /* POP nrofargs DWORD arguments and 3 DWORD parameters */
2483     stack16_pop( (3 + nrofargs) * sizeof(DWORD) );
2484
2485     return WOW_CallProc32W16( proc32, nrofargs, args );
2486 }
2487
2488 /**********************************************************************
2489  *           _CallProcEx32W         (KERNEL.518)
2490  */
2491 DWORD WINAPIV CallProcEx32W16( DWORD nrofargs, DWORD argconvmask, FARPROC proc32, VA_LIST16 valist )
2492 {
2493     DWORD args[32];
2494     unsigned int i;
2495
2496     TRACE("(%d,%d,%p args[",nrofargs,argconvmask,proc32);
2497
2498     for (i=0;i<nrofargs;i++)
2499     {
2500         if (argconvmask & (1<<i))
2501         {
2502             SEGPTR ptr = VA_ARG16( valist, SEGPTR );
2503             args[i] = (DWORD)MapSL(ptr);
2504             TRACE("%08x(%p),",ptr,MapSL(ptr));
2505         }
2506         else
2507         {
2508             DWORD arg = VA_ARG16( valist, DWORD );
2509             args[i] = arg;
2510             TRACE("%d,", arg);
2511         }
2512     }
2513     TRACE("])\n");
2514     return WOW_CallProc32W16( proc32, nrofargs, args );
2515 }
2516
2517
2518 /**********************************************************************
2519  *           WOW16Call               (KERNEL.500)
2520  *
2521  * FIXME!!!
2522  *
2523  */
2524 DWORD WINAPIV WOW16Call(WORD x, WORD y, WORD z, VA_LIST16 args)
2525 {
2526         int     i;
2527         DWORD   calladdr;
2528         FIXME("(0x%04x,0x%04x,%d),calling (",x,y,z);
2529
2530         for (i=0;i<x/2;i++) {
2531                 WORD    a = VA_ARG16(args,WORD);
2532                 DPRINTF("%04x ",a);
2533         }
2534         calladdr = VA_ARG16(args,DWORD);
2535         stack16_pop( 3*sizeof(WORD) + x + sizeof(DWORD) );
2536         DPRINTF(") calling address was 0x%08x\n",calladdr);
2537         return 0;
2538 }