Merged msacm and msacm32 dlls.
[wine] / if1632 / thunk.c
1 /*
2  * Emulator thunks
3  *
4  * Copyright 1996, 1997 Alexandre Julliard
5  * Copyright 1998       Ulrich Weigand
6  */
7
8 #include <string.h>
9 #include "wine/winbase16.h"
10 #include "task.h"
11 #include "hook.h"
12 #include "callback.h"
13 #include "builtin16.h"
14 #include "heap.h"
15 #include "neexe.h"
16 #include "process.h"
17 #include "stackframe.h"
18 #include "win.h"
19 #include "flatthunk.h"
20 #include "selectors.h"
21 #include "keyboard.h"
22 #include "debugtools.h"
23
24 DEFAULT_DEBUG_CHANNEL(thunk)
25
26
27 /* List of the 16-bit callback functions. This list is used  */
28 /* by the build program to generate the file if1632/callto16.S */
29
30 /* ### start build ### */
31 extern WORD CALLBACK THUNK_CallTo16_word_     (FARPROC16);
32 extern WORD CALLBACK THUNK_CallTo16_word_w    (FARPROC16,WORD);
33 extern WORD CALLBACK THUNK_CallTo16_word_l    (FARPROC16,LONG);
34 extern LONG CALLBACK THUNK_CallTo16_long_l    (FARPROC16,LONG);
35 extern WORD CALLBACK THUNK_CallTo16_word_ww   (FARPROC16,WORD,WORD);
36 extern LONG CALLBACK THUNK_CallTo16_long_ll   (FARPROC16,LONG,LONG);
37 extern WORD CALLBACK THUNK_CallTo16_word_www  (FARPROC16,WORD,WORD,WORD);
38 extern WORD CALLBACK THUNK_CallTo16_word_lllw (FARPROC16,LONG,LONG,LONG,WORD);
39 extern WORD CALLBACK THUNK_CallTo16_word_lwww (FARPROC16,LONG,WORD,WORD,WORD);
40 extern WORD CALLBACK THUNK_CallTo16_word_wlww (FARPROC16,WORD,LONG,WORD,WORD);
41 extern WORD CALLBACK THUNK_CallTo16_word_wwwl (FARPROC16,WORD,WORD,WORD,LONG);
42 extern LONG CALLBACK THUNK_CallTo16_long_wwwl (FARPROC16,WORD,WORD,WORD,LONG);
43 extern WORD CALLBACK THUNK_CallTo16_word_lwwww(FARPROC16,LONG,WORD,WORD,WORD,WORD);
44 /* ### stop build ### */
45
46 static THUNK *firstThunk = NULL;
47
48 static BOOL THUNK_ThunkletInit( void );
49
50 /* Callbacks function table for the emulator */
51 static const CALLBACKS_TABLE CALLBACK_EmulatorTable =
52 {
53     (void *)CallTo16RegisterShort,               /* CallRegisterShortProc */
54     (void *)CallTo16RegisterLong,                /* CallRegisterLongProc */
55     (void *)THUNK_CallTo16_word_w,               /* CallWindowsExitProc */
56     (void *)THUNK_CallTo16_word_lwww,            /* CallWordBreakProc */
57     (void *)THUNK_CallTo16_word_ww,              /* CallBootAppProc */
58     (void *)THUNK_CallTo16_word_www,             /* CallLoadAppSegProc */
59     (void *)THUNK_CallTo16_word_www,             /* CallLocalNotifyFunc */
60     (void *)THUNK_CallTo16_word_www,             /* CallResourceHandlerProc */
61     (void *)THUNK_CallTo16_long_ll,              /* CallUTProc */
62     (void *)THUNK_CallTo16_long_l                /* CallASPIPostProc */
63 };
64
65 const CALLBACKS_TABLE *Callbacks = &CALLBACK_EmulatorTable;
66
67 CALLOUT_TABLE Callout = { 0 };
68
69
70 /***********************************************************************
71  *           THUNK_Init
72  */
73 BOOL THUNK_Init(void)
74 {
75     /* Initialize Thunklets */
76     return THUNK_ThunkletInit();
77 }
78
79 /***********************************************************************
80  *           THUNK_Alloc
81  */
82 FARPROC THUNK_Alloc( FARPROC16 func, RELAY relay )
83 {
84     HANDLE16 hSeg;
85     NE_MODULE *pModule;
86     THUNK *thunk;
87
88     /* NULL maps to NULL */
89     if ( !func ) return NULL;
90
91     /* 
92      * If we got an 16-bit built-in API entry point, retrieve the Wine
93      * 32-bit handler for that API routine.
94      *
95      * NOTE: For efficiency reasons, we only check whether the selector
96      *       of 'func' points to the code segment of a built-in module.
97      *       It might be theoretically possible that the offset is such
98      *       that 'func' does not point, in fact, to an API entry point.
99      *       In this case, however, the pointer is corrupt anyway.
100      */
101     hSeg = GlobalHandle16( SELECTOROF( func ) );
102     pModule = NE_GetPtr( FarGetOwner16( hSeg ) );
103
104     if ( pModule && (pModule->flags & NE_FFLAGS_BUILTIN) 
105                  && NE_SEG_TABLE(pModule)[0].hSeg == hSeg )
106     {
107         FARPROC proc = (FARPROC)((ENTRYPOINT16 *)PTR_SEG_TO_LIN( func ))->target;
108
109         TRACE( "(%04x:%04x, %p) -> built-in API %p\n",
110                SELECTOROF( func ), OFFSETOF( func ), relay, proc );
111         return proc;
112     }
113
114     /* Otherwise, we need to alloc a thunk */
115     thunk = HeapAlloc( GetProcessHeap(), 0, sizeof(*thunk) );
116     if (thunk)
117     {
118         thunk->popl_eax   = 0x58;
119         thunk->pushl_func = 0x68;
120         thunk->proc       = func;
121         thunk->pushl_eax  = 0x50;
122         thunk->jmp        = 0xe9;
123         thunk->relay      = (RELAY)((char *)relay - (char *)(&thunk->next));
124         thunk->magic      = CALLTO16_THUNK_MAGIC;
125         thunk->next       = firstThunk;
126         firstThunk = thunk;
127     }
128
129     TRACE( "(%04x:%04x, %p) -> allocated thunk %p\n",
130            SELECTOROF( func ), OFFSETOF( func ), relay, thunk );
131     return (FARPROC)thunk;
132 }
133
134 /***********************************************************************
135  *           THUNK_Free
136  */
137 void THUNK_Free( FARPROC thunk )
138 {
139     THUNK *t = (THUNK*)thunk;
140     if ( !t || IsBadReadPtr( t, sizeof(*t) ) 
141             || t->magic != CALLTO16_THUNK_MAGIC )
142          return;
143
144     if (HEAP_IsInsideHeap( GetProcessHeap(), 0, t ))
145     {
146         THUNK **prev = &firstThunk;
147         while (*prev && (*prev != t)) prev = &(*prev)->next;
148         if (*prev)
149         {
150             *prev = t->next;
151             HeapFree( GetProcessHeap(), 0, t );
152             return;
153         }
154     }
155     ERR("invalid thunk addr %p\n", thunk );
156     return;
157 }
158
159
160 /***********************************************************************
161  *           THUNK_GetCalloutThunk
162  *
163  * Retrieve API entry point with given name from given module.
164  * If module is builtin, return the 32-bit entry point, otherwise
165  * create a 32->16 thunk to the 16-bit entry point, using the 
166  * given relay code.
167  *
168  */
169 static FARPROC THUNK_GetCalloutThunk( NE_MODULE *pModule, LPSTR name, RELAY relay )
170 {
171     FARPROC16 proc = WIN32_GetProcAddress16( pModule->self, name );
172     if ( !proc ) return 0;
173
174     if ( pModule->flags & NE_FFLAGS_BUILTIN )
175         return (FARPROC)((ENTRYPOINT16 *)PTR_SEG_TO_LIN( proc ))->target;
176     else
177         return (FARPROC)THUNK_Alloc( proc, relay );
178 }
179
180 /***********************************************************************
181  *           THUNK_InitCallout
182  */
183 void THUNK_InitCallout(void)
184 {
185     HMODULE hModule;
186     NE_MODULE *pModule;
187
188     hModule = GetModuleHandleA( "USER32" );
189     if ( hModule )
190     {
191 #define GETADDR( name )  \
192         *(FARPROC *)&Callout.##name = GetProcAddress( hModule, #name )
193
194         GETADDR( PeekMessageA );
195         GETADDR( PeekMessageW );
196         GETADDR( GetMessageA );
197         GETADDR( GetMessageW );
198         GETADDR( SendMessageA );
199         GETADDR( SendMessageW );
200         GETADDR( PostMessageA );
201         GETADDR( PostMessageW );
202         GETADDR( PostThreadMessageA );
203         GETADDR( PostThreadMessageW );
204         GETADDR( TranslateMessage );
205         GETADDR( DispatchMessageW );
206         GETADDR( DispatchMessageA );
207         GETADDR( RedrawWindow );
208         GETADDR( WaitForInputIdle );
209         GETADDR( MessageBoxA );
210         GETADDR( MessageBoxW );
211 #undef GETADDR
212     }
213
214     pModule = NE_GetPtr( GetModuleHandle16( "USER" ) );
215     if ( pModule )
216     {
217 #define GETADDR( var, name, thk )  \
218         *(FARPROC *)&Callout.##var = THUNK_GetCalloutThunk( pModule, name, \
219                                                  (RELAY)THUNK_CallTo16_##thk )
220
221         GETADDR( PeekMessage16, "PeekMessage", word_lwwww );
222         GETADDR( GetMessage16, "GetMessage", word_lwww );
223         GETADDR( SendMessage16, "SendMessage", long_wwwl );
224         GETADDR( PostMessage16, "PostMessage", word_wwwl );
225         GETADDR( PostAppMessage16, "PostAppMessage", word_wwwl );
226         GETADDR( TranslateMessage16, "TranslateMessage", word_l );
227         GETADDR( DispatchMessage16, "DispatchMessage", long_l );
228         GETADDR( RedrawWindow16, "RedrawWindow", word_wlww );
229         GETADDR( FinalUserInit16, "FinalUserInit", word_ );
230         GETADDR( InitApp16, "InitApp", word_w );
231         GETADDR( InitThreadInput16, "InitThreadInput", word_ww );
232         GETADDR( UserYield16, "UserYield", word_ );
233         GETADDR( DestroyIcon32, "DestroyIcon32", word_ww );
234         GETADDR( UserSignalProc, "SignalProc32", word_lllw );
235
236 #undef GETADDR
237     }
238 }
239
240 /***********************************************************************
241  * 16->32 Flat Thunk routines:
242  */
243
244 /***********************************************************************
245  *              ThunkConnect16          (KERNEL.651)
246  * Connects a 32bit and a 16bit thunkbuffer.
247  */
248 UINT WINAPI ThunkConnect16(
249         LPSTR module16,              /* [in] name of win16 dll */
250         LPSTR module32,              /* [in] name of win32 dll */
251         HINSTANCE16 hInst16,         /* [in] hInst of win16 dll */
252         DWORD dwReason,              /* [in] initialisation argument */
253         struct ThunkDataCommon *TD,  /* [in/out] thunkbuffer */
254         LPSTR thunkfun32,            /* [in] win32 thunkfunction */
255         WORD cs                      /* [in] CS of win16 dll */
256 ) {
257     BOOL directionSL;
258
259     if (!strncmp(TD->magic, "SL01", 4))
260     {
261         directionSL = TRUE;
262
263         TRACE("SL01 thunk %s (%lx) -> %s (%s), Reason: %ld\n",
264               module16, (DWORD)TD, module32, thunkfun32, dwReason);
265     }
266     else if (!strncmp(TD->magic, "LS01", 4))
267     {
268         directionSL = FALSE;
269
270         TRACE("LS01 thunk %s (%lx) <- %s (%s), Reason: %ld\n",
271               module16, (DWORD)TD, module32, thunkfun32, dwReason);
272     }
273     else
274     {
275         ERR("Invalid magic %c%c%c%c\n",
276             TD->magic[0], TD->magic[1], TD->magic[2], TD->magic[3]);
277         return 0;
278     }
279
280     switch (dwReason)
281     {
282         case DLL_PROCESS_ATTACH:
283             if (directionSL)
284             {
285                 struct ThunkDataSL16 *SL16 = (struct ThunkDataSL16 *)TD;
286                 struct ThunkDataSL   *SL   = SL16->fpData;
287
288                 if (SL == NULL)
289                 {
290                     SL = HeapAlloc(GetProcessHeap(), 0, sizeof(*SL));
291
292                     SL->common   = SL16->common;
293                     SL->flags1   = SL16->flags1;
294                     SL->flags2   = SL16->flags2;
295
296                     SL->apiDB    = PTR_SEG_TO_LIN(SL16->apiDatabase);
297                     SL->targetDB = NULL;
298
299                     lstrcpynA(SL->pszDll16, module16, 255);
300                     lstrcpynA(SL->pszDll32, module32, 255);
301
302                     /* We should create a SEGPTR to the ThunkDataSL,
303                        but since the contents are not in the original format,
304                        any access to this by 16-bit code would crash anyway. */
305                     SL16->spData = 0;
306                     SL16->fpData = SL;
307                 }
308
309
310                 if (SL->flags2 & 0x80000000)
311                 {
312                     TRACE("Preloading 32-bit library\n");
313                     LoadLibraryA(module32);
314                 }
315             }
316             else
317             {
318                 /* nothing to do */
319             }
320             break;
321
322         case DLL_PROCESS_DETACH:
323             /* FIXME: cleanup */
324             break;
325     }
326
327     return 1;
328 }
329
330
331 /***********************************************************************
332  *           C16ThkSL                           (KERNEL.630)
333  */
334
335 void WINAPI C16ThkSL(CONTEXT86 *context)
336 {
337     LPBYTE stub = PTR_SEG_TO_LIN(EAX_reg(context)), x = stub;
338     WORD cs = __get_cs();
339     WORD ds = __get_ds();
340
341     /* We produce the following code:
342      *
343      *   mov ax, __FLATDS
344      *   mov es, ax
345      *   movzx ecx, cx
346      *   mov edx, es:[ecx + $EDX]
347      *   push bp
348      *   push edx
349      *   push dx
350      *   push edx
351      *   call __FLATCS:CallFrom16Thunk
352      */
353
354     *x++ = 0xB8; *((WORD *)x)++ = ds;
355     *x++ = 0x8E; *x++ = 0xC0;
356     *x++ = 0x66; *x++ = 0x0F; *x++ = 0xB7; *x++ = 0xC9;
357     *x++ = 0x67; *x++ = 0x66; *x++ = 0x26; *x++ = 0x8B;
358                  *x++ = 0x91; *((DWORD *)x)++ = EDX_reg(context);
359
360     *x++ = 0x55;
361     *x++ = 0x66; *x++ = 0x52;
362     *x++ = 0x52;
363     *x++ = 0x66; *x++ = 0x52;
364     *x++ = 0x66; *x++ = 0x9A; *((DWORD *)x)++ = (DWORD)CallFrom16Thunk;
365                               *((WORD *)x)++ = cs;
366
367     /* Jump to the stub code just created */
368     EIP_reg(context) = LOWORD(EAX_reg(context));
369     CS_reg(context)  = HIWORD(EAX_reg(context));
370
371     /* Since C16ThkSL got called by a jmp, we need to leave the
372        original return address on the stack */
373     ESP_reg(context) -= 4;
374 }
375
376 /***********************************************************************
377  *           C16ThkSL01                         (KERNEL.631)
378  */
379
380 void WINAPI C16ThkSL01(CONTEXT86 *context)
381 {
382     LPBYTE stub = PTR_SEG_TO_LIN(EAX_reg(context)), x = stub;
383
384     if (stub)
385     {
386         struct ThunkDataSL16 *SL16 = PTR_SEG_TO_LIN(EDX_reg(context));
387         struct ThunkDataSL *td = SL16->fpData;
388
389         DWORD procAddress = (DWORD)GetProcAddress16(GetModuleHandle16("KERNEL"), 631);
390         WORD cs = __get_cs();
391
392         if (!td)
393         {
394             ERR("ThunkConnect16 was not called!\n");
395             return;
396         }
397
398         TRACE("Creating stub for ThunkDataSL %08lx\n", (DWORD)td);
399
400
401         /* We produce the following code:
402          *
403          *   xor eax, eax
404          *   mov edx, $td
405          *   call C16ThkSL01
406          *   push bp
407          *   push edx
408          *   push dx
409          *   push edx
410          *   call __FLATCS:CallFrom16Thunk
411          */
412
413         *x++ = 0x66; *x++ = 0x33; *x++ = 0xC0;
414         *x++ = 0x66; *x++ = 0xBA; *((DWORD *)x)++ = (DWORD)td;
415         *x++ = 0x9A; *((DWORD *)x)++ = procAddress;
416
417         *x++ = 0x55;
418         *x++ = 0x66; *x++ = 0x52;
419         *x++ = 0x52;
420         *x++ = 0x66; *x++ = 0x52;
421         *x++ = 0x66; *x++ = 0x9A; *((DWORD *)x)++ = (DWORD)CallFrom16Thunk;
422                                   *((WORD *)x)++ = cs;
423
424         /* Jump to the stub code just created */
425         EIP_reg(context) = LOWORD(EAX_reg(context));
426         CS_reg(context)  = HIWORD(EAX_reg(context));
427
428         /* Since C16ThkSL01 got called by a jmp, we need to leave the
429            orginal return address on the stack */
430         ESP_reg(context) -= 4;
431     }
432     else
433     {
434         struct ThunkDataSL *td = (struct ThunkDataSL *)EDX_reg(context);
435         DWORD targetNr = CX_reg(context) / 4;
436         struct SLTargetDB *tdb;
437
438         TRACE("Process %08lx calling target %ld of ThunkDataSL %08lx\n",
439               (DWORD)PROCESS_Current(), targetNr, (DWORD)td);
440
441         for (tdb = td->targetDB; tdb; tdb = tdb->next)
442             if (tdb->process == PROCESS_Current())
443                 break;
444
445         if (!tdb)
446         {
447             TRACE("Loading 32-bit library %s\n", td->pszDll32);
448             LoadLibraryA(td->pszDll32);
449
450             for (tdb = td->targetDB; tdb; tdb = tdb->next)
451                 if (tdb->process == PROCESS_Current())
452                     break;
453         }
454
455         if (tdb)
456         {
457             EDX_reg(context) = tdb->targetTable[targetNr];
458
459             TRACE("Call target is %08lx\n", EDX_reg(context));
460         }
461         else
462         {
463             WORD *stack = PTR_SEG_OFF_TO_LIN(SS_reg(context), LOWORD(ESP_reg(context)));
464             DX_reg(context) = HIWORD(td->apiDB[targetNr].errorReturnValue);
465             AX_reg(context) = LOWORD(td->apiDB[targetNr].errorReturnValue);
466             EIP_reg(context) = stack[2];
467             CS_reg(context)  = stack[3];
468             ESP_reg(context) += td->apiDB[targetNr].nrArgBytes + 4;
469
470             ERR("Process %08lx did not ThunkConnect32 %s to %s\n",
471                 (DWORD)PROCESS_Current(), td->pszDll32, td->pszDll16);
472         }
473     }
474 }
475
476
477
478 /***********************************************************************
479  * 16<->32 Thunklet/Callback API:
480  */
481
482 #include "pshpack1.h"
483 typedef struct _THUNKLET
484 {
485     BYTE        prefix_target;
486     BYTE        pushl_target;
487     DWORD       target;
488
489     BYTE        prefix_relay;
490     BYTE        pushl_relay;
491     DWORD       relay;
492
493     BYTE        jmp_glue;
494     DWORD       glue;
495
496     BYTE        type;
497     HINSTANCE16 owner;
498     struct _THUNKLET *next;
499 } THUNKLET;
500 #include "poppack.h"
501
502 #define THUNKLET_TYPE_LS  1
503 #define THUNKLET_TYPE_SL  2
504
505 static HANDLE  ThunkletHeap = 0;
506 static THUNKLET *ThunkletAnchor = NULL;
507
508 static FARPROC ThunkletSysthunkGlueLS = 0;
509 static SEGPTR    ThunkletSysthunkGlueSL = 0;
510
511 static FARPROC ThunkletCallbackGlueLS = 0;
512 static SEGPTR    ThunkletCallbackGlueSL = 0;
513
514 /***********************************************************************
515  *     THUNK_ThunkletInit
516  */
517 static BOOL THUNK_ThunkletInit( void )
518 {
519     LPBYTE thunk;
520
521     ThunkletHeap = HeapCreate(HEAP_WINE_SEGPTR | HEAP_WINE_CODE16SEG, 0, 0);
522     if (!ThunkletHeap) return FALSE;
523
524     thunk = HeapAlloc( ThunkletHeap, 0, 5 );
525     if (!thunk) return FALSE;
526     
527     ThunkletSysthunkGlueLS = (FARPROC)thunk;
528     *thunk++ = 0x58;                             /* popl eax */
529     *thunk++ = 0xC3;                             /* ret      */
530
531     ThunkletSysthunkGlueSL = HEAP_GetSegptr( ThunkletHeap, 0, thunk );
532     *thunk++ = 0x66; *thunk++ = 0x58;            /* popl eax */
533     *thunk++ = 0xCB;                             /* lret     */
534
535     return TRUE;
536 }
537
538 /***********************************************************************
539  *     SetThunkletCallbackGlue             (KERNEL.560)
540  */
541 void WINAPI SetThunkletCallbackGlue16( FARPROC glueLS, SEGPTR glueSL )
542 {
543     ThunkletCallbackGlueLS = glueLS;
544     ThunkletCallbackGlueSL = glueSL;
545 }
546
547
548 /***********************************************************************
549  *     THUNK_FindThunklet
550  */
551 THUNKLET *THUNK_FindThunklet( DWORD target, DWORD relay, 
552                               DWORD glue, BYTE type ) 
553 {
554     THUNKLET *thunk; 
555
556     for (thunk = ThunkletAnchor; thunk; thunk = thunk->next)
557         if (    thunk->type   == type
558              && thunk->target == target
559              && thunk->relay  == relay 
560              && ( type == THUNKLET_TYPE_LS ?
561                     ( thunk->glue == glue - (DWORD)&thunk->type )
562                   : ( thunk->glue == glue ) ) )
563             return thunk;
564
565      return NULL;
566 }
567
568 /***********************************************************************
569  *     THUNK_AllocLSThunklet
570  */
571 FARPROC THUNK_AllocLSThunklet( SEGPTR target, DWORD relay, 
572                                  FARPROC glue, HTASK16 owner ) 
573 {
574     THUNKLET *thunk = THUNK_FindThunklet( (DWORD)target, relay, (DWORD)glue,
575                                           THUNKLET_TYPE_LS );
576     if (!thunk)
577     {
578         TDB *pTask = (TDB*)GlobalLock16( owner );
579
580         if ( !(thunk = HeapAlloc( ThunkletHeap, 0, sizeof(THUNKLET) )) )
581             return 0;
582
583         thunk->prefix_target = thunk->prefix_relay = 0x90;
584         thunk->pushl_target  = thunk->pushl_relay  = 0x68;
585         thunk->jmp_glue = 0xE9;
586
587         thunk->target  = (DWORD)target;
588         thunk->relay   = (DWORD)relay;
589         thunk->glue    = (DWORD)glue - (DWORD)&thunk->type;
590
591         thunk->type    = THUNKLET_TYPE_LS;
592         thunk->owner   = pTask? pTask->hInstance : 0;
593
594         thunk->next    = ThunkletAnchor;
595         ThunkletAnchor = thunk;
596     }
597
598     return (FARPROC)thunk;
599 }
600
601 /***********************************************************************
602  *     THUNK_AllocSLThunklet
603  */
604 SEGPTR THUNK_AllocSLThunklet( FARPROC target, DWORD relay,
605                               SEGPTR glue, HTASK16 owner )
606 {
607     THUNKLET *thunk = THUNK_FindThunklet( (DWORD)target, relay, (DWORD)glue,
608                                           THUNKLET_TYPE_SL );
609     if (!thunk)
610     {
611         TDB *pTask = (TDB*)GlobalLock16( owner );
612
613         if ( !(thunk = HeapAlloc( ThunkletHeap, 0, sizeof(THUNKLET) )) )
614             return 0;
615
616         thunk->prefix_target = thunk->prefix_relay = 0x66;
617         thunk->pushl_target  = thunk->pushl_relay  = 0x68;
618         thunk->jmp_glue = 0xEA;
619
620         thunk->target  = (DWORD)target;
621         thunk->relay   = (DWORD)relay;
622         thunk->glue    = (DWORD)glue;
623
624         thunk->type    = THUNKLET_TYPE_SL;
625         thunk->owner   = pTask? pTask->hInstance : 0;
626
627         thunk->next    = ThunkletAnchor;
628         ThunkletAnchor = thunk;
629     }
630
631     return HEAP_GetSegptr( ThunkletHeap, 0, thunk );
632 }
633
634 /**********************************************************************
635  *     IsLSThunklet
636  */
637 BOOL16 WINAPI IsLSThunklet( THUNKLET *thunk )
638 {
639     return    thunk->prefix_target == 0x90 && thunk->pushl_target == 0x68
640            && thunk->prefix_relay  == 0x90 && thunk->pushl_relay  == 0x68
641            && thunk->jmp_glue == 0xE9 && thunk->type == THUNKLET_TYPE_LS;
642 }
643
644 /**********************************************************************
645  *     IsSLThunklet                        (KERNEL.612)
646  */
647 BOOL16 WINAPI IsSLThunklet16( THUNKLET *thunk )
648 {
649     return    thunk->prefix_target == 0x66 && thunk->pushl_target == 0x68
650            && thunk->prefix_relay  == 0x66 && thunk->pushl_relay  == 0x68
651            && thunk->jmp_glue == 0xEA && thunk->type == THUNKLET_TYPE_SL;
652 }
653
654
655
656 /***********************************************************************
657  *     AllocLSThunkletSysthunk             (KERNEL.607)
658  */
659 FARPROC WINAPI AllocLSThunkletSysthunk16( SEGPTR target, 
660                                           FARPROC relay, DWORD dummy )
661 {
662     return THUNK_AllocLSThunklet( (SEGPTR)relay, (DWORD)target, 
663                                   ThunkletSysthunkGlueLS, GetCurrentTask() );
664 }
665
666 /***********************************************************************
667  *     AllocSLThunkletSysthunk             (KERNEL.608)
668  */
669 SEGPTR WINAPI AllocSLThunkletSysthunk16( FARPROC target, 
670                                        SEGPTR relay, DWORD dummy )
671 {
672     return THUNK_AllocSLThunklet( (FARPROC)relay, (DWORD)target, 
673                                   ThunkletSysthunkGlueSL, GetCurrentTask() );
674 }
675
676
677 /***********************************************************************
678  *     AllocLSThunkletCallbackEx           (KERNEL.567)
679  */
680 FARPROC WINAPI AllocLSThunkletCallbackEx16( SEGPTR target, 
681                                             DWORD relay, HTASK16 task )
682 {
683     THUNKLET *thunk = (THUNKLET *)PTR_SEG_TO_LIN( target );
684     if ( !thunk ) return NULL;
685
686     if (   IsSLThunklet16( thunk ) && thunk->relay == relay 
687         && thunk->glue == (DWORD)ThunkletCallbackGlueSL )
688         return (FARPROC)thunk->target;
689
690     return THUNK_AllocLSThunklet( target, relay, 
691                                   ThunkletCallbackGlueLS, task );
692 }
693
694 /***********************************************************************
695  *     AllocSLThunkletCallbackEx           (KERNEL.568)
696  */
697 SEGPTR WINAPI AllocSLThunkletCallbackEx16( FARPROC target, 
698                                          DWORD relay, HTASK16 task )
699 {
700     THUNKLET *thunk = (THUNKLET *)target;
701     if ( !thunk ) return 0;
702
703     if (   IsLSThunklet( thunk ) && thunk->relay == relay 
704         && thunk->glue == (DWORD)ThunkletCallbackGlueLS - (DWORD)&thunk->type )
705         return (SEGPTR)thunk->target;
706
707     return THUNK_AllocSLThunklet( target, relay, 
708                                   ThunkletCallbackGlueSL, task );
709 }
710
711 /***********************************************************************
712  *     AllocLSThunkletCallback             (KERNEL.561) (KERNEL.606)
713  */
714 FARPROC WINAPI AllocLSThunkletCallback16( SEGPTR target, DWORD relay )
715 {
716     return AllocLSThunkletCallbackEx16( target, relay, GetCurrentTask() );
717 }
718
719 /***********************************************************************
720  *     AllocSLThunkletCallback             (KERNEL.562) (KERNEL.605)
721  */
722 SEGPTR WINAPI AllocSLThunkletCallback16( FARPROC target, DWORD relay )
723 {
724     return AllocSLThunkletCallbackEx16( target, relay, GetCurrentTask() );
725 }
726
727 /***********************************************************************
728  *     FindLSThunkletCallback              (KERNEL.563) (KERNEL.609)
729  */
730 FARPROC WINAPI FindLSThunkletCallback( SEGPTR target, DWORD relay )
731 {
732     THUNKLET *thunk = (THUNKLET *)PTR_SEG_TO_LIN( target );
733     if (   thunk && IsSLThunklet16( thunk ) && thunk->relay == relay 
734         && thunk->glue == (DWORD)ThunkletCallbackGlueSL )
735         return (FARPROC)thunk->target;
736
737     thunk = THUNK_FindThunklet( (DWORD)target, relay, 
738                                 (DWORD)ThunkletCallbackGlueLS, 
739                                 THUNKLET_TYPE_LS );
740     return (FARPROC)thunk;
741 }
742
743 /***********************************************************************
744  *     FindSLThunkletCallback              (KERNEL.564) (KERNEL.610)
745  */
746 SEGPTR WINAPI FindSLThunkletCallback( FARPROC target, DWORD relay )
747 {
748     THUNKLET *thunk = (THUNKLET *)target;
749     if (   thunk && IsLSThunklet( thunk ) && thunk->relay == relay 
750         && thunk->glue == (DWORD)ThunkletCallbackGlueLS - (DWORD)&thunk->type )
751         return (SEGPTR)thunk->target;
752
753     thunk = THUNK_FindThunklet( (DWORD)target, relay, 
754                                 (DWORD)ThunkletCallbackGlueSL, 
755                                 THUNKLET_TYPE_SL );
756     return HEAP_GetSegptr( ThunkletHeap, 0, thunk );
757 }
758
759
760 /***********************************************************************
761  *     FreeThunklet16            (KERNEL.611)
762  */
763 BOOL16 WINAPI FreeThunklet16( DWORD unused1, DWORD unused2 )
764 {
765     return FALSE;
766 }
767
768 /***********************************************************************
769  * Callback Client API
770  */
771
772 #define N_CBC_FIXED    20
773 #define N_CBC_VARIABLE 10
774 #define N_CBC_TOTAL    (N_CBC_FIXED + N_CBC_VARIABLE)
775
776 static SEGPTR CBClientRelay16[ N_CBC_TOTAL ];
777 static FARPROC *CBClientRelay32[ N_CBC_TOTAL ];
778
779 /***********************************************************************
780  *     RegisterCBClient                    (KERNEL.619)
781  */
782 INT16 WINAPI RegisterCBClient16( INT16 wCBCId, 
783                                  SEGPTR relay16, FARPROC *relay32 )
784 {
785     /* Search for free Callback ID */
786     if ( wCBCId == -1 )
787         for ( wCBCId = N_CBC_FIXED; wCBCId < N_CBC_TOTAL; wCBCId++ )
788             if ( !CBClientRelay16[ wCBCId ] )
789                 break;
790
791     /* Register Callback ID */
792     if ( wCBCId > 0 && wCBCId < N_CBC_TOTAL )
793     {
794         CBClientRelay16[ wCBCId ] = relay16;
795         CBClientRelay32[ wCBCId ] = relay32;
796     }
797     else
798         wCBCId = 0;
799
800     return wCBCId;
801 }
802
803 /***********************************************************************
804  *     UnRegisterCBClient                  (KERNEL.622)
805  */
806 INT16 WINAPI UnRegisterCBClient16( INT16 wCBCId, 
807                                    SEGPTR relay16, FARPROC *relay32 )
808 {
809     if (    wCBCId >= N_CBC_FIXED && wCBCId < N_CBC_TOTAL 
810          && CBClientRelay16[ wCBCId ] == relay16 
811          && CBClientRelay32[ wCBCId ] == relay32 )
812     {
813         CBClientRelay16[ wCBCId ] = 0;
814         CBClientRelay32[ wCBCId ] = 0;
815     }
816     else
817         wCBCId = 0;
818
819     return wCBCId;
820 }
821
822
823 /***********************************************************************
824  *     InitCBClient                        (KERNEL.623)
825  */
826 void WINAPI InitCBClient16( FARPROC glueLS )
827 {
828     HMODULE16 kernel = GetModuleHandle16( "KERNEL" );
829     SEGPTR glueSL = (SEGPTR)WIN32_GetProcAddress16( kernel, (LPCSTR)604 );
830
831     SetThunkletCallbackGlue16( glueLS, glueSL );
832 }
833
834 /***********************************************************************
835  *     CBClientGlueSL                      (KERNEL.604)
836  */
837 void WINAPI CBClientGlueSL( CONTEXT86 *context )
838 {
839     /* Create stack frame */
840     SEGPTR stackSeg = stack16_push( 12 );
841     LPWORD stackLin = PTR_SEG_TO_LIN( stackSeg );
842     SEGPTR glue, *glueTab;
843     
844     stackLin[3] = BP_reg( context );
845     stackLin[2] = SI_reg( context );
846     stackLin[1] = DI_reg( context );
847     stackLin[0] = DS_reg( context );
848
849     EBP_reg( context ) = OFFSETOF( stackSeg ) + 6;
850     ESP_reg( context ) = OFFSETOF( stackSeg ) - 4;
851     GS_reg( context ) = 0;
852
853     /* Jump to 16-bit relay code */
854     glueTab = PTR_SEG_TO_LIN( CBClientRelay16[ stackLin[5] ] );
855     glue = glueTab[ stackLin[4] ];
856     CS_reg ( context ) = SELECTOROF( glue );
857     EIP_reg( context ) = OFFSETOF  ( glue );
858 }
859
860 /***********************************************************************
861  *     CBClientThunkSL                      (KERNEL.620)
862  */
863 extern DWORD CALL32_CBClient( FARPROC proc, LPWORD args, DWORD *esi );
864 void WINAPI CBClientThunkSL( CONTEXT86 *context )
865 {
866     /* Call 32-bit relay code */
867
868     LPWORD args = PTR_SEG_OFF_TO_LIN( SS_reg( context ), BP_reg( context ) );
869     FARPROC proc = CBClientRelay32[ args[2] ][ args[1] ];
870
871     EAX_reg(context) = CALL32_CBClient( proc, args, &ESI_reg( context ) );
872 }
873
874 /***********************************************************************
875  *     CBClientThunkSLEx                    (KERNEL.621)
876  */
877 extern DWORD CALL32_CBClientEx( FARPROC proc, LPWORD args, DWORD *esi, INT *nArgs );
878 void WINAPI CBClientThunkSLEx( CONTEXT86 *context )
879 {
880     /* Call 32-bit relay code */
881
882     LPWORD args = PTR_SEG_OFF_TO_LIN( SS_reg( context ), BP_reg( context ) );
883     FARPROC proc = CBClientRelay32[ args[2] ][ args[1] ];
884     INT nArgs;
885     LPWORD stackLin;
886
887     EAX_reg(context) = CALL32_CBClientEx( proc, args, &ESI_reg( context ), &nArgs );
888
889     /* Restore registers saved by CBClientGlueSL */
890     stackLin = (LPWORD)((LPBYTE)CURRENT_STACK16 + sizeof(STACK16FRAME) - 4);
891     BP_reg( context ) = stackLin[3];
892     SI_reg( context ) = stackLin[2];
893     DI_reg( context ) = stackLin[1];
894     DS_reg( context ) = stackLin[0];
895     ESP_reg( context ) += 16+nArgs;
896
897     /* Return to caller of CBClient thunklet */
898     CS_reg ( context ) = stackLin[9];
899     EIP_reg( context ) = stackLin[8];
900 }
901