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