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