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