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