Implemented DosFileHandleToWin32Handle, Win32HandleToDosFileHandle and
[wine] / dlls / kernel / thunk.c
1 /*
2  * KERNEL32 thunks and other undocumented stuff
3  *
4  * Copyright 1996, 1997 Alexandre Julliard
5  * Copyright 1997, 1998 Marcus Meissner
6  * Copyright 1998       Ulrich Weigand
7  *
8  */
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 "task.h"
28
29 DEFAULT_DEBUG_CHANNEL(thunk);
30
31
32 /***********************************************************************
33  *                                                                     *
34  *                 Win95 internal thunks                               *
35  *                                                                     *
36  ***********************************************************************/
37
38 /***********************************************************************
39  *           LogApiThk    (KERNEL.423)
40  */
41 void WINAPI LogApiThk( LPSTR func )
42 {
43     TRACE( "%s\n", debugstr_a(func) );
44 }
45
46 /***********************************************************************
47  *           LogApiThkLSF    (KERNEL32.42)
48  * 
49  * NOTE: needs to preserve all registers!
50  */
51 void WINAPI LogApiThkLSF( LPSTR func, CONTEXT86 *context )
52 {
53     TRACE( "%s\n", debugstr_a(func) );
54 }
55
56 /***********************************************************************
57  *           LogApiThkSL    (KERNEL32.44)
58  * 
59  * NOTE: needs to preserve all registers!
60  */
61 void WINAPI LogApiThkSL( LPSTR func, CONTEXT86 *context )
62 {
63     TRACE( "%s\n", debugstr_a(func) );
64 }
65
66 /***********************************************************************
67  *           LogCBThkSL    (KERNEL32.47)
68  * 
69  * NOTE: needs to preserve all registers!
70  */
71 void WINAPI LogCBThkSL( LPSTR func, CONTEXT86 *context )
72 {
73     TRACE( "%s\n", debugstr_a(func) );
74 }
75
76 /***********************************************************************
77  * Generates a FT_Prolog call.
78  *      
79  *  0FB6D1                  movzbl edx,cl
80  *  8B1495xxxxxxxx          mov edx,[4*edx + targetTable]
81  *  68xxxxxxxx              push FT_Prolog
82  *  C3                      lret
83  */
84 static void _write_ftprolog(LPBYTE relayCode ,DWORD *targetTable) {
85         LPBYTE  x;
86
87         x       = relayCode;
88         *x++    = 0x0f;*x++=0xb6;*x++=0xd1; /* movzbl edx,cl */
89         *x++    = 0x8B;*x++=0x14;*x++=0x95;*(DWORD**)x= targetTable;
90         x+=4;   /* mov edx, [4*edx + targetTable] */
91         *x++    = 0x68; *(DWORD*)x = (DWORD)GetProcAddress(GetModuleHandleA("KERNEL32"),"FT_Prolog");
92         x+=4;   /* push FT_Prolog */
93         *x++    = 0xC3;         /* lret */
94         /* fill rest with 0xCC / int 3 */
95 }
96
97 /***********************************************************************
98  *      _write_qtthunk                                  (internal)
99  * Generates a QT_Thunk style call.
100  *
101  *  33C9                    xor ecx, ecx
102  *  8A4DFC                  mov cl , [ebp-04]
103  *  8B148Dxxxxxxxx          mov edx, [4*ecx + targetTable]
104  *  B8yyyyyyyy              mov eax, QT_Thunk
105  *  FFE0                    jmp eax
106  */
107 static void _write_qtthunk(
108         LPBYTE relayCode,       /* [in] start of QT_Thunk stub */
109         DWORD *targetTable      /* [in] start of thunk (for index lookup) */
110 ) {
111         LPBYTE  x;
112
113         x       = relayCode;
114         *x++    = 0x33;*x++=0xC9; /* xor ecx,ecx */
115         *x++    = 0x8A;*x++=0x4D;*x++=0xFC; /* movb cl,[ebp-04] */
116         *x++    = 0x8B;*x++=0x14;*x++=0x8D;*(DWORD**)x= targetTable;
117         x+=4;   /* mov edx, [4*ecx + targetTable */
118         *x++    = 0xB8; *(DWORD*)x = (DWORD)GetProcAddress(GetModuleHandleA("KERNEL32"),"QT_Thunk");
119         x+=4;   /* mov eax , QT_Thunk */
120         *x++    = 0xFF; *x++ = 0xE0;    /* jmp eax */
121         /* should fill the rest of the 32 bytes with 0xCC */
122 }
123
124 /***********************************************************************
125  *           _loadthunk
126  */
127 static LPVOID _loadthunk(LPCSTR module, LPCSTR func, LPCSTR module32, 
128                          struct ThunkDataCommon *TD32, DWORD checksum)
129 {
130     struct ThunkDataCommon *TD16;
131     HMODULE hmod;
132     int ordinal;
133
134     if ((hmod = LoadLibrary16(module)) <= 32) 
135     {
136         ERR("(%s, %s, %s): Unable to load '%s', error %d\n",
137                    module, func, module32, module, hmod);
138         return 0;
139     }
140
141     if (   !(ordinal = NE_GetOrdinal(hmod, func))
142         || !(TD16 = PTR_SEG_TO_LIN(NE_GetEntryPointEx(hmod, ordinal, FALSE))))
143     {
144         ERR("Unable to find thunk data '%s' in %s, required by %s (conflicting/incorrect DLL versions !?).\n",
145                    func, module, module32);
146         return 0;
147     }
148
149     if (TD32 && memcmp(TD16->magic, TD32->magic, 4))
150     {
151         ERR("(%s, %s, %s): Bad magic %c%c%c%c (should be %c%c%c%c)\n",
152                    module, func, module32, 
153                    TD16->magic[0], TD16->magic[1], TD16->magic[2], TD16->magic[3],
154                    TD32->magic[0], TD32->magic[1], TD32->magic[2], TD32->magic[3]);
155         return 0;
156     }
157
158     if (TD32 && TD16->checksum != TD32->checksum)
159     {
160         ERR("(%s, %s, %s): Wrong checksum %08lx (should be %08lx)\n",
161                    module, func, module32, TD16->checksum, TD32->checksum);
162         return 0;
163     }
164
165     if (!TD32 && checksum && checksum != *(LPDWORD)TD16)
166     {
167         ERR("(%s, %s, %s): Wrong checksum %08lx (should be %08lx)\n",
168                    module, func, module32, *(LPDWORD)TD16, checksum);
169         return 0;
170     }
171
172     return TD16;
173 }
174
175 /***********************************************************************
176  *           GetThunkStuff    (KERNEL32.53)
177  */
178 LPVOID WINAPI GetThunkStuff(LPSTR module, LPSTR func)
179 {
180     return _loadthunk(module, func, "<kernel>", NULL, 0L);
181 }
182
183 /***********************************************************************
184  *           GetThunkBuff    (KERNEL32.52)
185  * Returns a pointer to ThkBuf in the 16bit library SYSTHUNK.DLL.
186  */
187 LPVOID WINAPI GetThunkBuff(void)
188 {
189     return GetThunkStuff("SYSTHUNK.DLL", "ThkBuf");
190 }
191
192 /***********************************************************************
193  *              ThunkConnect32          (KERNEL32)
194  * Connects a 32bit and a 16bit thunkbuffer.
195  */
196 UINT WINAPI ThunkConnect32( 
197         struct ThunkDataCommon *TD,  /* [in/out] thunkbuffer */
198         LPSTR thunkfun16,            /* [in] win16 thunkfunction */
199         LPSTR module16,              /* [in] name of win16 dll */
200         LPSTR module32,              /* [in] name of win32 dll */
201         HMODULE hmod32,            /* [in] hmodule of win32 dll */
202         DWORD dwReason               /* [in] initialisation argument */
203 ) {
204     BOOL directionSL;
205
206     if (!strncmp(TD->magic, "SL01", 4))
207     {
208         directionSL = TRUE;
209
210         TRACE("SL01 thunk %s (%lx) <- %s (%s), Reason: %ld\n",
211                      module32, (DWORD)TD, module16, thunkfun16, dwReason);
212     }
213     else if (!strncmp(TD->magic, "LS01", 4))
214     {
215         directionSL = FALSE;
216
217         TRACE("LS01 thunk %s (%lx) -> %s (%s), Reason: %ld\n",
218                      module32, (DWORD)TD, module16, thunkfun16, dwReason);
219     }
220     else
221     {
222         ERR("Invalid magic %c%c%c%c\n", 
223                    TD->magic[0], TD->magic[1], TD->magic[2], TD->magic[3]);
224         return 0;
225     }
226     
227     switch (dwReason)
228     {
229         case DLL_PROCESS_ATTACH:
230         {
231             struct ThunkDataCommon *TD16;
232             if (!(TD16 = _loadthunk(module16, thunkfun16, module32, TD, 0L)))
233                 return 0;
234
235             if (directionSL)
236             {
237                 struct ThunkDataSL32 *SL32 = (struct ThunkDataSL32 *)TD;
238                 struct ThunkDataSL16 *SL16 = (struct ThunkDataSL16 *)TD16;
239                 struct SLTargetDB *tdb;
240
241                 if (SL16->fpData == NULL)
242                 {
243                     ERR("ThunkConnect16 was not called!\n");
244                     return 0;
245                 }
246
247                 SL32->data = SL16->fpData;
248
249                 tdb = HeapAlloc(GetProcessHeap(), 0, sizeof(*tdb));
250                 tdb->process = GetCurrentProcessId();
251                 tdb->targetTable = (DWORD *)(thunkfun16 + SL32->offsetTargetTable);
252
253                 tdb->next = SL32->data->targetDB;   /* FIXME: not thread-safe! */
254                 SL32->data->targetDB = tdb;
255
256                 TRACE("Process %08lx allocated TargetDB entry for ThunkDataSL %08lx\n", 
257                              GetCurrentProcessId(), (DWORD)SL32->data);
258             }
259             else
260             {
261                 struct ThunkDataLS32 *LS32 = (struct ThunkDataLS32 *)TD;
262                 struct ThunkDataLS16 *LS16 = (struct ThunkDataLS16 *)TD16;
263
264                 LS32->targetTable = PTR_SEG_TO_LIN(LS16->targetTable);
265
266                 /* write QT_Thunk and FT_Prolog stubs */
267                 _write_qtthunk ((LPBYTE)TD + LS32->offsetQTThunk,  LS32->targetTable);
268                 _write_ftprolog((LPBYTE)TD + LS32->offsetFTProlog, LS32->targetTable);
269             }
270             break;
271         }
272
273         case DLL_PROCESS_DETACH:
274             /* FIXME: cleanup */
275             break;
276     }
277
278     return 1;
279 }
280
281 /**********************************************************************
282  *              QT_Thunk                        (KERNEL32)
283  *
284  * The target address is in EDX.
285  * The 16 bit arguments start at ESP.
286  * The number of 16bit argument bytes is EBP-ESP-0x40 (64 Byte thunksetup).
287  * [ok]
288  */
289 void WINAPI QT_Thunk( CONTEXT86 *context )
290 {
291     CONTEXT86 context16;
292     DWORD argsize;
293
294     memcpy(&context16,context,sizeof(context16));
295
296     context16.SegCs = HIWORD(context->Edx);
297     context16.Eip   = LOWORD(context->Edx);
298     context16.Ebp   = OFFSETOF( NtCurrentTeb()->cur_stack )
299                            + (WORD)&((STACK16FRAME*)0)->bp;
300
301     argsize = context->Ebp-context->Esp-0x40;
302
303     memcpy( (LPBYTE)CURRENT_STACK16 - argsize,
304             (LPBYTE)context->Esp, argsize );
305
306     CallTo16RegisterShort( &context16, argsize );
307     context->Eax = context16.Eax;
308     context->Edx = context16.Edx;
309     context->Ecx = context16.Ecx;
310
311     context->Esp +=   LOWORD(context16.Esp) -
312                         ( OFFSETOF( NtCurrentTeb()->cur_stack ) - argsize );
313 }
314
315
316 /**********************************************************************
317  *              FT_Prolog                       (KERNEL32.233)
318  * 
319  * The set of FT_... thunk routines is used instead of QT_Thunk,
320  * if structures have to be converted from 32-bit to 16-bit
321  * (change of member alignment, conversion of members).
322  *
323  * The thunk function (as created by the thunk compiler) calls
324  * FT_Prolog at the beginning, to set up a stack frame and
325  * allocate a 64 byte buffer on the stack.
326  * The input parameters (target address and some flags) are
327  * saved for later use by FT_Thunk.
328  *
329  * Input:  EDX  16-bit target address (SEGPTR)
330  *         CX   bits  0..7   target number (in target table)
331  *              bits  8..9   some flags (unclear???)
332  *              bits 10..15  number of DWORD arguments
333  *
334  * Output: A new stackframe is created, and a 64 byte buffer
335  *         allocated on the stack. The layout of the stack 
336  *         on return is as follows:
337  *
338  *  (ebp+4)  return address to caller of thunk function
339  *  (ebp)    old EBP
340  *  (ebp-4)  saved EBX register of caller
341  *  (ebp-8)  saved ESI register of caller
342  *  (ebp-12) saved EDI register of caller
343  *  (ebp-16) saved ECX register, containing flags
344  *  (ebp-20) bitmap containing parameters that are to be converted
345  *           by FT_Thunk; it is initialized to 0 by FT_Prolog and
346  *           filled in by the thunk code before calling FT_Thunk
347  *  (ebp-24)
348  *    ...    (unclear)
349  *  (ebp-44)
350  *  (ebp-48) saved EAX register of caller (unclear, never restored???)
351  *  (ebp-52) saved EDX register, containing 16-bit thunk target
352  *  (ebp-56)
353  *    ...    (unclear)
354  *  (ebp-64)
355  *
356  *  ESP is EBP-64 after return.
357  *         
358  */
359
360 void WINAPI FT_Prolog( CONTEXT86 *context )
361 {
362     /* Build stack frame */
363     stack32_push(context, context->Ebp);
364     context->Ebp = context->Esp;
365
366     /* Allocate 64-byte Thunk Buffer */
367     context->Esp -= 64;
368     memset((char *)context->Esp, '\0', 64);
369
370     /* Store Flags (ECX) and Target Address (EDX) */
371     /* Save other registers to be restored later */
372     *(DWORD *)(context->Ebp -  4) = context->Ebx;
373     *(DWORD *)(context->Ebp -  8) = context->Esi;
374     *(DWORD *)(context->Ebp - 12) = context->Edi;
375     *(DWORD *)(context->Ebp - 16) = context->Ecx;
376
377     *(DWORD *)(context->Ebp - 48) = context->Eax;
378     *(DWORD *)(context->Ebp - 52) = context->Edx;
379 }
380
381 /**********************************************************************
382  *              FT_Thunk                        (KERNEL32.234)
383  *
384  * This routine performs the actual call to 16-bit code, 
385  * similar to QT_Thunk. The differences are:
386  *  - The call target is taken from the buffer created by FT_Prolog
387  *  - Those arguments requested by the thunk code (by setting the
388  *    corresponding bit in the bitmap at EBP-20) are converted
389  *    from 32-bit pointers to segmented pointers (those pointers
390  *    are guaranteed to point to structures copied to the stack
391  *    by the thunk code, so we always use the 16-bit stack selector
392  *    for those addresses).
393  * 
394  *    The bit #i of EBP-20 corresponds here to the DWORD starting at
395  *    ESP+4 + 2*i.
396  * 
397  * FIXME: It is unclear what happens if there are more than 32 WORDs 
398  *        of arguments, so that the single DWORD bitmap is no longer
399  *        sufficient ...
400  */
401
402 void WINAPI FT_Thunk( CONTEXT86 *context )
403 {
404     DWORD mapESPrelative = *(DWORD *)(context->Ebp - 20);
405     DWORD callTarget     = *(DWORD *)(context->Ebp - 52);
406
407     CONTEXT86 context16;
408     DWORD i, argsize;
409     LPBYTE newstack, oldstack;
410
411     memcpy(&context16,context,sizeof(context16));
412
413     context16.SegCs = HIWORD(callTarget);
414     context16.Eip   = LOWORD(callTarget);
415     context16.Ebp   = OFFSETOF( NtCurrentTeb()->cur_stack )
416                            + (WORD)&((STACK16FRAME*)0)->bp;
417
418     argsize  = context->Ebp-context->Esp-0x40;
419     newstack = (LPBYTE)CURRENT_STACK16 - argsize;
420     oldstack = (LPBYTE)context->Esp;
421
422     memcpy( newstack, oldstack, argsize );
423
424     for (i = 0; i < 32; i++)    /* NOTE: What about > 32 arguments? */
425         if (mapESPrelative & (1 << i))
426         {
427             SEGPTR *arg = (SEGPTR *)(newstack + 2*i);
428             *arg = PTR_SEG_OFF_TO_SEGPTR(SELECTOROF(NtCurrentTeb()->cur_stack), 
429                                          OFFSETOF(NtCurrentTeb()->cur_stack) - argsize
430                                          + (*(LPBYTE *)arg - oldstack));
431         }
432
433     CallTo16RegisterShort( &context16, argsize );
434     context->Eax = context16.Eax;
435     context->Edx = context16.Edx;
436     context->Ecx = context16.Ecx;
437
438     context->Esp +=   LOWORD(context16.Esp) -
439                         ( OFFSETOF( NtCurrentTeb()->cur_stack ) - argsize );
440
441     /* Copy modified buffers back to 32-bit stack */
442     memcpy( oldstack, newstack, argsize );
443 }
444
445 /**********************************************************************
446  *              FT_ExitNN               (KERNEL32.218 - 232)
447  *
448  * One of the FT_ExitNN functions is called at the end of the thunk code.
449  * It removes the stack frame created by FT_Prolog, moves the function
450  * return from EBX to EAX (yes, FT_Thunk did use EAX for the return 
451  * value, but the thunk code has moved it from EAX to EBX in the 
452  * meantime ... :-), restores the caller's EBX, ESI, and EDI registers,
453  * and perform a return to the CALLER of the thunk code (while removing
454  * the given number of arguments from the caller's stack).
455  */
456
457 static void FT_Exit(CONTEXT86 *context, int nPopArgs)
458 {
459     /* Return value is in EBX */
460     context->Eax = context->Ebx;
461
462     /* Restore EBX, ESI, and EDI registers */
463     context->Ebx = *(DWORD *)(context->Ebp -  4);
464     context->Esi = *(DWORD *)(context->Ebp -  8);
465     context->Edi = *(DWORD *)(context->Ebp - 12);
466
467     /* Clean up stack frame */
468     context->Esp = context->Ebp;
469     context->Ebp = stack32_pop(context);
470
471     /* Pop return address to CALLER of thunk code */
472     context->Eip = stack32_pop(context);
473     /* Remove arguments */
474     context->Esp += nPopArgs;
475 }
476
477 /***********************************************************************
478  *              FT_Exit0 (KERNEL32.218)
479  */
480 void WINAPI FT_Exit0 (CONTEXT86 *context) { FT_Exit(context,  0); }
481
482 /***********************************************************************
483  *              FT_Exit4 (KERNEL32.219)
484  */
485 void WINAPI FT_Exit4 (CONTEXT86 *context) { FT_Exit(context,  4); }
486
487 /***********************************************************************
488  *              FT_Exit8 (KERNEL32.220)
489  */
490 void WINAPI FT_Exit8 (CONTEXT86 *context) { FT_Exit(context,  8); }
491
492 /***********************************************************************
493  *              FT_Exit12 (KERNEL32.221)
494  */
495 void WINAPI FT_Exit12(CONTEXT86 *context) { FT_Exit(context, 12); }
496
497 /***********************************************************************
498  *              FT_Exit16 (KERNEL32.222)
499  */
500 void WINAPI FT_Exit16(CONTEXT86 *context) { FT_Exit(context, 16); }
501
502 /***********************************************************************
503  *              FT_Exit20 (KERNEL32.223)
504  */
505 void WINAPI FT_Exit20(CONTEXT86 *context) { FT_Exit(context, 20); }
506
507 /***********************************************************************
508  *              FT_Exit24 (KERNEL32.224)
509  */
510 void WINAPI FT_Exit24(CONTEXT86 *context) { FT_Exit(context, 24); }
511
512 /***********************************************************************
513  *              FT_Exit28 (KERNEL32.225)
514  */
515 void WINAPI FT_Exit28(CONTEXT86 *context) { FT_Exit(context, 28); }
516
517 /***********************************************************************
518  *              FT_Exit32 (KERNEL32.226)
519  */
520 void WINAPI FT_Exit32(CONTEXT86 *context) { FT_Exit(context, 32); }
521
522 /***********************************************************************
523  *              FT_Exit36 (KERNEL32.227)
524  */
525 void WINAPI FT_Exit36(CONTEXT86 *context) { FT_Exit(context, 36); }
526
527 /***********************************************************************
528  *              FT_Exit40 (KERNEL32.228)
529  */
530 void WINAPI FT_Exit40(CONTEXT86 *context) { FT_Exit(context, 40); }
531
532 /***********************************************************************
533  *              FT_Exit44 (KERNEL32.229)
534  */
535 void WINAPI FT_Exit44(CONTEXT86 *context) { FT_Exit(context, 44); }
536
537 /***********************************************************************
538  *              FT_Exit48 (KERNEL32.230)
539  */
540 void WINAPI FT_Exit48(CONTEXT86 *context) { FT_Exit(context, 48); }
541
542 /***********************************************************************
543  *              FT_Exit52 (KERNEL32.231)
544  */
545 void WINAPI FT_Exit52(CONTEXT86 *context) { FT_Exit(context, 52); }
546
547 /***********************************************************************
548  *              FT_Exit56 (KERNEL32.232)
549  */
550 void WINAPI FT_Exit56(CONTEXT86 *context) { FT_Exit(context, 56); }
551
552 /***********************************************************************
553  *              ThunkInitLS     (KERNEL32.43)
554  * A thunkbuffer link routine 
555  * The thunkbuf looks like:
556  *
557  *      00: DWORD       length          ? don't know exactly
558  *      04: SEGPTR      ptr             ? where does it point to?
559  * The pointer ptr is written into the first DWORD of 'thunk'.
560  * (probably correctly implemented)
561  * [ok probably]
562  * RETURNS
563  *      segmented pointer to thunk?
564  */
565 DWORD WINAPI ThunkInitLS(
566         LPDWORD thunk,  /* [in] win32 thunk */
567         LPCSTR thkbuf,  /* [in] thkbuffer name in win16 dll */
568         DWORD len,      /* [in] thkbuffer length */
569         LPCSTR dll16,   /* [in] name of win16 dll */
570         LPCSTR dll32    /* [in] name of win32 dll (FIXME: not used?) */
571 ) {
572         LPDWORD         addr;
573
574         if (!(addr = _loadthunk( dll16, thkbuf, dll32, NULL, len )))
575                 return 0;
576
577         if (!addr[1])
578                 return 0;
579         *(DWORD*)thunk = addr[1];
580
581         return addr[1];
582 }
583
584 /***********************************************************************
585  *              Common32ThkLS   (KERNEL32.45)
586  * 
587  * This is another 32->16 thunk, independent of the QT_Thunk/FT_Thunk
588  * style thunks. The basic difference is that the parameter conversion 
589  * is done completely on the *16-bit* side here. Thus we do not call
590  * the 16-bit target directly, but call a common entry point instead.
591  * This entry function then calls the target according to the target
592  * number passed in the DI register.
593  * 
594  * Input:  EAX    SEGPTR to the common 16-bit entry point
595  *         CX     offset in thunk table (target number * 4)
596  *         DX     error return value if execution fails (unclear???)
597  *         EDX.HI number of DWORD parameters
598  *
599  * (Note that we need to move the thunk table offset from CX to DI !)
600  *
601  * The called 16-bit stub expects its stack to look like this:
602  *     ...
603  *   (esp+40)  32-bit arguments
604  *     ...
605  *   (esp+8)   32 byte of stack space available as buffer
606  *   (esp)     8 byte return address for use with 0x66 lret 
607  * 
608  * The called 16-bit stub uses a 0x66 lret to return to 32-bit code,
609  * and uses the EAX register to return a DWORD return value.
610  * Thus we need to use a special assembly glue routine 
611  * (CallRegisterLongProc instead of CallRegisterShortProc).
612  *
613  * Finally, we return to the caller, popping the arguments off 
614  * the stack.  The number of arguments to be popped is returned
615  * in the BL register by the called 16-bit routine.
616  *
617  */
618 void WINAPI Common32ThkLS( CONTEXT86 *context )
619 {
620     CONTEXT86 context16;
621     DWORD argsize;
622
623     memcpy(&context16,context,sizeof(context16));
624
625     context16.Edi   = LOWORD(context->Ecx);
626     context16.SegCs = HIWORD(context->Eax);
627     context16.Eip   = LOWORD(context->Eax);
628     context16.Ebp   = OFFSETOF( NtCurrentTeb()->cur_stack )
629                            + (WORD)&((STACK16FRAME*)0)->bp;
630
631     argsize = HIWORD(context->Edx) * 4;
632
633     /* FIXME: hack for stupid USER32 CallbackGlueLS routine */
634     if (context->Edx == context->Eip)
635         argsize = 6 * 4;
636
637     memcpy( (LPBYTE)CURRENT_STACK16 - argsize,
638             (LPBYTE)context->Esp, argsize );
639
640     CallTo16RegisterLong(&context16, argsize + 32);
641     context->Eax = context16.Eax;
642
643     /* Clean up caller's stack frame */
644     context->Esp += BL_reg(&context16);
645 }
646
647 /***********************************************************************
648  *              OT_32ThkLSF     (KERNEL32.40)
649  *
650  * YET Another 32->16 thunk. The difference to Common32ThkLS is that
651  * argument processing is done on both the 32-bit and the 16-bit side:
652  * The 32-bit side prepares arguments, copying them onto the stack.
653  * 
654  * When this routine is called, the first word on the stack is the 
655  * number of argument bytes prepared by the 32-bit code, and EDX
656  * contains the 16-bit target address.
657  *
658  * The called 16-bit routine is another relaycode, doing further 
659  * argument processing and then calling the real 16-bit target
660  * whose address is stored at [bp-04].
661  *
662  * The call proceeds using a normal CallRegisterShortProc.
663  * After return from the 16-bit relaycode, the arguments need
664  * to be copied *back* to the 32-bit stack, since the 32-bit
665  * relaycode processes output parameters.
666  * 
667  * Note that we copy twice the number of arguments, since some of the
668  * 16-bit relaycodes in SYSTHUNK.DLL directly access the original
669  * arguments of the caller!
670  *
671  * (Note that this function seems only to be used for
672  *  OLECLI32 -> OLECLI and OLESVR32 -> OLESVR thunking.)
673  */
674 void WINAPI OT_32ThkLSF( CONTEXT86 *context )
675 {
676     CONTEXT86 context16;
677     DWORD argsize;
678
679     memcpy(&context16,context,sizeof(context16));
680
681     context16.SegCs = HIWORD(context->Edx);
682     context16.Eip   = LOWORD(context->Edx);
683     context16.Ebp   = OFFSETOF( NtCurrentTeb()->cur_stack )
684                            + (WORD)&((STACK16FRAME*)0)->bp;
685
686     argsize = 2 * *(WORD *)context->Esp + 2;
687
688     memcpy( (LPBYTE)CURRENT_STACK16 - argsize,
689             (LPBYTE)context->Esp, argsize );
690
691     CallTo16RegisterShort(&context16, argsize);
692     context->Eax = context16.Eax;
693     context->Edx = context16.Edx;
694
695     /* Copy modified buffers back to 32-bit stack */
696     memcpy( (LPBYTE)context->Esp, 
697             (LPBYTE)CURRENT_STACK16 - argsize, argsize );
698
699     context->Esp +=   LOWORD(context16.Esp) -
700                         ( OFFSETOF( NtCurrentTeb()->cur_stack ) - argsize );
701 }
702
703 /***********************************************************************
704  *              ThunkInitLSF            (KERNEL32.41)
705  * A thunk setup routine.
706  * Expects a pointer to a preinitialized thunkbuffer in the first argument
707  * looking like:
708  *      00..03:         unknown (pointer, check _41, _43, _46)
709  *      04: EB1E                jmp +0x20
710  *
711  *      06..23:         unknown (space for replacement code, check .90)
712  *
713  *      24:>E800000000          call offset 29
714  *      29:>58                  pop eax            ( target of call )
715  *      2A: 2D25000000          sub eax,0x00000025 ( now points to offset 4 )
716  *      2F: BAxxxxxxxx          mov edx,xxxxxxxx
717  *      34: 68yyyyyyyy          push KERNEL32.90
718  *      39: C3                  ret
719  *
720  *      3A: EB1E                jmp +0x20
721  *      3E ... 59:      unknown (space for replacement code?)
722  *      5A: E8xxxxxxxx          call <32bitoffset xxxxxxxx>
723  *      5F: 5A                  pop edx
724  *      60: 81EA25xxxxxx        sub edx, 0x25xxxxxx
725  *      66: 52                  push edx
726  *      67: 68xxxxxxxx          push xxxxxxxx
727  *      6C: 68yyyyyyyy          push KERNEL32.89
728  *      71: C3                  ret
729  *      72: end?
730  * This function checks if the code is there, and replaces the yyyyyyyy entries
731  * by the functionpointers.
732  * The thunkbuf looks like:
733  *
734  *      00: DWORD       length          ? don't know exactly
735  *      04: SEGPTR      ptr             ? where does it point to?
736  * The segpointer ptr is written into the first DWORD of 'thunk'.
737  * [ok probably]
738  * RETURNS
739  *      unclear, pointer to win16 thkbuffer?
740  */
741 LPVOID WINAPI ThunkInitLSF(
742         LPBYTE thunk,   /* [in] win32 thunk */
743         LPCSTR thkbuf,  /* [in] thkbuffer name in win16 dll */
744         DWORD len,      /* [in] length of thkbuffer */
745         LPCSTR dll16,   /* [in] name of win16 dll */
746         LPCSTR dll32    /* [in] name of win32 dll */
747 ) {
748         HMODULE hkrnl32 = GetModuleHandleA("KERNEL32");
749         LPDWORD         addr,addr2;
750
751         /* FIXME: add checks for valid code ... */
752         /* write pointers to kernel32.89 and kernel32.90 (+ordinal base of 1) */
753         *(DWORD*)(thunk+0x35) = (DWORD)GetProcAddress(hkrnl32,(LPSTR)90);
754         *(DWORD*)(thunk+0x6D) = (DWORD)GetProcAddress(hkrnl32,(LPSTR)89);
755
756         
757         if (!(addr = _loadthunk( dll16, thkbuf, dll32, NULL, len )))
758                 return 0;
759
760         addr2 = PTR_SEG_TO_LIN(addr[1]);
761         if (HIWORD(addr2))
762                 *(DWORD*)thunk = (DWORD)addr2;
763
764         return addr2;
765 }
766
767 /***********************************************************************
768  *              FT_PrologPrime                  (KERNEL32.89)
769  * 
770  * This function is called from the relay code installed by
771  * ThunkInitLSF. It replaces the location from where it was 
772  * called by a standard FT_Prolog call stub (which is 'primed'
773  * by inserting the correct target table pointer).
774  * Finally, it calls that stub.
775  * 
776  * Input:  ECX    target number + flags (passed through to FT_Prolog)
777  *        (ESP)   offset of location where target table pointer 
778  *                is stored, relative to the start of the relay code
779  *        (ESP+4) pointer to start of relay code
780  *                (this is where the FT_Prolog call stub gets written to)
781  * 
782  * Note: The two DWORD arguments get popped off the stack.
783  *        
784  */
785 void WINAPI FT_PrologPrime( CONTEXT86 *context )
786 {
787     DWORD  targetTableOffset;
788     LPBYTE relayCode;
789
790     /* Compensate for the fact that the Wine register relay code thought
791        we were being called, although we were in fact jumped to */
792     context->Esp -= 4;
793
794     /* Write FT_Prolog call stub */
795     targetTableOffset = stack32_pop(context);
796     relayCode = (LPBYTE)stack32_pop(context);
797     _write_ftprolog( relayCode, *(DWORD **)(relayCode+targetTableOffset) );
798
799     /* Jump to the call stub just created */
800     context->Eip = (DWORD)relayCode;
801 }
802
803 /***********************************************************************
804  *              QT_ThunkPrime                   (KERNEL32.90)
805  *
806  * This function corresponds to FT_PrologPrime, but installs a 
807  * call stub for QT_Thunk instead.
808  *
809  * Input: (EBP-4) target number (passed through to QT_Thunk)
810  *         EDX    target table pointer location offset
811  *         EAX    start of relay code
812  *      
813  */
814 void WINAPI QT_ThunkPrime( CONTEXT86 *context )
815 {
816     DWORD  targetTableOffset;
817     LPBYTE relayCode;
818
819     /* Compensate for the fact that the Wine register relay code thought
820        we were being called, although we were in fact jumped to */
821     context->Esp -= 4;
822
823     /* Write QT_Thunk call stub */
824     targetTableOffset = context->Edx;
825     relayCode = (LPBYTE)context->Eax;
826     _write_qtthunk( relayCode, *(DWORD **)(relayCode+targetTableOffset) );
827
828     /* Jump to the call stub just created */
829     context->Eip = (DWORD)relayCode;
830 }
831
832 /***********************************************************************
833  *              ThunkInitSL (KERNEL32.46)
834  * Another thunkbuf link routine.
835  * The start of the thunkbuf looks like this:
836  *      00: DWORD       length
837  *      04: SEGPTR      address for thunkbuffer pointer
838  * [ok probably]
839  */
840 VOID WINAPI ThunkInitSL(
841         LPBYTE thunk,           /* [in] start of thunkbuffer */
842         LPCSTR thkbuf,          /* [in] name/ordinal of thunkbuffer in win16 dll */
843         DWORD len,              /* [in] length of thunkbuffer */
844         LPCSTR dll16,           /* [in] name of win16 dll containing the thkbuf */
845         LPCSTR dll32            /* [in] win32 dll. FIXME: strange, unused */
846 ) {
847         LPDWORD         addr;
848
849         if (!(addr = _loadthunk( dll16, thkbuf, dll32, NULL, len )))
850                 return;
851
852         *(DWORD*)PTR_SEG_TO_LIN(addr[1]) = (DWORD)thunk;
853 }
854
855 /**********************************************************************
856  *           SSInit             KERNEL.700
857  * RETURNS
858  *      TRUE for success.
859  */
860 BOOL WINAPI SSInit16()
861 {
862     return TRUE;
863 }
864
865 /**********************************************************************
866  *           SSOnBigStack       KERNEL32.87
867  * Check if thunking is initialized (ss selector set up etc.)
868  * We do that differently, so just return TRUE.
869  * [ok]
870  * RETURNS
871  *      TRUE for success.
872  */
873 BOOL WINAPI SSOnBigStack()
874 {
875     TRACE("Yes, thunking is initialized\n");
876     return TRUE;
877 }
878
879 /**********************************************************************
880  *           SSConfirmSmallStack     KERNEL.704
881  *
882  * Abort if not on small stack.
883  *
884  * This must be a register routine as it has to preserve *all* registers.
885  */
886 void WINAPI SSConfirmSmallStack( CONTEXT86 *context )
887 {
888     /* We are always on the small stack while in 16-bit code ... */
889 }
890
891 /**********************************************************************
892  *           SSCall
893  * One of the real thunking functions. This one seems to be for 32<->32
894  * thunks. It should probably be capable of crossing processboundaries.
895  *
896  * And YES, I've seen nr=48 (somewhere in the Win95 32<->16 OLE coupling)
897  * [ok]
898  */
899 DWORD WINAPIV SSCall(
900         DWORD nr,       /* [in] number of argument bytes */
901         DWORD flags,    /* [in] FIXME: flags ? */
902         FARPROC fun,    /* [in] function to call */
903         ...             /* [in/out] arguments */
904 ) {
905     DWORD i,ret;
906     DWORD *args = ((DWORD *)&fun) + 1;
907
908     if(TRACE_ON(thunk))
909     {
910       DPRINTF("(%ld,0x%08lx,%p,[",nr,flags,fun);
911       for (i=0;i<nr/4;i++) 
912           DPRINTF("0x%08lx,",args[i]);
913       DPRINTF("])\n");
914     }
915     switch (nr) {
916     case 0:     ret = fun();
917                 break;
918     case 4:     ret = fun(args[0]);
919                 break;
920     case 8:     ret = fun(args[0],args[1]);
921                 break;
922     case 12:    ret = fun(args[0],args[1],args[2]);
923                 break;
924     case 16:    ret = fun(args[0],args[1],args[2],args[3]);
925                 break;
926     case 20:    ret = fun(args[0],args[1],args[2],args[3],args[4]);
927                 break;
928     case 24:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5]);
929                 break;
930     case 28:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5],args[6]);
931                 break;
932     case 32:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7]);
933                 break;
934     case 36:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]);
935                 break;
936     case 40:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9]);
937                 break;
938     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]);
939                 break;
940     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]);
941                 break;
942     default:
943         WARN("Unsupported nr of arguments, %ld\n",nr);
944         ret = 0;
945         break;
946
947     }
948     TRACE(" returning %ld ...\n",ret);
949     return ret;
950 }
951
952 /**********************************************************************
953  *           W32S_BackTo32                      (KERNEL32.51)
954  */
955 void WINAPI W32S_BackTo32( CONTEXT86 *context )
956 {
957     LPDWORD stack = (LPDWORD)context->Esp;
958     FARPROC proc = (FARPROC)context->Eip;
959
960     context->Eax = proc( stack[1], stack[2], stack[3], stack[4], stack[5],
961                                stack[6], stack[7], stack[8], stack[9], stack[10] );
962
963     context->Eip = stack32_pop(context);
964 }
965
966 /**********************************************************************
967  *                      AllocSLCallback         (KERNEL32)
968  *
969  * Win95 uses some structchains for callbacks. It allocates them
970  * in blocks of 100 entries, size 32 bytes each, layout:
971  * blockstart:
972  *      0:      PTR     nextblockstart
973  *      4:      entry   *first;
974  *      8:      WORD    sel ( start points to blockstart)
975  *      A:      WORD    unknown
976  * 100xentry:
977  *      00..17:         Code
978  *      18:     PDB     *owning_process;
979  *      1C:     PTR     blockstart
980  *
981  * We ignore this for now. (Just a note for further developers)
982  * FIXME: use this method, so we don't waste selectors...
983  *
984  * Following code is then generated by AllocSLCallback. The code is 16 bit, so
985  * the 0x66 prefix switches from word->long registers.
986  *
987  *      665A            pop     edx 
988  *      6668x arg2 x    pushl   <arg2>
989  *      6652            push    edx
990  *      EAx arg1 x      jmpf    <arg1>
991  *
992  * returns the startaddress of this thunk.
993  *
994  * Note, that they look very similair to the ones allocates by THUNK_Alloc.
995  * RETURNS
996  *      segmented pointer to the start of the thunk
997  */
998 DWORD WINAPI
999 AllocSLCallback(
1000         DWORD finalizer,        /* [in] finalizer function */
1001         DWORD callback          /* [in] callback function */
1002 ) {
1003         LPBYTE  x,thunk = HeapAlloc( GetProcessHeap(), 0, 32 );
1004         WORD    sel;
1005
1006         x=thunk;
1007         *x++=0x66;*x++=0x5a;                            /* popl edx */
1008         *x++=0x66;*x++=0x68;*(DWORD*)x=finalizer;x+=4;  /* pushl finalizer */
1009         *x++=0x66;*x++=0x52;                            /* pushl edx */
1010         *x++=0xea;*(DWORD*)x=callback;x+=4;             /* jmpf callback */
1011
1012         *(DWORD*)(thunk+18) = GetCurrentProcessId();
1013
1014         sel = SELECTOR_AllocBlock( thunk, 32, WINE_LDT_FLAGS_CODE );
1015         return (sel<<16)|0;
1016 }
1017
1018 /**********************************************************************
1019  *              FreeSLCallback          (KERNEL32.274)
1020  * Frees the specified 16->32 callback
1021  */
1022 void WINAPI
1023 FreeSLCallback(
1024         DWORD x /* [in] 16 bit callback (segmented pointer?) */
1025 ) {
1026         FIXME("(0x%08lx): stub\n",x);
1027 }
1028
1029
1030 /**********************************************************************
1031  *              GetTEBSelectorFS        (KERNEL.475)
1032  *      Set the 16-bit %fs to the 32-bit %fs (current TEB selector)
1033  */
1034 void WINAPI GetTEBSelectorFS16(void) 
1035 {
1036     CURRENT_STACK16->fs = __get_fs();
1037 }
1038
1039 /**********************************************************************
1040  *              KERNEL_431              (KERNEL.431)
1041  * Checks the passed filename if it is a PE format executeable
1042  * RETURNS
1043  *  TRUE, if it is.
1044  *  FALSE if not.
1045  */
1046 BOOL16 WINAPI IsPeFormat16(
1047         LPSTR   fn,     /* [in] filename to executeable */
1048         HFILE16 hf16    /* [in] open file, if filename is NULL */
1049 ) {
1050     BOOL ret = FALSE;
1051     IMAGE_DOS_HEADER mzh;
1052     OFSTRUCT ofs;
1053     DWORD xmagic;
1054
1055     if (fn) hf16 = OpenFile16(fn,&ofs,OF_READ);
1056     if (hf16 == HFILE_ERROR16) return FALSE;
1057     _llseek16(hf16,0,SEEK_SET);
1058     if (sizeof(mzh)!=_lread16(hf16,&mzh,sizeof(mzh))) goto done;
1059     if (mzh.e_magic!=IMAGE_DOS_SIGNATURE) goto done;
1060     _llseek16(hf16,mzh.e_lfanew,SEEK_SET);
1061     if (sizeof(DWORD)!=_lread16(hf16,&xmagic,sizeof(DWORD))) goto done;
1062     ret = (xmagic == IMAGE_NT_SIGNATURE);
1063  done:
1064     _lclose16(hf16);
1065     return ret;
1066 }
1067
1068
1069 /***********************************************************************
1070  *           K32Thk1632Prolog                   (KERNEL32.492)
1071  */
1072 void WINAPI K32Thk1632Prolog( CONTEXT86 *context )
1073 {
1074    LPBYTE code = (LPBYTE)context->Eip - 5;
1075
1076    /* Arrrgh! SYSTHUNK.DLL just has to re-implement another method
1077       of 16->32 thunks instead of using one of the standard methods!
1078       This means that SYSTHUNK.DLL itself switches to a 32-bit stack,
1079       and does a far call to the 32-bit code segment of OLECLI32/OLESVR32.
1080       Unfortunately, our CallTo/CallFrom mechanism is therefore completely
1081       bypassed, which means it will crash the next time the 32-bit OLE 
1082       code thunks down again to 16-bit (this *will* happen!).
1083
1084       The following hack tries to recognize this situation.
1085       This is possible since the called stubs in OLECLI32/OLESVR32 all
1086       look exactly the same:
1087         00   E8xxxxxxxx    call K32Thk1632Prolog
1088         05   FF55FC        call [ebp-04]
1089         08   E8xxxxxxxx    call K32Thk1632Epilog
1090         0D   66CB          retf
1091
1092       If we recognize this situation, we try to simulate the actions
1093       of our CallTo/CallFrom mechanism by copying the 16-bit stack
1094       to our 32-bit stack, creating a proper STACK16FRAME and 
1095       updating cur_stack. */ 
1096
1097    if (   code[5] == 0xFF && code[6] == 0x55 && code[7] == 0xFC
1098        && code[13] == 0x66 && code[14] == 0xCB)
1099    {
1100       WORD  stackSel  = NtCurrentTeb()->stack_sel;
1101       DWORD stackBase = GetSelectorBase(stackSel);
1102
1103       DWORD argSize = context->Ebp - context->Esp;
1104       char *stack16 = (char *)context->Esp - 4;
1105       char *stack32 = (char *)NtCurrentTeb()->cur_stack - argSize;
1106       STACK16FRAME *frame16 = (STACK16FRAME *)stack16 - 1;
1107
1108       TRACE("before SYSTHUNK hack: EBP: %08lx ESP: %08lx cur_stack: %08lx\n",
1109                    context->Ebp, context->Esp, NtCurrentTeb()->cur_stack);
1110
1111       memset(frame16, '\0', sizeof(STACK16FRAME));
1112       frame16->frame32 = (STACK32FRAME *)NtCurrentTeb()->cur_stack;
1113       frame16->ebp = context->Ebp;
1114
1115       memcpy(stack32, stack16, argSize);
1116       NtCurrentTeb()->cur_stack = PTR_SEG_OFF_TO_SEGPTR(stackSel, (DWORD)frame16 - stackBase);
1117
1118       context->Esp = (DWORD)stack32 + 4;
1119       context->Ebp = context->Esp + argSize;
1120
1121       TRACE("after  SYSTHUNK hack: EBP: %08lx ESP: %08lx cur_stack: %08lx\n",
1122                    context->Ebp, context->Esp, NtCurrentTeb()->cur_stack);
1123    }
1124
1125     /* entry_point is never used again once the entry point has
1126        been called.  Thus we re-use it to hold the Win16Lock count */
1127    ReleaseThunkLock(&CURRENT_STACK16->entry_point);
1128 }
1129
1130 /***********************************************************************
1131  *           K32Thk1632Epilog                   (KERNEL32.491)
1132  */
1133 void WINAPI K32Thk1632Epilog( CONTEXT86 *context )
1134 {
1135    LPBYTE code = (LPBYTE)context->Eip - 13;
1136
1137    RestoreThunkLock(CURRENT_STACK16->entry_point);
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 = context->Esp - (DWORD)stack32;
1150
1151       TRACE("before SYSTHUNK hack: EBP: %08lx ESP: %08lx cur_stack: %08lx\n",
1152                    context->Ebp, context->Esp, NtCurrentTeb()->cur_stack);
1153
1154       NtCurrentTeb()->cur_stack = (DWORD)frame16->frame32;
1155
1156       context->Esp = (DWORD)stack16 + nArgsPopped;
1157       context->Ebp = frame16->ebp;
1158
1159       TRACE("after  SYSTHUNK hack: EBP: %08lx ESP: %08lx cur_stack: %08lx\n",
1160                    context->Ebp, context->Esp, 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(context->Eax), 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:__wine_call_from_16_thunk
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)++ = context->Edx;
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)__wine_call_from_16_thunk;
1309                               *((WORD *)x)++ = cs;
1310
1311     /* Jump to the stub code just created */
1312     context->Eip = LOWORD(context->Eax);
1313     context->SegCs  = HIWORD(context->Eax);
1314
1315     /* Since C16ThkSL got called by a jmp, we need to leave the
1316        original return address on the stack */
1317     context->Esp -= 4;
1318 }
1319
1320 /***********************************************************************
1321  *           C16ThkSL01                         (KERNEL.631)
1322  */
1323
1324 void WINAPI C16ThkSL01(CONTEXT86 *context)
1325 {
1326     LPBYTE stub = PTR_SEG_TO_LIN(context->Eax), x = stub;
1327
1328     if (stub)
1329     {
1330         struct ThunkDataSL16 *SL16 = PTR_SEG_TO_LIN(context->Edx);
1331         struct ThunkDataSL *td = SL16->fpData;
1332
1333         DWORD procAddress = (DWORD)GetProcAddress16(GetModuleHandle16("KERNEL"), (LPCSTR)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:__wine_call_from_16_thunk
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)__wine_call_from_16_thunk;
1366                                   *((WORD *)x)++ = cs;
1367
1368         /* Jump to the stub code just created */
1369         context->Eip = LOWORD(context->Eax);
1370         context->SegCs  = HIWORD(context->Eax);
1371
1372         /* Since C16ThkSL01 got called by a jmp, we need to leave the
1373            orginal return address on the stack */
1374         context->Esp -= 4;
1375     }
1376     else
1377     {
1378         struct ThunkDataSL *td = (struct ThunkDataSL *)context->Edx;
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             context->Edx = tdb->targetTable[targetNr];
1402
1403             TRACE("Call target is %08lx\n", context->Edx);
1404         }
1405         else
1406         {
1407             WORD *stack = PTR_SEG_OFF_TO_LIN(context->SegSs, LOWORD(context->Esp));
1408             DX_reg(context) = HIWORD(td->apiDB[targetNr].errorReturnValue);
1409             AX_reg(context) = LOWORD(td->apiDB[targetNr].errorReturnValue);
1410             context->Eip = stack[2];
1411             context->SegCs  = stack[3];
1412             context->Esp += 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)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] = context->SegDs;
1792
1793     context->Ebp = OFFSETOF( stackSeg ) + 6;
1794     context->Esp = OFFSETOF( stackSeg ) - 4;
1795     context->SegGs = 0;
1796
1797     /* Jump to 16-bit relay code */
1798     glueTab = PTR_SEG_TO_LIN( CBClientRelay16[ stackLin[5] ] );
1799     glue = glueTab[ stackLin[4] ];
1800     context->SegCs = SELECTOROF( glue );
1801     context->Eip   = 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( context->SegSs, BP_reg( context ) );
1813     FARPROC proc = CBClientRelay32[ args[2] ][ args[1] ];
1814
1815     context->Eax = CALL32_CBClient( proc, args, &context->Esi );
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( context->SegSs, BP_reg( context ) );
1827     FARPROC proc = CBClientRelay32[ args[2] ][ args[1] ];
1828     INT nArgs;
1829     LPWORD stackLin;
1830
1831     context->Eax = CALL32_CBClientEx( proc, args, &context->Esi, &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     context->SegDs = stackLin[0];
1839     context->Esp += 16+nArgs;
1840
1841     /* Return to caller of CBClient thunklet */
1842     context->SegCs = stackLin[9];
1843     context->Eip   = 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)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 (context->Eax)
1899         MESSAGE( "*** Unimplemented Win32 API: %s\n", (LPSTR)context->Eax );
1900
1901     switch ((context->Ecx >> 4) & 0x0f)
1902     {
1903     case 15:  context->Eax = -1;   break;
1904     case 14:  context->Eax = 0x78; break;
1905     case 13:  context->Eax = 0x32; break;
1906     case 1:   context->Eax = 1;    break;
1907     default:  context->Eax = 0;    break;
1908     }
1909
1910     context->Esp += (context->Ecx & 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(context->Eip);
1966     lpbuf[1] = context->SegCs;
1967     /* Windows pushes 4 more words before saving sp */
1968     lpbuf[2] = LOWORD(context->Esp) - 4 * sizeof(WORD);
1969     lpbuf[3] = LOWORD(context->Ebp);
1970     lpbuf[4] = LOWORD(context->Esi);
1971     lpbuf[5] = LOWORD(context->Edi);
1972     lpbuf[6] = context->SegDs;
1973     lpbuf[7] = 0;
1974     lpbuf[8] = context->SegSs;
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     context->Eip = lpbuf[0];
2010     context->SegCs  = lpbuf[1];
2011     context->Esp = lpbuf[2] + 4 * sizeof(WORD) - sizeof(WORD) /*extra arg*/;
2012     context->Ebp = lpbuf[3];
2013     context->Esi = lpbuf[4];
2014     context->Edi = lpbuf[5];
2015     context->SegDs  = lpbuf[6];
2016
2017     if (lpbuf[8] != context->SegSs)
2018         ERR("Switching stack segment with Throw() not supported; expect crash now\n" );
2019 }