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