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