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