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