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