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