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