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