Added StackEnter() and StackLeave() stubs
[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 "wine/winuser16.h"
11 #include "hook.h"
12 #include "callback.h"
13 #include "task.h"
14 #include "user.h"
15 #include "heap.h"
16 #include "module.h"
17 #include "process.h"
18 #include "stackframe.h"
19 #include "selectors.h"
20 #include "syslevel.h"
21 #include "task.h"
22 #include "except.h"
23 #include "win.h"
24 #include "flatthunk.h"
25 #include "mouse.h"
26 #include "keyboard.h"
27 #include "debug.h"
28
29
30 /* List of the 16-bit callback functions. This list is used  */
31 /* by the build program to generate the file if1632/callto16.S */
32
33 /* ### start build ### */
34 extern LONG CALLBACK CallTo16_sreg_(const CONTEXT *context, INT offset);
35 extern LONG CALLBACK CallTo16_lreg_(const CONTEXT *context, INT offset);
36 extern WORD CALLBACK CallTo16_word_     (FARPROC16);
37 extern LONG CALLBACK CallTo16_long_     (FARPROC16);
38 extern WORD CALLBACK CallTo16_word_w    (FARPROC16,WORD);
39 extern WORD CALLBACK CallTo16_word_l    (FARPROC16,LONG);
40 extern LONG CALLBACK CallTo16_long_l    (FARPROC16,LONG);
41 extern WORD CALLBACK CallTo16_word_ww   (FARPROC16,WORD,WORD);
42 extern WORD CALLBACK CallTo16_word_wl   (FARPROC16,WORD,LONG);
43 extern WORD CALLBACK CallTo16_word_ll   (FARPROC16,LONG,LONG);
44 extern LONG CALLBACK CallTo16_long_ll   (FARPROC16,LONG,LONG);
45 extern WORD CALLBACK CallTo16_word_www  (FARPROC16,WORD,WORD,WORD);
46 extern WORD CALLBACK CallTo16_word_wwl  (FARPROC16,WORD,WORD,LONG);
47 extern WORD CALLBACK CallTo16_word_wlw  (FARPROC16,WORD,LONG,WORD);
48 extern LONG CALLBACK CallTo16_long_wwl  (FARPROC16,WORD,WORD,LONG);
49 extern LONG CALLBACK CallTo16_long_lll  (FARPROC16,LONG,LONG,LONG);
50 extern WORD CALLBACK CallTo16_word_llwl (FARPROC16,LONG,LONG,WORD,LONG);
51 extern WORD CALLBACK CallTo16_word_lwll (FARPROC16,LONG,WORD,LONG,LONG);
52 extern WORD CALLBACK CallTo16_word_lwww (FARPROC16,LONG,WORD,WORD,WORD);
53 extern WORD CALLBACK CallTo16_word_wlww (FARPROC16,WORD,LONG,WORD,WORD);
54 extern WORD CALLBACK CallTo16_word_wwll (FARPROC16,WORD,WORD,LONG,LONG);
55 extern WORD CALLBACK CallTo16_word_wwwl (FARPROC16,WORD,WORD,WORD,LONG);
56 extern LONG CALLBACK CallTo16_long_wwwl (FARPROC16,WORD,WORD,WORD,LONG);
57 extern WORD CALLBACK CallTo16_word_llll (FARPROC16,LONG,LONG,LONG,LONG);
58 extern LONG CALLBACK CallTo16_long_llll (FARPROC16,LONG,LONG,LONG,LONG);
59 extern WORD CALLBACK CallTo16_word_wllwl(FARPROC16,WORD,LONG,LONG,WORD,LONG);
60 extern WORD CALLBACK CallTo16_word_lwwww(FARPROC16,LONG,WORD,WORD,WORD,WORD);
61 extern LONG CALLBACK CallTo16_long_lwwll(FARPROC16,LONG,WORD,WORD,LONG,LONG);
62 extern WORD CALLBACK CallTo16_word_wwlll(FARPROC16,WORD,WORD,LONG,LONG,LONG);
63 extern WORD CALLBACK CallTo16_word_wwwww(FARPROC16,WORD,WORD,WORD,WORD,WORD);
64 extern WORD CALLBACK CallTo16_word_lwlll(FARPROC16,LONG,WORD,LONG,LONG,LONG);
65 extern LONG CALLBACK CallTo16_long_lwlll(FARPROC16,LONG,WORD,LONG,LONG,LONG);
66 extern LONG CALLBACK CallTo16_long_lllll(FARPROC16,LONG,LONG,LONG,LONG,LONG);
67 extern LONG CALLBACK CallTo16_long_llllll(FARPROC16,LONG,LONG,LONG,LONG,LONG,
68                                           LONG);
69 extern LONG CALLBACK CallTo16_long_lllllll(FARPROC16,LONG,LONG,LONG,LONG,LONG,
70                                            LONG,LONG);
71 extern WORD CALLBACK CallTo16_word_llwwlll(FARPROC16,LONG,LONG,WORD,WORD,LONG,
72                                            LONG,LONG);
73 extern LONG CALLBACK CallTo16_word_lwwlllll(FARPROC16,LONG,WORD,WORD,LONG,LONG,
74                                             LONG,LONG,LONG);
75 extern LONG CALLBACK CallTo16_long_llllllll(FARPROC16,LONG,LONG,LONG,LONG,LONG,
76                                             LONG,LONG,LONG);
77 extern LONG CALLBACK CallTo16_long_lllllllll(FARPROC16,LONG,LONG,LONG,LONG,
78                                              LONG,LONG,LONG,LONG,LONG);
79 extern LONG CALLBACK CallTo16_long_llllllllll(FARPROC16,LONG,LONG,LONG,LONG,
80                                               LONG,LONG,LONG,LONG,LONG,LONG);
81 extern LONG CALLBACK CallTo16_long_lllllllllll(FARPROC16,LONG,LONG,LONG,LONG,
82                                                LONG,LONG,LONG,LONG,LONG,LONG,
83                                                LONG);
84 extern LONG CALLBACK CallTo16_long_llllllllllll(FARPROC16,LONG,LONG,LONG,LONG,
85                                                 LONG,LONG,LONG,LONG,LONG,LONG,
86                                                 LONG,LONG);
87 extern LONG CALLBACK CallTo16_long_lwwllwlllllw(FARPROC16,LONG,WORD,WORD,LONG,
88                                                 LONG,WORD,LONG,LONG,LONG,LONG,
89                                                 LONG,WORD);
90 extern LONG CALLBACK CallTo16_long_lllllllllllll(FARPROC16,LONG,LONG,LONG,LONG,
91                                                  LONG,LONG,LONG,LONG,LONG,LONG,
92                                                  LONG,LONG,LONG);
93 extern LONG CALLBACK CallTo16_long_llllllllllllll(FARPROC16,LONG,LONG,LONG,
94                                                   LONG,LONG,LONG,LONG,LONG,
95                                                   LONG,LONG,LONG,LONG,LONG,
96                                                   LONG);
97 extern LONG CALLBACK CallTo16_word_lwwwwlwwwwllll(FARPROC16,LONG,WORD,WORD,
98                                                   WORD,WORD,LONG,WORD,WORD,
99                                                   WORD,WORD,LONG,LONG,LONG,
100                                                   LONG);
101 extern LONG CALLBACK CallTo16_long_lllllllllllllll(FARPROC16,LONG,LONG,LONG,
102                                                    LONG,LONG,LONG,LONG,LONG,
103                                                    LONG,LONG,LONG,LONG,LONG,
104                                                    LONG,LONG);
105 extern LONG CALLBACK CallTo16_long_llllllllllllllll(FARPROC16,LONG,LONG,LONG,
106                                                     LONG,LONG,LONG,LONG,LONG,
107                                                     LONG,LONG,LONG,LONG,LONG,
108                                                     LONG,LONG,LONG);
109 /* ### stop build ### */
110
111
112 typedef void (*RELAY)();
113
114 #pragma pack(1)
115
116 typedef struct tagTHUNK
117 {
118     BYTE             popl_eax;           /* 0x58  popl  %eax (return address)*/
119     BYTE             pushl_func;         /* 0x68  pushl $proc */
120     FARPROC        proc WINE_PACKED;
121     BYTE             pushl_eax;          /* 0x50  pushl %eax */
122     BYTE             jmp;                /* 0xe9  jmp   relay (relative jump)*/
123     RELAY            relay WINE_PACKED;
124     struct tagTHUNK *next WINE_PACKED;
125 } THUNK;
126
127 #pragma pack(4)
128
129 #define DECL_THUNK(name,proc,relay) \
130     THUNK name = { 0x58, 0x68, (FARPROC)(proc), 0x50, 0xe9, \
131                    (RELAY)((char *)(relay) - (char *)(&(name).next)), NULL }
132
133
134 static THUNK *firstThunk = NULL;
135
136 static LRESULT WINAPI THUNK_CallWndProc16( WNDPROC16 proc, HWND16 hwnd,
137                                            UINT16 msg, WPARAM16 wParam,
138                                            LPARAM lParam );
139 static BOOL WINAPI THUNK_CallTaskReschedule(void);
140 static BOOL WINAPI THUNK_WOWCallback16Ex( FARPROC16,DWORD,DWORD,
141                                             LPVOID,LPDWORD );
142
143 /* TASK_Reschedule() 16-bit entry point */
144 static FARPROC16 TASK_RescheduleProc;
145
146 static BOOL THUNK_ThunkletInit( void );
147
148 extern void CallFrom16_p_long_wwwll(void);
149
150 /* Callbacks function table for the emulator */
151 static const CALLBACKS_TABLE CALLBACK_EmulatorTable =
152 {
153     (void *)CallTo16_sreg_,                /* CallRegisterShortProc */
154     (void *)CallTo16_lreg_,                /* CallRegisterLongProc */
155     THUNK_CallTaskReschedule,              /* CallTaskRescheduleProc */
156     (void*)CallFrom16_p_long_wwwll,        /* CallFrom16WndProc */
157     THUNK_CallWndProc16,                   /* CallWndProc */
158     (void *)CallTo16_long_lwwll,           /* CallDriverProc */
159     (void *)CallTo16_word_wwlll,           /* CallDriverCallback */
160     (void *)CallTo16_word_wwlll,           /* CallTimeFuncProc */
161     (void *)CallTo16_word_w,               /* CallWindowsExitProc */
162     (void *)CallTo16_word_lwww,            /* CallWordBreakProc */
163     (void *)CallTo16_word_ww,              /* CallBootAppProc */
164     (void *)CallTo16_word_www,             /* CallLoadAppSegProc */
165     (void *)CallTo16_word_www,             /* CallLocalNotifyFunc */
166     (void *)CallTo16_word_www,             /* CallResourceHandlerProc */
167     (void *)CallTo16_long_l,               /* CallWOWCallbackProc */
168     THUNK_WOWCallback16Ex,                 /* CallWOWCallback16Ex */
169     (void *)CallTo16_long_ll,              /* CallUTProc */
170     (void *)CallTo16_long_l,               /* CallASPIPostProc */
171     (void *)CallTo16_word_lwll,            /* CallDrvControlProc */
172     (void *)CallTo16_word_lwlll,           /* CallDrvEnableProc */
173     (void *)CallTo16_word_llll,            /* CallDrvEnumDFontsProc */
174     (void *)CallTo16_word_lwll,            /* CallDrvEnumObjProc */
175     (void *)CallTo16_word_lwwlllll,        /* CallDrvOutputProc */
176     (void *)CallTo16_long_lwlll,           /* CallDrvRealizeProc */
177     (void *)CallTo16_word_lwwwwlwwwwllll,  /* CallDrvStretchBltProc */
178     (void *)CallTo16_long_lwwllwlllllw,    /* CallDrvExtTextOutProc */
179     (void *)CallTo16_word_llwwlll,         /* CallDrvGetCharWidth */ 
180     (void *)CallTo16_word_ww               /* CallDrvAbortProc */
181 };
182
183
184 /***********************************************************************
185  *           THUNK_Init
186  */
187 BOOL THUNK_Init(void)
188 {
189     /* Set the window proc calling functions */
190     Callbacks = &CALLBACK_EmulatorTable;
191     /* Get the 16-bit reschedule function pointer */
192     TASK_RescheduleProc = MODULE_GetWndProcEntry16( "TASK_Reschedule" );
193     /* Initialize Thunklets */
194     return THUNK_ThunkletInit();
195 }
196
197 /***********************************************************************
198  *           THUNK_Alloc
199  */
200 static THUNK *THUNK_Alloc( FARPROC func, RELAY relay )
201 {
202     THUNK *thunk = HeapAlloc( GetProcessHeap(), 0, sizeof(*thunk) );
203     if (thunk)
204     {
205         thunk->popl_eax   = 0x58;
206         thunk->pushl_func = 0x68;
207         thunk->proc       = func;
208         thunk->pushl_eax  = 0x50;
209         thunk->jmp        = 0xe9;
210         thunk->relay      = (RELAY)((char *)relay - (char *)(&thunk->next));
211         thunk->next       = firstThunk;
212         firstThunk = thunk;
213     }
214     return thunk;
215 }
216
217
218 /***********************************************************************
219  *           THUNK_Find
220  */
221 static THUNK *THUNK_Find( FARPROC func )
222 {
223     THUNK *thunk = firstThunk;
224     while (thunk && (thunk->proc != func)) thunk = thunk->next;
225     return thunk;
226 }
227
228
229 /***********************************************************************
230  *           THUNK_Free
231  */
232 static void THUNK_Free( THUNK *thunk )
233 {
234     if (HEAP_IsInsideHeap( GetProcessHeap(), 0, thunk ))
235     {
236         THUNK **prev = &firstThunk;
237         while (*prev && (*prev != thunk)) prev = &(*prev)->next;
238         if (*prev)
239         {
240             *prev = thunk->next;
241             HeapFree( GetProcessHeap(), 0, thunk );
242             return;
243         }
244     }
245     ERR(thunk, "invalid thunk addr %p\n", thunk );
246 }
247
248
249 /***********************************************************************
250  *           THUNK_CallWndProc16
251  *
252  * Call a 16-bit window procedure
253  */
254 static LRESULT WINAPI THUNK_CallWndProc16( WNDPROC16 proc, HWND16 hwnd,
255                                            UINT16 msg, WPARAM16 wParam,
256                                            LPARAM lParam )
257 {
258     CONTEXT context;
259     LRESULT ret;
260     WORD *args;
261     WND *wndPtr = WIN_FindWndPtr( hwnd );
262     DWORD offset = 0;
263     THDB *thdb = THREAD_Current();
264
265     /* Window procedures want ax = hInstance, ds = es = ss */
266     
267     memset(&context, '\0', sizeof(context));
268     DS_reg(&context)  = SELECTOROF(thdb->cur_stack);
269     ES_reg(&context)  = DS_reg(&context);
270     EAX_reg(&context) = wndPtr ? wndPtr->hInstance : DS_reg(&context);
271     CS_reg(&context)  = SELECTOROF(proc);
272     EIP_reg(&context) = OFFSETOF(proc);
273     EBP_reg(&context) = OFFSETOF(thdb->cur_stack)
274                         + (WORD)&((STACK16FRAME*)0)->bp;
275
276     WIN_ReleaseWndPtr(wndPtr);
277     
278     if (lParam)
279     {
280         /* Some programs (eg. the "Undocumented Windows" examples, JWP) only
281            work if structures passed in lParam are placed in the stack/data
282            segment. Programmers easily make the mistake of converting lParam
283            to a near rather than a far pointer, since Windows apparently
284            allows this. We copy the structures to the 16 bit stack; this is
285            ugly but makes these programs work. */
286         switch (msg)
287         {
288           case WM_CREATE:
289           case WM_NCCREATE:
290             offset = sizeof(CREATESTRUCT16); break;
291           case WM_DRAWITEM:
292             offset = sizeof(DRAWITEMSTRUCT16); break;
293           case WM_COMPAREITEM:
294             offset = sizeof(COMPAREITEMSTRUCT16); break;
295         }
296         if (offset)
297         {
298             void *s = PTR_SEG_TO_LIN(lParam);
299             lParam = STACK16_PUSH( thdb, offset );
300             memcpy( PTR_SEG_TO_LIN(lParam), s, offset );
301         }
302     }
303
304     args = (WORD *)THREAD_STACK16(thdb) - 5;
305     args[0] = LOWORD(lParam);
306     args[1] = HIWORD(lParam);
307     args[2] = wParam;
308     args[3] = msg;
309     args[4] = hwnd;
310
311     ret = CallTo16_sreg_( &context, 5 * sizeof(WORD) );
312     if (offset) STACK16_POP( thdb, offset );
313     return ret;
314 }
315
316
317 /***********************************************************************
318  *           THUNK_CallTaskReschedule
319  */
320 static BOOL WINAPI THUNK_CallTaskReschedule(void)
321 {
322     return CallTo16_word_(TASK_RescheduleProc);
323 }
324
325
326 /***********************************************************************
327  *           THUNK_EnumObjects16   (GDI.71)
328  */
329 INT16 WINAPI THUNK_EnumObjects16( HDC16 hdc, INT16 nObjType,
330                                   GOBJENUMPROC16 func, LPARAM lParam )
331 {
332     DECL_THUNK( thunk, func, CallTo16_word_ll );
333     return EnumObjects16( hdc, nObjType, (GOBJENUMPROC16)&thunk, lParam );
334 }
335
336
337 /*************************************************************************
338  *           THUNK_EnumFonts16   (GDI.70)
339  */
340 INT16 WINAPI THUNK_EnumFonts16( HDC16 hdc, LPCSTR lpFaceName,
341                                 FONTENUMPROC16 func, LPARAM lParam )
342 {
343     DECL_THUNK( thunk, func, CallTo16_word_llwl );
344     return EnumFonts16( hdc, lpFaceName, (FONTENUMPROC16)&thunk, lParam );
345 }
346
347 /******************************************************************
348  *           THUNK_EnumMetaFile16   (GDI.175)
349  */
350 BOOL16 WINAPI THUNK_EnumMetaFile16( HDC16 hdc, HMETAFILE16 hmf,
351                                     MFENUMPROC16 func, LPARAM lParam )
352 {
353     DECL_THUNK( thunk, func, CallTo16_word_wllwl );
354     return EnumMetaFile16( hdc, hmf, (MFENUMPROC16)&thunk, lParam );
355 }
356
357
358 /*************************************************************************
359  *           THUNK_EnumFontFamilies16   (GDI.330)
360  */
361 INT16 WINAPI THUNK_EnumFontFamilies16( HDC16 hdc, LPCSTR lpszFamily,
362                                        FONTENUMPROC16 func, LPARAM lParam )
363 {
364     DECL_THUNK( thunk, func, CallTo16_word_llwl );
365     return EnumFontFamilies16(hdc, lpszFamily, (FONTENUMPROC16)&thunk, lParam);
366 }
367
368
369 /*************************************************************************
370  *           THUNK_EnumFontFamiliesEx16   (GDI.613)
371  */
372 INT16 WINAPI THUNK_EnumFontFamiliesEx16( HDC16 hdc, LPLOGFONT16 lpLF,
373                                          FONTENUMPROCEX16 func, LPARAM lParam,
374                                          DWORD reserved )
375 {
376     DECL_THUNK( thunk, func, CallTo16_word_llwl );
377     return EnumFontFamiliesEx16( hdc, lpLF, (FONTENUMPROCEX16)&thunk,
378                                  lParam, reserved );
379 }
380
381
382 /**********************************************************************
383  *           THUNK_LineDDA16   (GDI.100)
384  */
385 void WINAPI THUNK_LineDDA16( INT16 nXStart, INT16 nYStart, INT16 nXEnd,
386                              INT16 nYEnd, LINEDDAPROC16 func, LPARAM lParam )
387 {
388     DECL_THUNK( thunk, func, CallTo16_word_wwl );
389     LineDDA16( nXStart, nYStart, nXEnd, nYEnd, (LINEDDAPROC16)&thunk, lParam );
390 }
391
392
393 /*******************************************************************
394  *           THUNK_EnumWindows16   (USER.54)
395  */
396 BOOL16 WINAPI THUNK_EnumWindows16( WNDENUMPROC16 func, LPARAM lParam )
397 {
398     DECL_THUNK( thunk, func, CallTo16_word_wl );
399     return EnumWindows16( (WNDENUMPROC16)&thunk, lParam );
400 }
401
402
403 /**********************************************************************
404  *           THUNK_EnumChildWindows16   (USER.55)
405  */
406 BOOL16 WINAPI THUNK_EnumChildWindows16( HWND16 parent, WNDENUMPROC16 func,
407                                         LPARAM lParam )
408 {
409     DECL_THUNK( thunk, func, CallTo16_word_wl );
410     return EnumChildWindows16( parent, (WNDENUMPROC16)&thunk, lParam );
411 }
412
413
414 /**********************************************************************
415  *           THUNK_EnumTaskWindows16   (USER.225)
416  */
417 BOOL16 WINAPI THUNK_EnumTaskWindows16( HTASK16 hTask, WNDENUMPROC16 func,
418                                        LPARAM lParam )
419 {
420     DECL_THUNK( thunk, func, CallTo16_word_wl );
421     return EnumTaskWindows16( hTask, (WNDENUMPROC16)&thunk, lParam );
422 }
423
424
425 /***********************************************************************
426  *           THUNK_EnumProps16   (USER.27)
427  */
428 INT16 WINAPI THUNK_EnumProps16( HWND16 hwnd, PROPENUMPROC16 func )
429 {
430     DECL_THUNK( thunk, func, CallTo16_word_wlw );
431     return EnumProps16( hwnd, (PROPENUMPROC16)&thunk );
432 }
433
434
435 /***********************************************************************
436  *           THUNK_GrayString16   (USER.185)
437  */
438 BOOL16 WINAPI THUNK_GrayString16( HDC16 hdc, HBRUSH16 hbr,
439                                   GRAYSTRINGPROC16 func, LPARAM lParam,
440                                   INT16 cch, INT16 x, INT16 y,
441                                   INT16 cx, INT16 cy )
442 {
443     DECL_THUNK( thunk, func, CallTo16_word_wlw );
444     if (!func)
445         return GrayString16( hdc, hbr, NULL, lParam, cch, x, y, cx, cy );
446     else
447         return GrayString16( hdc, hbr, (GRAYSTRINGPROC16)&thunk, lParam, cch,
448                              x, y, cx, cy );
449 }
450
451
452 /***********************************************************************
453  *           THUNK_SetWindowsHook16   (USER.121)
454  */
455 FARPROC16 WINAPI THUNK_SetWindowsHook16( INT16 id, HOOKPROC16 proc )
456 {
457     HINSTANCE16 hInst = FarGetOwner16( HIWORD(proc) );
458     HTASK16 hTask = (id == WH_MSGFILTER) ? GetCurrentTask() : 0;
459     THUNK *thunk = THUNK_Alloc( (FARPROC16)proc, (RELAY)CallTo16_long_wwl );
460     if (!thunk) return 0;
461     return (FARPROC16)SetWindowsHookEx16( id, (HOOKPROC16)thunk, hInst, hTask);
462 }
463
464
465 /***********************************************************************
466  *           THUNK_UnhookWindowsHook16   (USER.234)
467  */
468 BOOL16 WINAPI THUNK_UnhookWindowsHook16( INT16 id, HOOKPROC16 proc )
469 {
470     BOOL16 ret;
471     THUNK *thunk = THUNK_Find( (FARPROC16)proc );
472     if (!thunk) return FALSE;
473     ret = UnhookWindowsHook16( id, (HOOKPROC16)thunk );
474     THUNK_Free( thunk );
475     return ret;
476 }
477
478
479 /***********************************************************************
480  *           THUNK_SetWindowsHookEx16   (USER.291)
481  */
482 HHOOK WINAPI THUNK_SetWindowsHookEx16( INT16 id, HOOKPROC16 proc,
483                                        HINSTANCE16 hInst, HTASK16 hTask )
484 {
485     THUNK *thunk = THUNK_Alloc( (FARPROC16)proc, (RELAY)CallTo16_long_wwl );
486     if (!thunk) return 0;
487     return SetWindowsHookEx16( id, (HOOKPROC16)thunk, hInst, hTask );
488 }
489
490
491 /***********************************************************************
492  *           THUNK_UnhookWindowHookEx16   (USER.292)
493  */
494 BOOL16 WINAPI THUNK_UnhookWindowsHookEx16( HHOOK hhook )
495 {
496     THUNK *thunk = (THUNK *)HOOK_GetProc16( hhook );
497     BOOL16 ret = UnhookWindowsHookEx16( hhook );
498     if (thunk) THUNK_Free( thunk );
499     return ret;
500 }
501
502
503
504 static FARPROC16 defDCHookProc = NULL;
505
506 /***********************************************************************
507  *           THUNK_SetDCHook   (GDI.190)
508  */
509 BOOL16 WINAPI THUNK_SetDCHook( HDC16 hdc, FARPROC16 proc, DWORD dwHookData )
510 {
511     THUNK *thunk, *oldThunk;
512
513     if (!defDCHookProc)  /* Get DCHook Win16 entry point */
514         defDCHookProc = NE_GetEntryPoint( GetModuleHandle16("USER"), 362 );
515
516     if (proc != defDCHookProc)
517     {
518         thunk = THUNK_Alloc( proc, (RELAY)CallTo16_word_wwll );
519         if (!thunk) return FALSE;
520     }
521     else thunk = (THUNK *)DCHook16;
522
523     /* Free the previous thunk */
524     GetDCHook( hdc, (FARPROC16 *)&oldThunk );
525     if (oldThunk && (oldThunk != (THUNK *)DCHook16)) THUNK_Free( oldThunk );
526
527     return SetDCHook( hdc, (FARPROC16)thunk, dwHookData );
528 }
529
530
531 /***********************************************************************
532  *           THUNK_GetDCHook   (GDI.191)
533  */
534 DWORD WINAPI THUNK_GetDCHook( HDC16 hdc, FARPROC16 *phookProc )
535 {
536     THUNK *thunk = NULL;
537     DWORD ret = GetDCHook( hdc, (FARPROC16 *)&thunk );
538     if (thunk)
539     {
540         if (thunk == (THUNK *)DCHook16)
541         {
542             if (!defDCHookProc)  /* Get DCHook Win16 entry point */
543                 defDCHookProc = NE_GetEntryPoint(GetModuleHandle16("USER"),362);
544             *phookProc = defDCHookProc;
545         }
546         else *phookProc = thunk->proc;
547     }
548     return ret;
549 }
550
551
552 /***********************************************************************
553  *           THUNK_SetTaskSignalProc (KERNEL.38)
554  */
555 FARPROC16 WINAPI THUNK_SetTaskSignalProc( HTASK16 hTask, FARPROC16 proc )
556 {
557     static FARPROC16 defSignalProc16 = NULL;
558
559     THUNK *thunk = NULL;
560
561     if( !defSignalProc16 )
562         defSignalProc16 = NE_GetEntryPoint(GetModuleHandle16("USER"), 314 );
563
564     if( proc == defSignalProc16 )
565         thunk = (THUNK*)SetTaskSignalProc( hTask, (FARPROC16)&USER_SignalProc );
566     else 
567     {
568         thunk = THUNK_Alloc( proc, (RELAY)CallTo16_word_wwwww );
569         if( !thunk ) return FALSE;
570         thunk = (THUNK*)SetTaskSignalProc( hTask, (FARPROC16)thunk );
571     }
572
573     if( thunk != (THUNK*)USER_SignalProc )
574     {
575         if( !thunk ) return NULL;
576
577         proc = thunk->proc;
578         THUNK_Free( thunk );
579         return proc;
580     }
581     return defSignalProc16;
582 }
583
584 /***********************************************************************
585  *           THUNK_CreateThread16   (KERNEL.441)
586  */
587 static DWORD CALLBACK THUNK_StartThread16( LPVOID threadArgs )
588 {
589     FARPROC16 start = ((FARPROC16 *)threadArgs)[0];
590     DWORD     param = ((DWORD *)threadArgs)[1];
591     HeapFree( GetProcessHeap(), 0, threadArgs );
592
593     return CallTo16_long_l( start, param );
594 }
595 HANDLE WINAPI THUNK_CreateThread16( SECURITY_ATTRIBUTES *sa, DWORD stack,
596                                       FARPROC16 start, SEGPTR param,
597                                       DWORD flags, LPDWORD id )
598 {
599     DWORD *threadArgs = HeapAlloc( GetProcessHeap(), 0, 2*sizeof(DWORD) );
600     if (!threadArgs) return INVALID_HANDLE_VALUE;
601     threadArgs[0] = (DWORD)start;
602     threadArgs[1] = (DWORD)param;
603
604     return CreateThread( sa, stack, THUNK_StartThread16, threadArgs, flags, id );
605 }
606
607 /***********************************************************************
608  *           THUNK_WOWCallback16Ex      (WOW32.3)(KERNEL32.55)
609  * Generic thunking routine to call 16 bit functions from 32bit code.
610  * 
611  * RETURNS
612  *      TRUE if the call was done
613  */
614 static BOOL WINAPI THUNK_WOWCallback16Ex(
615         FARPROC16 proc,         /* [in] 16bit function to call */
616         DWORD dwFlags,          /* [in] flags (WCB_*) */
617         DWORD cbArgs,           /* [in] number of arguments */
618         LPVOID xargs,           /* [in/out] arguments */
619         LPDWORD pdwret          /* [out] return value of the 16bit call */
620 ) {
621     LPDWORD     args = (LPDWORD)xargs;
622     DWORD       ret,i;
623
624     TRACE(relay,"(%p,0x%08lx,%ld,%p,%p)\n",
625         proc,dwFlags,cbArgs,xargs,pdwret
626     );
627     if (dwFlags == WCB16_CDECL) {
628         /* swap the arguments */
629         args = HeapAlloc(GetProcessHeap(),0,cbArgs*sizeof(DWORD));
630         for (i=0;i<cbArgs;i++)
631             args[i] = ((DWORD*)xargs)[cbArgs-i-1];
632     }
633     switch (cbArgs) {
634     case 0: ret = CallTo16_long_(proc);break;
635     case 1: ret = CallTo16_long_l(proc,args[0]);break;
636     case 2: ret = CallTo16_long_ll(proc,args[0],args[1]);break;
637     case 3: ret = CallTo16_long_lll(proc,args[0],args[1],args[2]);break;
638     case 4: ret = CallTo16_long_llll(proc,args[0],args[1],args[2],args[3]);
639             break;
640     case 5: ret = CallTo16_long_lllll(proc,args[0],args[1],args[2],args[3],
641                 args[4]
642             );
643             break;
644     case 6: ret = CallTo16_long_llllll(proc,args[0],args[1],args[2],args[3],
645                 args[4],args[5]
646             );
647             break;
648     case 7: ret = CallTo16_long_lllllll(proc,args[0],args[1],args[2],args[3],
649                 args[4],args[5],args[6]
650             );
651             break;
652     case 8: ret = CallTo16_long_llllllll(proc,args[0],args[1],args[2],args[3],
653                 args[4],args[5],args[6],args[7]
654             );
655             break;
656     case 9: ret = CallTo16_long_lllllllll(proc,args[0],args[1],args[2],args[3],
657                 args[4],args[5],args[6],args[7],args[8]
658             );
659             break;
660     case 10:ret = CallTo16_long_llllllllll(proc,args[0],args[1],args[2],args[3],
661                 args[4],args[5],args[6],args[7],args[8],args[9]
662             );
663             break;
664     case 11:ret = CallTo16_long_lllllllllll(proc,args[0],args[1],args[2],
665                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10]
666             );
667             break;
668     case 12:ret = CallTo16_long_llllllllllll(proc,args[0],args[1],args[2],
669                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],
670                 args[10],args[11]
671             );
672             break;
673     case 13:ret = CallTo16_long_lllllllllllll(proc,args[0],args[1],args[2],
674                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],
675                 args[10],args[11],args[12]
676             );
677             break;
678     case 14:ret = CallTo16_long_llllllllllllll(proc,args[0],args[1],args[2],
679                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],
680                 args[10],args[11],args[12],args[13]
681             );
682             break;
683     case 15:ret = CallTo16_long_lllllllllllllll(proc,args[0],args[1],args[2],
684                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],
685                 args[10],args[11],args[12],args[13],args[14]
686             );
687             break;
688     case 16:ret = CallTo16_long_llllllllllllllll(proc,args[0],args[1],args[2],
689                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],
690                 args[10],args[11],args[12],args[13],args[14],args[15]
691             );
692             break;
693     default:
694             ERR(thunk,"%ld arguments not supported.\n",cbArgs);
695             if (dwFlags == WCB16_CDECL)
696                 HeapFree(GetProcessHeap(),0,args);
697             return FALSE;
698     }
699     if (dwFlags == WCB16_CDECL)
700         HeapFree(GetProcessHeap(),0,args);
701     if (pdwret) 
702         *pdwret = ret;
703     return TRUE;
704 }
705
706 /***********************************************************************
707  *           THUNK_MOUSE_Enable   (MOUSE.2)
708  */
709 static VOID WINAPI THUNK_CallMouseEventProc( FARPROC16 proc, 
710                                              DWORD dwFlags, DWORD dx, DWORD dy,
711                                              DWORD cButtons, DWORD dwExtraInfo )
712 {
713     CONTEXT context;
714
715     memset( &context, 0, sizeof(context) );
716     CS_reg(&context)  = SELECTOROF( proc );
717     EIP_reg(&context) = OFFSETOF( proc );
718     AX_reg(&context)  = (WORD)dwFlags;
719     BX_reg(&context)  = (WORD)dx;
720     CX_reg(&context)  = (WORD)dy;
721     DX_reg(&context)  = (WORD)cButtons;
722     SI_reg(&context)  = LOWORD( dwExtraInfo );
723     DI_reg(&context)  = HIWORD( dwExtraInfo );
724
725     CallTo16_sreg_( &context, 0 );
726 }
727 VOID WINAPI THUNK_MOUSE_Enable( FARPROC16 proc )
728 {
729     static THUNK *lastThunk = NULL;
730     static FARPROC16 lastProc = NULL;
731
732     if ( lastProc != proc )
733     {
734         if ( lastThunk ) 
735             THUNK_Free( lastThunk );
736
737         if ( !proc )
738             lastThunk = NULL;
739         else
740             lastThunk = THUNK_Alloc( proc, (RELAY)THUNK_CallMouseEventProc );
741
742         lastProc = proc;
743     }
744
745     return MOUSE_Enable( (LPMOUSE_EVENT_PROC)lastThunk );
746 }
747
748 /***********************************************************************
749  *           GetMouseEventProc   (USER.337)
750  */
751 FARPROC16 WINAPI GetMouseEventProc16(void)
752 {
753     HMODULE16 hmodule = GetModuleHandle16("USER");
754     return NE_GetEntryPoint( hmodule, NE_GetOrdinal( hmodule, "mouse_event" ));
755 }
756
757
758 /***********************************************************************
759  *           WIN16_mouse_event   (USER.299)
760  */
761 void WINAPI WIN16_mouse_event( CONTEXT *context )
762 {
763     mouse_event( AX_reg(context), BX_reg(context), CX_reg(context),
764                  DX_reg(context), MAKELONG(SI_reg(context), DI_reg(context)) );
765 }
766
767
768 /***********************************************************************
769  *           THUNK_KEYBD_Enable   (KEYBOARD.2)
770  */
771 static VOID WINAPI THUNK_CallKeybdEventProc( FARPROC16 proc, 
772                                              BYTE bVk, BYTE bScan,
773                                              DWORD dwFlags, DWORD dwExtraInfo )
774 {
775     CONTEXT context;
776
777     memset( &context, 0, sizeof(context) );
778     CS_reg(&context)  = SELECTOROF( proc );
779     EIP_reg(&context) = OFFSETOF( proc );
780     AH_reg(&context)  = (dwFlags & KEYEVENTF_KEYUP)? 0x80 : 0;
781     AL_reg(&context)  = bVk;
782     BH_reg(&context)  = (dwFlags & KEYEVENTF_EXTENDEDKEY)? 1 : 0;
783     BL_reg(&context)  = bScan;
784     SI_reg(&context)  = LOWORD( dwExtraInfo );
785     DI_reg(&context)  = HIWORD( dwExtraInfo );
786
787     CallTo16_sreg_( &context, 0 );
788 }
789 VOID WINAPI THUNK_KEYBOARD_Enable( FARPROC16 proc, LPBYTE lpKeyState )
790 {
791     static THUNK *lastThunk = NULL;
792     static FARPROC16 lastProc = NULL;
793
794     if ( lastProc != proc )
795     {
796         if ( lastThunk ) 
797             THUNK_Free( lastThunk );
798
799         if ( !proc )
800             lastThunk = NULL;
801         else
802             lastThunk = THUNK_Alloc( proc, (RELAY)THUNK_CallKeybdEventProc );
803
804         lastProc = proc;
805     }
806
807     return KEYBOARD_Enable( (LPKEYBD_EVENT_PROC)lastThunk, lpKeyState );
808 }
809
810 /***********************************************************************
811  *           WIN16_keybd_event   (USER.289)
812  */
813 void WINAPI WIN16_keybd_event( CONTEXT *context )
814 {
815     DWORD dwFlags = 0;
816     
817     if (AH_reg(context) & 0x80) dwFlags |= KEYEVENTF_KEYUP;
818     if (BH_reg(context) & 1   ) dwFlags |= KEYEVENTF_EXTENDEDKEY;
819
820     keybd_event( AL_reg(context), BL_reg(context), 
821                  dwFlags, MAKELONG(SI_reg(context), DI_reg(context)) );
822 }
823
824
825 /***********************************************************************
826  *           WIN16_CreateSystemTimer   (SYSTEM.2)
827  */
828 static void THUNK_CallSystemTimerProc( FARPROC16 proc, WORD timer )
829 {
830     CONTEXT context;
831     memset( &context, '\0', sizeof(context) );
832
833     CS_reg( &context ) = SELECTOROF( proc );
834     IP_reg( &context ) = OFFSETOF( proc );
835     BP_reg( &context ) = OFFSETOF( THREAD_Current()->cur_stack )
836                          + (WORD)&((STACK16FRAME*)0)->bp;
837
838     AX_reg( &context ) = timer;
839
840     if ( _ConfirmWin16Lock() )
841     {
842         FIXME( system, "Skipping timer %d callback because timer signal "
843                        "arrived while we own the Win16Lock!\n", timer );
844         return;
845     }
846
847     CallTo16_sreg_( &context, 0 ); 
848
849     /* FIXME: This does not work if the signal occurs while this thread
850               is currently in 16-bit code. With the current structure
851               of the Wine thunking code, this seems to be hard to fix ... */
852 }
853 WORD WINAPI WIN16_CreateSystemTimer( WORD rate, FARPROC16 proc )
854 {
855     THUNK *thunk = THUNK_Alloc( proc, (RELAY)THUNK_CallSystemTimerProc );
856     WORD timer = CreateSystemTimer( rate, (SYSTEMTIMERPROC)thunk );
857     if (!timer) THUNK_Free( thunk );
858     return timer;
859 }
860
861 /***********************************************************************
862  *           THUNK_InitCallout
863  */
864 void THUNK_InitCallout(void)
865 {
866     HMODULE hModule = GetModuleHandleA( "USER32" );
867     if ( hModule )
868     {
869 #define GETADDR( var, name )  \
870         *(FARPROC *)&Callout.##var = GetProcAddress( hModule, name )
871
872         GETADDR( PeekMessageA, "PeekMessageA" );
873         GETADDR( PeekMessageW, "PeekMessageW" );
874         GETADDR( GetMessageA, "GetMessageA" );
875         GETADDR( GetMessageW, "GetMessageW" );
876         GETADDR( SendMessageA, "SendMessageA" );
877         GETADDR( SendMessageW, "SendMessageW" );
878         GETADDR( PostMessageA, "PostMessageA" );
879         GETADDR( PostMessageW, "PostMessageW" );
880         GETADDR( PostThreadMessageA, "PostThreadMessageA" );
881         GETADDR( PostThreadMessageW, "PostThreadMessageW" );
882         GETADDR( TranslateMessage, "TranslateMessage" );
883         GETADDR( DispatchMessageW, "DispatchMessageW" );
884         GETADDR( DispatchMessageA, "DispatchMessageA" );
885         GETADDR( RedrawWindow, "RedrawWindow" );
886
887 #undef GETADDR
888     }
889
890     hModule = GetModuleHandle16( "USER" );
891     if ( hModule )
892     {
893 #define GETADDR( var, name, thk )  \
894         *(FARPROC *)&Callout.##var = (FARPROC) \
895               THUNK_Alloc( WIN32_GetProcAddress16( hModule, name ), \
896                            (RELAY)CallTo16_##thk )
897
898         GETADDR( PeekMessage16, "PeekMessage", word_lwwww );
899         GETADDR( GetMessage16, "GetMessage", word_lwww );
900         GETADDR( SendMessage16, "SendMessage", long_wwwl );
901         GETADDR( PostMessage16, "PostMessage", word_wwwl );
902         GETADDR( PostAppMessage16, "PostAppMessage", word_wwwl );
903         GETADDR( TranslateMessage16, "TranslateMessage", word_l );
904         GETADDR( DispatchMessage16, "DispatchMessage", long_l );
905         GETADDR( RedrawWindow16, "RedrawWindow", word_wlww );
906         GETADDR( InitThreadInput16, "InitThreadInput", word_ww );
907         GETADDR( UserYield16, "UserYield", word_ );
908         GETADDR( DestroyIcon32, "DestroyIcon32", word_ww );
909
910 #undef GETADDR
911     }
912 }
913
914 /***********************************************************************
915  * 16->32 Flat Thunk routines:
916  */
917
918 /***********************************************************************
919  *              ThunkConnect16          (KERNEL.651)
920  * Connects a 32bit and a 16bit thunkbuffer.
921  */
922 UINT WINAPI ThunkConnect16(
923         LPSTR module16,              /* [in] name of win16 dll */
924         LPSTR module32,              /* [in] name of win32 dll */
925         HINSTANCE16 hInst16,         /* [in] hInst of win16 dll */
926         DWORD dwReason,              /* [in] initialisation argument */
927         struct ThunkDataCommon *TD,  /* [in/out] thunkbuffer */
928         LPSTR thunkfun32,            /* [in] win32 thunkfunction */
929         WORD cs                      /* [in] CS of win16 dll */
930 ) {
931     BOOL directionSL;
932
933     if (!lstrncmpA(TD->magic, "SL01", 4))
934     {
935         directionSL = TRUE;
936
937         TRACE(thunk, "SL01 thunk %s (%lx) -> %s (%s), Reason: %ld\n",
938                      module16, (DWORD)TD, module32, thunkfun32, dwReason);
939     }
940     else if (!lstrncmpA(TD->magic, "LS01", 4))
941     {
942         directionSL = FALSE;
943
944         TRACE(thunk, "LS01 thunk %s (%lx) <- %s (%s), Reason: %ld\n",
945                      module16, (DWORD)TD, module32, thunkfun32, dwReason);
946     }
947     else
948     {
949         ERR(thunk, "Invalid magic %c%c%c%c\n",
950                    TD->magic[0], TD->magic[1], TD->magic[2], TD->magic[3]);
951         return 0;
952     }
953
954     switch (dwReason)
955     {
956         case DLL_PROCESS_ATTACH:
957             if (directionSL)
958             {
959                 struct ThunkDataSL16 *SL16 = (struct ThunkDataSL16 *)TD;
960                 struct ThunkDataSL   *SL   = SL16->fpData;
961
962                 if (SL == NULL)
963                 {
964                     SL = HeapAlloc(GetProcessHeap(), 0, sizeof(*SL));
965
966                     SL->common   = SL16->common;
967                     SL->flags1   = SL16->flags1;
968                     SL->flags2   = SL16->flags2;
969
970                     SL->apiDB    = PTR_SEG_TO_LIN(SL16->apiDatabase);
971                     SL->targetDB = NULL;
972
973                     lstrcpynA(SL->pszDll16, module16, 255);
974                     lstrcpynA(SL->pszDll32, module32, 255);
975
976                     /* We should create a SEGPTR to the ThunkDataSL,
977                        but since the contents are not in the original format,
978                        any access to this by 16-bit code would crash anyway. */
979                     SL16->spData = 0;
980                     SL16->fpData = SL;
981                 }
982
983
984                 if (SL->flags2 & 0x80000000)
985                 {
986                     TRACE(thunk, "Preloading 32-bit library\n");
987                     LoadLibraryA(module32);
988                 }
989             }
990             else
991             {
992                 /* nothing to do */
993             }
994             break;
995
996         case DLL_PROCESS_DETACH:
997             /* FIXME: cleanup */
998             break;
999     }
1000
1001     return 1;
1002 }
1003
1004
1005 /***********************************************************************
1006  *           C16ThkSL                           (KERNEL.630)
1007  */
1008
1009 void WINAPI C16ThkSL(CONTEXT *context)
1010 {
1011     extern void CallFrom16_t_long_(void);
1012     LPBYTE stub = PTR_SEG_TO_LIN(EAX_reg(context)), x = stub;
1013     WORD cs, ds;
1014     GET_CS(cs);
1015     GET_DS(ds);
1016
1017     /* We produce the following code:
1018      *
1019      *   mov ax, __FLATDS
1020      *   mov es, ax
1021      *   movzx ecx, cx
1022      *   mov edx, es:[ecx + $EDX]
1023      *   push bp
1024      *   push edx
1025      *   call __FLATCS:CallFrom16_t_long_
1026      */
1027
1028     *x++ = 0xB8; *((WORD *)x)++ = ds;
1029     *x++ = 0x8E; *x++ = 0xC0;
1030     *x++ = 0x66; *x++ = 0x0F; *x++ = 0xB7; *x++ = 0xC9;
1031     *x++ = 0x67; *x++ = 0x66; *x++ = 0x26; *x++ = 0x8B;
1032                  *x++ = 0x91; *((DWORD *)x)++ = EDX_reg(context);
1033
1034     *x++ = 0x55;
1035     *x++ = 0x66; *x++ = 0x52;
1036     *x++ = 0x66; *x++ = 0x9A; *((DWORD *)x)++ = (DWORD)CallFrom16_t_long_;
1037                               *((WORD *)x)++ = cs;
1038
1039     /* Jump to the stub code just created */
1040     IP_reg(context) = LOWORD(EAX_reg(context));
1041     CS_reg(context) = HIWORD(EAX_reg(context));
1042
1043     /* Since C16ThkSL got called by a jmp, we need to leave the
1044        orginal return address on the stack */
1045     SP_reg(context) -= 4;
1046 }
1047
1048 /***********************************************************************
1049  *           C16ThkSL01                         (KERNEL.631)
1050  */
1051
1052 void WINAPI C16ThkSL01(CONTEXT *context)
1053 {
1054     LPBYTE stub = PTR_SEG_TO_LIN(EAX_reg(context)), x = stub;
1055
1056     if (stub)
1057     {
1058         struct ThunkDataSL16 *SL16 = PTR_SEG_TO_LIN(EDX_reg(context));
1059         struct ThunkDataSL *td = SL16->fpData;
1060
1061         extern void CallFrom16_t_long_(void);
1062         DWORD procAddress = (DWORD)GetProcAddress16(GetModuleHandle16("KERNEL"), 631);
1063         WORD cs;
1064         GET_CS(cs);
1065
1066         if (!td)
1067         {
1068             ERR(thunk, "ThunkConnect16 was not called!\n");
1069             return;
1070         }
1071
1072         TRACE(thunk, "Creating stub for ThunkDataSL %08lx\n", (DWORD)td);
1073
1074
1075         /* We produce the following code:
1076          *
1077          *   xor eax, eax
1078          *   mov edx, $td
1079          *   call C16ThkSL01
1080          *   push bp
1081          *   push edx
1082          *   call __FLATCS:CallFrom16_t_long_
1083          */
1084
1085         *x++ = 0x66; *x++ = 0x33; *x++ = 0xC0;
1086         *x++ = 0x66; *x++ = 0xBA; *((DWORD *)x)++ = (DWORD)td;
1087         *x++ = 0x9A; *((DWORD *)x)++ = procAddress;
1088
1089         *x++ = 0x55;
1090         *x++ = 0x66; *x++ = 0x52;
1091         *x++ = 0x66; *x++ = 0x9A; *((DWORD *)x)++ = (DWORD)CallFrom16_t_long_;
1092                                   *((WORD *)x)++ = cs;
1093
1094         /* Jump to the stub code just created */
1095         IP_reg(context) = LOWORD(EAX_reg(context));
1096         CS_reg(context) = HIWORD(EAX_reg(context));
1097
1098         /* Since C16ThkSL01 got called by a jmp, we need to leave the
1099            orginal return address on the stack */
1100         SP_reg(context) -= 4;
1101     }
1102     else
1103     {
1104         struct ThunkDataSL *td = (struct ThunkDataSL *)EDX_reg(context);
1105         DWORD targetNr = CX_reg(context) / 4;
1106         struct SLTargetDB *tdb;
1107
1108         TRACE(thunk, "Process %08lx calling target %ld of ThunkDataSL %08lx\n",
1109                      (DWORD)PROCESS_Current(), targetNr, (DWORD)td);
1110
1111         for (tdb = td->targetDB; tdb; tdb = tdb->next)
1112             if (tdb->process == PROCESS_Current())
1113                 break;
1114
1115         if (!tdb)
1116         {
1117             TRACE(thunk, "Loading 32-bit library %s\n", td->pszDll32);
1118             LoadLibraryA(td->pszDll32);
1119
1120             for (tdb = td->targetDB; tdb; tdb = tdb->next)
1121                 if (tdb->process == PROCESS_Current())
1122                     break;
1123         }
1124
1125         if (tdb)
1126         {
1127             EDX_reg(context) = tdb->targetTable[targetNr];
1128
1129             TRACE(thunk, "Call target is %08lx\n", EDX_reg(context));
1130         }
1131         else
1132         {
1133             WORD *stack = PTR_SEG_OFF_TO_LIN(SS_reg(context), SP_reg(context));
1134             DX_reg(context) = HIWORD(td->apiDB[targetNr].errorReturnValue);
1135             AX_reg(context) = LOWORD(td->apiDB[targetNr].errorReturnValue);
1136             IP_reg(context) = stack[2];
1137             CS_reg(context) = stack[3];
1138             SP_reg(context) += td->apiDB[targetNr].nrArgBytes + 4;
1139
1140             ERR(thunk, "Process %08lx did not ThunkConnect32 %s to %s\n",
1141                        (DWORD)PROCESS_Current(), td->pszDll32, td->pszDll16);
1142         }
1143     }
1144 }
1145
1146 DWORD WINAPI 
1147 WOW16Call(WORD x,WORD y,WORD z) {
1148         int     i;
1149         DWORD   calladdr;
1150         FIXME(thunk,"(0x%04x,0x%04x,%d),calling (",x,y,z);
1151
1152         for (i=0;i<x/2;i++) {
1153                 WORD    a = STACK16_POP(THREAD_Current(),2);
1154                 DPRINTF("%04x ",a);
1155         }
1156         calladdr = STACK16_POP(THREAD_Current(),4);
1157         DPRINTF(") calling address was 0x%08lx\n",calladdr);
1158         return 0;
1159 }
1160
1161
1162 /***********************************************************************
1163  * 16<->32 Thunklet/Callback API:
1164  */
1165
1166 #pragma pack(1)
1167 typedef struct _THUNKLET
1168 {
1169     BYTE        prefix_target;
1170     BYTE        pushl_target;
1171     DWORD       target;
1172
1173     BYTE        prefix_relay;
1174     BYTE        pushl_relay;
1175     DWORD       relay;
1176
1177     BYTE        jmp_glue;
1178     DWORD       glue;
1179
1180     BYTE        type;
1181     HINSTANCE16 owner;
1182     struct _THUNKLET *next;
1183 } THUNKLET;
1184 #pragma pack(4)
1185
1186 #define THUNKLET_TYPE_LS  1
1187 #define THUNKLET_TYPE_SL  2
1188
1189 static HANDLE  ThunkletHeap = 0;
1190 static THUNKLET *ThunkletAnchor = NULL;
1191
1192 static FARPROC ThunkletSysthunkGlueLS = 0;
1193 static SEGPTR    ThunkletSysthunkGlueSL = 0;
1194
1195 static FARPROC ThunkletCallbackGlueLS = 0;
1196 static SEGPTR    ThunkletCallbackGlueSL = 0;
1197
1198 /***********************************************************************
1199  *     THUNK_ThunkletInit
1200  */
1201 static BOOL THUNK_ThunkletInit( void )
1202 {
1203     LPBYTE thunk;
1204
1205     ThunkletHeap = HeapCreate(HEAP_WINE_SEGPTR | HEAP_WINE_CODE16SEG, 0, 0);
1206     if (!ThunkletHeap) return FALSE;
1207
1208     thunk = HeapAlloc( ThunkletHeap, 0, 5 );
1209     if (!thunk) return FALSE;
1210     
1211     ThunkletSysthunkGlueLS = (FARPROC)thunk;
1212     *thunk++ = 0x58;                             /* popl eax */
1213     *thunk++ = 0xC3;                             /* ret      */
1214
1215     ThunkletSysthunkGlueSL = HEAP_GetSegptr( ThunkletHeap, 0, thunk );
1216     *thunk++ = 0x66; *thunk++ = 0x58;            /* popl eax */
1217     *thunk++ = 0xCB;                             /* lret     */
1218
1219     return TRUE;
1220 }
1221
1222 /***********************************************************************
1223  *     SetThunkletCallbackGlue             (KERNEL.560)
1224  */
1225 void WINAPI SetThunkletCallbackGlue16( FARPROC glueLS, SEGPTR glueSL )
1226 {
1227     ThunkletCallbackGlueLS = glueLS;
1228     ThunkletCallbackGlueSL = glueSL;
1229 }
1230
1231
1232 /***********************************************************************
1233  *     THUNK_FindThunklet
1234  */
1235 THUNKLET *THUNK_FindThunklet( DWORD target, DWORD relay, 
1236                               DWORD glue, BYTE type ) 
1237 {
1238     THUNKLET *thunk; 
1239
1240     for (thunk = ThunkletAnchor; thunk; thunk = thunk->next)
1241         if (    thunk->type   == type
1242              && thunk->target == target
1243              && thunk->relay  == relay 
1244              && thunk->glue   == glue )
1245             return thunk;
1246
1247      return NULL;
1248 }
1249
1250 /***********************************************************************
1251  *     THUNK_AllocLSThunklet
1252  */
1253 FARPROC THUNK_AllocLSThunklet( SEGPTR target, DWORD relay, 
1254                                  FARPROC glue, HTASK16 owner ) 
1255 {
1256     THUNKLET *thunk = THUNK_FindThunklet( (DWORD)target, relay, (DWORD)glue,
1257                                           THUNKLET_TYPE_LS );
1258     if (!thunk)
1259     {
1260         TDB *pTask = (TDB*)GlobalLock16( owner );
1261
1262         if ( !(thunk = HeapAlloc( ThunkletHeap, 0, sizeof(THUNKLET) )) )
1263             return 0;
1264
1265         thunk->prefix_target = thunk->prefix_relay = 0x90;
1266         thunk->pushl_target  = thunk->pushl_relay  = 0x68;
1267         thunk->jmp_glue = 0xE9;
1268
1269         thunk->target  = (DWORD)target;
1270         thunk->relay   = (DWORD)relay;
1271         thunk->glue    = (DWORD)glue - (DWORD)&thunk->type;
1272
1273         thunk->type    = THUNKLET_TYPE_LS;
1274         thunk->owner   = pTask? pTask->hInstance : 0;
1275
1276         thunk->next    = ThunkletAnchor;
1277         ThunkletAnchor = thunk;
1278     }
1279
1280     return (FARPROC)thunk;
1281 }
1282
1283 /***********************************************************************
1284  *     THUNK_AllocSLThunklet
1285  */
1286 SEGPTR THUNK_AllocSLThunklet( FARPROC target, DWORD relay,
1287                               SEGPTR glue, HTASK16 owner )
1288 {
1289     THUNKLET *thunk = THUNK_FindThunklet( (DWORD)target, relay, (DWORD)glue,
1290                                           THUNKLET_TYPE_SL );
1291     if (!thunk)
1292     {
1293         TDB *pTask = (TDB*)GlobalLock16( owner );
1294
1295         if ( !(thunk = HeapAlloc( ThunkletHeap, 0, sizeof(THUNKLET) )) )
1296             return 0;
1297
1298         thunk->prefix_target = thunk->prefix_relay = 0x66;
1299         thunk->pushl_target  = thunk->pushl_relay  = 0x68;
1300         thunk->jmp_glue = 0xEA;
1301
1302         thunk->target  = (DWORD)target;
1303         thunk->relay   = (DWORD)relay;
1304         thunk->glue    = (DWORD)glue;
1305
1306         thunk->type    = THUNKLET_TYPE_SL;
1307         thunk->owner   = pTask? pTask->hInstance : 0;
1308
1309         thunk->next    = ThunkletAnchor;
1310         ThunkletAnchor = thunk;
1311     }
1312
1313     return HEAP_GetSegptr( ThunkletHeap, 0, thunk );
1314 }
1315
1316 /**********************************************************************
1317  *     IsLSThunklet
1318  */
1319 BOOL16 WINAPI IsLSThunklet( THUNKLET *thunk )
1320 {
1321     return    thunk->prefix_target == 0x90 && thunk->pushl_target == 0x68
1322            && thunk->prefix_relay  == 0x90 && thunk->pushl_relay  == 0x68
1323            && thunk->jmp_glue == 0xE9 && thunk->type == THUNKLET_TYPE_LS;
1324 }
1325
1326 /**********************************************************************
1327  *     IsSLThunklet                        (KERNEL.612)
1328  */
1329 BOOL16 WINAPI IsSLThunklet16( THUNKLET *thunk )
1330 {
1331     return    thunk->prefix_target == 0x66 && thunk->pushl_target == 0x68
1332            && thunk->prefix_relay  == 0x66 && thunk->pushl_relay  == 0x68
1333            && thunk->jmp_glue == 0xEA && thunk->type == THUNKLET_TYPE_SL;
1334 }
1335
1336
1337
1338 /***********************************************************************
1339  *     AllocLSThunkletSysthunk             (KERNEL.607)
1340  */
1341 FARPROC WINAPI AllocLSThunkletSysthunk16( SEGPTR target, 
1342                                           FARPROC relay, DWORD dummy )
1343 {
1344     return THUNK_AllocLSThunklet( (SEGPTR)relay, (DWORD)target, 
1345                                   ThunkletSysthunkGlueLS, GetCurrentTask() );
1346 }
1347
1348 /***********************************************************************
1349  *     AllocSLThunkletSysthunk             (KERNEL.608)
1350  */
1351 SEGPTR WINAPI AllocSLThunkletSysthunk16( FARPROC target, 
1352                                        SEGPTR relay, DWORD dummy )
1353 {
1354     return THUNK_AllocSLThunklet( (FARPROC)relay, (DWORD)target, 
1355                                   ThunkletSysthunkGlueSL, GetCurrentTask() );
1356 }
1357
1358
1359 /***********************************************************************
1360  *     AllocLSThunkletCallbackEx           (KERNEL.567)
1361  */
1362 FARPROC WINAPI AllocLSThunkletCallbackEx16( SEGPTR target, 
1363                                             DWORD relay, HTASK16 task )
1364 {
1365     THUNKLET *thunk = (THUNKLET *)PTR_SEG_TO_LIN( target );
1366     if (   IsSLThunklet16( thunk ) && thunk->relay == relay 
1367         && thunk->glue == (DWORD)ThunkletCallbackGlueSL )
1368         return (FARPROC)thunk->target;
1369
1370     return THUNK_AllocLSThunklet( target, relay, 
1371                                   ThunkletCallbackGlueLS, task );
1372 }
1373
1374 /***********************************************************************
1375  *     AllocSLThunkletCallbackEx           (KERNEL.568)
1376  */
1377 SEGPTR WINAPI AllocSLThunkletCallbackEx16( FARPROC target, 
1378                                          DWORD relay, HTASK16 task )
1379 {
1380     THUNKLET *thunk = (THUNKLET *)target;
1381     if (   IsLSThunklet( thunk ) && thunk->relay == relay 
1382         && thunk->glue == (DWORD)ThunkletCallbackGlueLS )
1383         return (SEGPTR)thunk->target;
1384
1385     return THUNK_AllocSLThunklet( target, relay, 
1386                                   ThunkletCallbackGlueSL, task );
1387 }
1388
1389 /***********************************************************************
1390  *     AllocLSThunkletCallback             (KERNEL.561) (KERNEL.606)
1391  */
1392 FARPROC WINAPI AllocLSThunkletCallback16( SEGPTR target, DWORD relay )
1393 {
1394     return AllocLSThunkletCallbackEx16( target, relay, GetCurrentTask() );
1395 }
1396
1397 /***********************************************************************
1398  *     AllocSLThunkletCallback             (KERNEL.562) (KERNEL.605)
1399  */
1400 SEGPTR WINAPI AllocSLThunkletCallback16( FARPROC target, DWORD relay )
1401 {
1402     return AllocSLThunkletCallbackEx16( target, relay, GetCurrentTask() );
1403 }
1404
1405 /***********************************************************************
1406  *     FindLSThunkletCallback              (KERNEL.563) (KERNEL.609)
1407  */
1408 FARPROC WINAPI FindLSThunkletCallback( SEGPTR target, DWORD relay )
1409 {
1410     THUNKLET *thunk = (THUNKLET *)PTR_SEG_TO_LIN( target );
1411     if (   thunk && IsSLThunklet16( thunk ) && thunk->relay == relay 
1412         && thunk->glue == (DWORD)ThunkletCallbackGlueSL )
1413         return (FARPROC)thunk->target;
1414
1415     thunk = THUNK_FindThunklet( (DWORD)target, relay, 
1416                                 (DWORD)ThunkletCallbackGlueLS, 
1417                                 THUNKLET_TYPE_LS );
1418     return (FARPROC)thunk;
1419 }
1420
1421 /***********************************************************************
1422  *     FindSLThunkletCallback              (KERNEL.564) (KERNEL.610)
1423  */
1424 SEGPTR WINAPI FindSLThunkletCallback( FARPROC target, DWORD relay )
1425 {
1426     THUNKLET *thunk = (THUNKLET *)target;
1427     if (   thunk && IsLSThunklet( thunk ) && thunk->relay == relay 
1428         && thunk->glue == (DWORD)ThunkletCallbackGlueLS )
1429         return (SEGPTR)thunk->target;
1430
1431     thunk = THUNK_FindThunklet( (DWORD)target, relay, 
1432                                 (DWORD)ThunkletCallbackGlueSL, 
1433                                 THUNKLET_TYPE_SL );
1434     return HEAP_GetSegptr( ThunkletHeap, 0, thunk );
1435 }
1436
1437
1438 /***********************************************************************
1439  * Callback Client API
1440  */
1441
1442 #define N_CBC_FIXED    20
1443 #define N_CBC_VARIABLE 10
1444 #define N_CBC_TOTAL    (N_CBC_FIXED + N_CBC_VARIABLE)
1445
1446 static SEGPTR    *CBClientRelay16[ N_CBC_TOTAL ];
1447 static FARPROC *CBClientRelay32[ N_CBC_TOTAL ];
1448
1449 /***********************************************************************
1450  *     RegisterCBClient                    (KERNEL.619)
1451  */
1452 INT16 WINAPI RegisterCBClient16( INT16 wCBCId, 
1453                                SEGPTR *relay16, FARPROC *relay32 )
1454 {
1455     /* Search for free Callback ID */
1456     if ( wCBCId == -1 )
1457         for ( wCBCId = N_CBC_FIXED; wCBCId < N_CBC_TOTAL; wCBCId++ )
1458             if ( !CBClientRelay16[ wCBCId ] )
1459                 break;
1460
1461     /* Register Callback ID */
1462     if ( wCBCId > 0 && wCBCId < N_CBC_TOTAL )
1463     {
1464         CBClientRelay16[ wCBCId ] = relay16;
1465         CBClientRelay32[ wCBCId ] = relay32;
1466     }
1467     else
1468         wCBCId = 0;
1469
1470     return wCBCId;
1471 }
1472
1473 /***********************************************************************
1474  *     UnRegisterCBClient                  (KERNEL.622)
1475  */
1476 INT16 WINAPI UnRegisterCBClient16( INT16 wCBCId, 
1477                                  SEGPTR *relay16, FARPROC *relay32 )
1478 {
1479     if (    wCBCId >= N_CBC_FIXED && wCBCId < N_CBC_TOTAL 
1480          && CBClientRelay16[ wCBCId ] == relay16 
1481          && CBClientRelay32[ wCBCId ] == relay32 )
1482     {
1483         CBClientRelay16[ wCBCId ] = 0;
1484         CBClientRelay32[ wCBCId ] = 0;
1485     }
1486     else
1487         wCBCId = 0;
1488
1489     return wCBCId;
1490 }
1491
1492
1493 /***********************************************************************
1494  *     InitCBClient                        (KERNEL.623)
1495  */
1496 void WINAPI InitCBClient16( FARPROC glueLS )
1497 {
1498     HMODULE16 kernel = GetModuleHandle16( "KERNEL" );
1499     SEGPTR glueSL = (SEGPTR)WIN32_GetProcAddress16( kernel, (LPCSTR)604 );
1500
1501     SetThunkletCallbackGlue16( glueLS, glueSL );
1502 }
1503
1504 /***********************************************************************
1505  *     CBClientGlueSL                      (KERNEL.604)
1506  */
1507 void WINAPI CBClientGlueSL( CONTEXT *context )
1508 {
1509     /* Create stack frame */
1510     SEGPTR stackSeg = STACK16_PUSH( THREAD_Current(), 12 );
1511     LPWORD stackLin = PTR_SEG_TO_LIN( stackSeg );
1512     SEGPTR glue;
1513     
1514     stackLin[3] = BP_reg( context );
1515     stackLin[2] = SI_reg( context );
1516     stackLin[1] = DI_reg( context );
1517     stackLin[0] = DS_reg( context );
1518
1519     BP_reg( context ) = OFFSETOF( stackSeg ) + 6;
1520     SP_reg( context ) = OFFSETOF( stackSeg ) - 4;
1521     GS_reg( context ) = 0;
1522
1523     /* Jump to 16-bit relay code */
1524     glue = CBClientRelay16[ stackLin[5] ][ stackLin[4] ];
1525     CS_reg ( context ) = SELECTOROF( glue );
1526     EIP_reg( context ) = OFFSETOF  ( glue );
1527 }
1528
1529 /***********************************************************************
1530  *     CBClientThunkSL                      (KERNEL.620)
1531  */
1532 void WINAPI CBClientThunkSL( CONTEXT *context )
1533 {
1534     /* Call 32-bit relay code */
1535     extern DWORD WINAPI CALL32_CBClient( FARPROC proc, LPWORD args );
1536
1537     LPWORD args = PTR_SEG_OFF_TO_LIN( SS_reg( context ), BP_reg( context ) );
1538     FARPROC proc = CBClientRelay32[ args[2] ][ args[1] ];
1539
1540     EAX_reg(context) = CALL32_CBClient( proc, args );
1541 }
1542
1543 /***********************************************************************
1544  *     CBClientThunkSLEx                    (KERNEL.621)
1545  */
1546 void WINAPI CBClientThunkSLEx( CONTEXT *context )
1547 {
1548     /* Call 32-bit relay code */
1549     extern DWORD WINAPI CALL32_CBClientEx( FARPROC proc, 
1550                                            LPWORD args, INT *nArgs );
1551
1552     LPWORD args = PTR_SEG_OFF_TO_LIN( SS_reg( context ), BP_reg( context ) );
1553     FARPROC proc = CBClientRelay32[ args[2] ][ args[1] ];
1554     INT nArgs;
1555     LPWORD stackLin;
1556
1557     EAX_reg(context) = CALL32_CBClientEx( proc, args, &nArgs );
1558
1559     /* Restore registers saved by CBClientGlueSL */
1560     stackLin = (LPWORD)((LPBYTE)CURRENT_STACK16 + sizeof(STACK16FRAME) - 4);
1561     BP_reg( context ) = stackLin[3];
1562     SI_reg( context ) = stackLin[2];
1563     DI_reg( context ) = stackLin[1];
1564     DS_reg( context ) = stackLin[0];
1565     SP_reg( context ) += 16+nArgs;
1566
1567     /* Return to caller of CBClient thunklet */
1568     CS_reg ( context ) = stackLin[9];
1569     EIP_reg( context ) = stackLin[8];
1570 }
1571