Fixed SearchPathA return value.
[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     THUNK *thunk = THUNK_Alloc( proc, (RELAY)CallTo16_word_wwwww );
558     if ( !thunk ) return NULL;
559
560     thunk = (THUNK*)SetTaskSignalProc( hTask, (FARPROC16)thunk );
561     if ( !thunk ) return NULL;
562
563     proc = thunk->proc;
564     THUNK_Free( thunk );
565     return proc;
566 }
567
568 /***********************************************************************
569  *           THUNK_CreateThread16   (KERNEL.441)
570  */
571 static DWORD CALLBACK THUNK_StartThread16( LPVOID threadArgs )
572 {
573     FARPROC16 start = ((FARPROC16 *)threadArgs)[0];
574     DWORD     param = ((DWORD *)threadArgs)[1];
575     HeapFree( GetProcessHeap(), 0, threadArgs );
576
577     return CallTo16_long_l( start, param );
578 }
579 HANDLE WINAPI THUNK_CreateThread16( SECURITY_ATTRIBUTES *sa, DWORD stack,
580                                       FARPROC16 start, SEGPTR param,
581                                       DWORD flags, LPDWORD id )
582 {
583     DWORD *threadArgs = HeapAlloc( GetProcessHeap(), 0, 2*sizeof(DWORD) );
584     if (!threadArgs) return INVALID_HANDLE_VALUE;
585     threadArgs[0] = (DWORD)start;
586     threadArgs[1] = (DWORD)param;
587
588     return CreateThread( sa, stack, THUNK_StartThread16, threadArgs, flags, id );
589 }
590
591 /***********************************************************************
592  *           THUNK_WOWCallback16Ex      (WOW32.3)(KERNEL32.55)
593  * Generic thunking routine to call 16 bit functions from 32bit code.
594  * 
595  * RETURNS
596  *      TRUE if the call was done
597  */
598 static BOOL WINAPI THUNK_WOWCallback16Ex(
599         FARPROC16 proc,         /* [in] 16bit function to call */
600         DWORD dwFlags,          /* [in] flags (WCB_*) */
601         DWORD cbArgs,           /* [in] number of arguments */
602         LPVOID xargs,           /* [in/out] arguments */
603         LPDWORD pdwret          /* [out] return value of the 16bit call */
604 ) {
605     LPDWORD     args = (LPDWORD)xargs;
606     DWORD       ret,i;
607
608     TRACE(relay,"(%p,0x%08lx,%ld,%p,%p)\n",
609         proc,dwFlags,cbArgs,xargs,pdwret
610     );
611     if (dwFlags == WCB16_CDECL) {
612         /* swap the arguments */
613         args = HeapAlloc(GetProcessHeap(),0,cbArgs*sizeof(DWORD));
614         for (i=0;i<cbArgs;i++)
615             args[i] = ((DWORD*)xargs)[cbArgs-i-1];
616     }
617     switch (cbArgs) {
618     case 0: ret = CallTo16_long_(proc);break;
619     case 1: ret = CallTo16_long_l(proc,args[0]);break;
620     case 2: ret = CallTo16_long_ll(proc,args[0],args[1]);break;
621     case 3: ret = CallTo16_long_lll(proc,args[0],args[1],args[2]);break;
622     case 4: ret = CallTo16_long_llll(proc,args[0],args[1],args[2],args[3]);
623             break;
624     case 5: ret = CallTo16_long_lllll(proc,args[0],args[1],args[2],args[3],
625                 args[4]
626             );
627             break;
628     case 6: ret = CallTo16_long_llllll(proc,args[0],args[1],args[2],args[3],
629                 args[4],args[5]
630             );
631             break;
632     case 7: ret = CallTo16_long_lllllll(proc,args[0],args[1],args[2],args[3],
633                 args[4],args[5],args[6]
634             );
635             break;
636     case 8: ret = CallTo16_long_llllllll(proc,args[0],args[1],args[2],args[3],
637                 args[4],args[5],args[6],args[7]
638             );
639             break;
640     case 9: ret = CallTo16_long_lllllllll(proc,args[0],args[1],args[2],args[3],
641                 args[4],args[5],args[6],args[7],args[8]
642             );
643             break;
644     case 10:ret = CallTo16_long_llllllllll(proc,args[0],args[1],args[2],args[3],
645                 args[4],args[5],args[6],args[7],args[8],args[9]
646             );
647             break;
648     case 11:ret = CallTo16_long_lllllllllll(proc,args[0],args[1],args[2],
649                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10]
650             );
651             break;
652     case 12:ret = CallTo16_long_llllllllllll(proc,args[0],args[1],args[2],
653                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],
654                 args[10],args[11]
655             );
656             break;
657     case 13:ret = CallTo16_long_lllllllllllll(proc,args[0],args[1],args[2],
658                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],
659                 args[10],args[11],args[12]
660             );
661             break;
662     case 14:ret = CallTo16_long_llllllllllllll(proc,args[0],args[1],args[2],
663                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],
664                 args[10],args[11],args[12],args[13]
665             );
666             break;
667     case 15:ret = CallTo16_long_lllllllllllllll(proc,args[0],args[1],args[2],
668                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],
669                 args[10],args[11],args[12],args[13],args[14]
670             );
671             break;
672     case 16:ret = CallTo16_long_llllllllllllllll(proc,args[0],args[1],args[2],
673                 args[3],args[4],args[5],args[6],args[7],args[8],args[9],
674                 args[10],args[11],args[12],args[13],args[14],args[15]
675             );
676             break;
677     default:
678             ERR(thunk,"%ld arguments not supported.\n",cbArgs);
679             if (dwFlags == WCB16_CDECL)
680                 HeapFree(GetProcessHeap(),0,args);
681             return FALSE;
682     }
683     if (dwFlags == WCB16_CDECL)
684         HeapFree(GetProcessHeap(),0,args);
685     if (pdwret) 
686         *pdwret = ret;
687     return TRUE;
688 }
689
690 /***********************************************************************
691  *           THUNK_MOUSE_Enable   (MOUSE.2)
692  */
693 static VOID WINAPI THUNK_CallMouseEventProc( FARPROC16 proc, 
694                                              DWORD dwFlags, DWORD dx, DWORD dy,
695                                              DWORD cButtons, DWORD dwExtraInfo )
696 {
697     CONTEXT context;
698
699     memset( &context, 0, sizeof(context) );
700     CS_reg(&context)  = SELECTOROF( proc );
701     EIP_reg(&context) = OFFSETOF( proc );
702     AX_reg(&context)  = (WORD)dwFlags;
703     BX_reg(&context)  = (WORD)dx;
704     CX_reg(&context)  = (WORD)dy;
705     DX_reg(&context)  = (WORD)cButtons;
706     SI_reg(&context)  = LOWORD( dwExtraInfo );
707     DI_reg(&context)  = HIWORD( dwExtraInfo );
708
709     CallTo16_sreg_( &context, 0 );
710 }
711 VOID WINAPI THUNK_MOUSE_Enable( FARPROC16 proc )
712 {
713     static THUNK *lastThunk = NULL;
714     static FARPROC16 lastProc = NULL;
715
716     if ( lastProc != proc )
717     {
718         if ( lastThunk ) 
719             THUNK_Free( lastThunk );
720
721         if ( !proc )
722             lastThunk = NULL;
723         else
724             lastThunk = THUNK_Alloc( proc, (RELAY)THUNK_CallMouseEventProc );
725
726         lastProc = proc;
727     }
728
729     return MOUSE_Enable( (LPMOUSE_EVENT_PROC)lastThunk );
730 }
731
732 /***********************************************************************
733  *           GetMouseEventProc   (USER.337)
734  */
735 FARPROC16 WINAPI GetMouseEventProc16(void)
736 {
737     HMODULE16 hmodule = GetModuleHandle16("USER");
738     return NE_GetEntryPoint( hmodule, NE_GetOrdinal( hmodule, "mouse_event" ));
739 }
740
741
742 /***********************************************************************
743  *           WIN16_mouse_event   (USER.299)
744  */
745 void WINAPI WIN16_mouse_event( CONTEXT *context )
746 {
747     mouse_event( AX_reg(context), BX_reg(context), CX_reg(context),
748                  DX_reg(context), MAKELONG(SI_reg(context), DI_reg(context)) );
749 }
750
751
752 /***********************************************************************
753  *           THUNK_KEYBD_Enable   (KEYBOARD.2)
754  */
755 static VOID WINAPI THUNK_CallKeybdEventProc( FARPROC16 proc, 
756                                              BYTE bVk, BYTE bScan,
757                                              DWORD dwFlags, DWORD dwExtraInfo )
758 {
759     CONTEXT context;
760
761     memset( &context, 0, sizeof(context) );
762     CS_reg(&context)  = SELECTOROF( proc );
763     EIP_reg(&context) = OFFSETOF( proc );
764     AH_reg(&context)  = (dwFlags & KEYEVENTF_KEYUP)? 0x80 : 0;
765     AL_reg(&context)  = bVk;
766     BH_reg(&context)  = (dwFlags & KEYEVENTF_EXTENDEDKEY)? 1 : 0;
767     BL_reg(&context)  = bScan;
768     SI_reg(&context)  = LOWORD( dwExtraInfo );
769     DI_reg(&context)  = HIWORD( dwExtraInfo );
770
771     CallTo16_sreg_( &context, 0 );
772 }
773 VOID WINAPI THUNK_KEYBOARD_Enable( FARPROC16 proc, LPBYTE lpKeyState )
774 {
775     static THUNK *lastThunk = NULL;
776     static FARPROC16 lastProc = NULL;
777
778     if ( lastProc != proc )
779     {
780         if ( lastThunk ) 
781             THUNK_Free( lastThunk );
782
783         if ( !proc )
784             lastThunk = NULL;
785         else
786             lastThunk = THUNK_Alloc( proc, (RELAY)THUNK_CallKeybdEventProc );
787
788         lastProc = proc;
789     }
790
791     return KEYBOARD_Enable( (LPKEYBD_EVENT_PROC)lastThunk, lpKeyState );
792 }
793
794 /***********************************************************************
795  *           WIN16_keybd_event   (USER.289)
796  */
797 void WINAPI WIN16_keybd_event( CONTEXT *context )
798 {
799     DWORD dwFlags = 0;
800     
801     if (AH_reg(context) & 0x80) dwFlags |= KEYEVENTF_KEYUP;
802     if (BH_reg(context) & 1   ) dwFlags |= KEYEVENTF_EXTENDEDKEY;
803
804     keybd_event( AL_reg(context), BL_reg(context), 
805                  dwFlags, MAKELONG(SI_reg(context), DI_reg(context)) );
806 }
807
808
809 /***********************************************************************
810  *           WIN16_CreateSystemTimer   (SYSTEM.2)
811  */
812 static void THUNK_CallSystemTimerProc( FARPROC16 proc, WORD timer )
813 {
814     CONTEXT context;
815     memset( &context, '\0', sizeof(context) );
816
817     CS_reg( &context ) = SELECTOROF( proc );
818     IP_reg( &context ) = OFFSETOF( proc );
819     BP_reg( &context ) = OFFSETOF( THREAD_Current()->cur_stack )
820                          + (WORD)&((STACK16FRAME*)0)->bp;
821
822     AX_reg( &context ) = timer;
823
824     if ( _ConfirmWin16Lock() )
825     {
826         FIXME( system, "Skipping timer %d callback because timer signal "
827                        "arrived while we own the Win16Lock!\n", timer );
828         return;
829     }
830
831     CallTo16_sreg_( &context, 0 ); 
832
833     /* FIXME: This does not work if the signal occurs while this thread
834               is currently in 16-bit code. With the current structure
835               of the Wine thunking code, this seems to be hard to fix ... */
836 }
837 WORD WINAPI WIN16_CreateSystemTimer( WORD rate, FARPROC16 proc )
838 {
839     THUNK *thunk = THUNK_Alloc( proc, (RELAY)THUNK_CallSystemTimerProc );
840     WORD timer = CreateSystemTimer( rate, (SYSTEMTIMERPROC)thunk );
841     if (!timer) THUNK_Free( thunk );
842     return timer;
843 }
844
845 /***********************************************************************
846  *           THUNK_InitCallout
847  */
848 void THUNK_InitCallout(void)
849 {
850     HMODULE hModule = GetModuleHandleA( "USER32" );
851     if ( hModule )
852     {
853 #define GETADDR( var, name )  \
854         *(FARPROC *)&Callout.##var = GetProcAddress( hModule, name )
855
856         GETADDR( PeekMessageA, "PeekMessageA" );
857         GETADDR( PeekMessageW, "PeekMessageW" );
858         GETADDR( GetMessageA, "GetMessageA" );
859         GETADDR( GetMessageW, "GetMessageW" );
860         GETADDR( SendMessageA, "SendMessageA" );
861         GETADDR( SendMessageW, "SendMessageW" );
862         GETADDR( PostMessageA, "PostMessageA" );
863         GETADDR( PostMessageW, "PostMessageW" );
864         GETADDR( PostThreadMessageA, "PostThreadMessageA" );
865         GETADDR( PostThreadMessageW, "PostThreadMessageW" );
866         GETADDR( TranslateMessage, "TranslateMessage" );
867         GETADDR( DispatchMessageW, "DispatchMessageW" );
868         GETADDR( DispatchMessageA, "DispatchMessageA" );
869         GETADDR( RedrawWindow, "RedrawWindow" );
870         GETADDR( UserSignalProc, "UserSignalProc" );
871
872 #undef GETADDR
873     }
874
875     hModule = GetModuleHandle16( "USER" );
876     if ( hModule )
877     {
878 #define GETADDR( var, name, thk )  \
879         *(FARPROC *)&Callout.##var = (FARPROC) \
880               THUNK_Alloc( WIN32_GetProcAddress16( hModule, name ), \
881                            (RELAY)CallTo16_##thk )
882
883         GETADDR( PeekMessage16, "PeekMessage", word_lwwww );
884         GETADDR( GetMessage16, "GetMessage", word_lwww );
885         GETADDR( SendMessage16, "SendMessage", long_wwwl );
886         GETADDR( PostMessage16, "PostMessage", word_wwwl );
887         GETADDR( PostAppMessage16, "PostAppMessage", word_wwwl );
888         GETADDR( TranslateMessage16, "TranslateMessage", word_l );
889         GETADDR( DispatchMessage16, "DispatchMessage", long_l );
890         GETADDR( RedrawWindow16, "RedrawWindow", word_wlww );
891         GETADDR( InitThreadInput16, "InitThreadInput", word_ww );
892         GETADDR( UserYield16, "UserYield", word_ );
893         GETADDR( DestroyIcon32, "DestroyIcon32", word_ww );
894
895 #undef GETADDR
896     }
897 }
898
899 /***********************************************************************
900  * 16->32 Flat Thunk routines:
901  */
902
903 /***********************************************************************
904  *              ThunkConnect16          (KERNEL.651)
905  * Connects a 32bit and a 16bit thunkbuffer.
906  */
907 UINT WINAPI ThunkConnect16(
908         LPSTR module16,              /* [in] name of win16 dll */
909         LPSTR module32,              /* [in] name of win32 dll */
910         HINSTANCE16 hInst16,         /* [in] hInst of win16 dll */
911         DWORD dwReason,              /* [in] initialisation argument */
912         struct ThunkDataCommon *TD,  /* [in/out] thunkbuffer */
913         LPSTR thunkfun32,            /* [in] win32 thunkfunction */
914         WORD cs                      /* [in] CS of win16 dll */
915 ) {
916     BOOL directionSL;
917
918     if (!lstrncmpA(TD->magic, "SL01", 4))
919     {
920         directionSL = TRUE;
921
922         TRACE(thunk, "SL01 thunk %s (%lx) -> %s (%s), Reason: %ld\n",
923                      module16, (DWORD)TD, module32, thunkfun32, dwReason);
924     }
925     else if (!lstrncmpA(TD->magic, "LS01", 4))
926     {
927         directionSL = FALSE;
928
929         TRACE(thunk, "LS01 thunk %s (%lx) <- %s (%s), Reason: %ld\n",
930                      module16, (DWORD)TD, module32, thunkfun32, dwReason);
931     }
932     else
933     {
934         ERR(thunk, "Invalid magic %c%c%c%c\n",
935                    TD->magic[0], TD->magic[1], TD->magic[2], TD->magic[3]);
936         return 0;
937     }
938
939     switch (dwReason)
940     {
941         case DLL_PROCESS_ATTACH:
942             if (directionSL)
943             {
944                 struct ThunkDataSL16 *SL16 = (struct ThunkDataSL16 *)TD;
945                 struct ThunkDataSL   *SL   = SL16->fpData;
946
947                 if (SL == NULL)
948                 {
949                     SL = HeapAlloc(GetProcessHeap(), 0, sizeof(*SL));
950
951                     SL->common   = SL16->common;
952                     SL->flags1   = SL16->flags1;
953                     SL->flags2   = SL16->flags2;
954
955                     SL->apiDB    = PTR_SEG_TO_LIN(SL16->apiDatabase);
956                     SL->targetDB = NULL;
957
958                     lstrcpynA(SL->pszDll16, module16, 255);
959                     lstrcpynA(SL->pszDll32, module32, 255);
960
961                     /* We should create a SEGPTR to the ThunkDataSL,
962                        but since the contents are not in the original format,
963                        any access to this by 16-bit code would crash anyway. */
964                     SL16->spData = 0;
965                     SL16->fpData = SL;
966                 }
967
968
969                 if (SL->flags2 & 0x80000000)
970                 {
971                     TRACE(thunk, "Preloading 32-bit library\n");
972                     LoadLibraryA(module32);
973                 }
974             }
975             else
976             {
977                 /* nothing to do */
978             }
979             break;
980
981         case DLL_PROCESS_DETACH:
982             /* FIXME: cleanup */
983             break;
984     }
985
986     return 1;
987 }
988
989
990 /***********************************************************************
991  *           C16ThkSL                           (KERNEL.630)
992  */
993
994 void WINAPI C16ThkSL(CONTEXT *context)
995 {
996     extern void CallFrom16_t_long_(void);
997     LPBYTE stub = PTR_SEG_TO_LIN(EAX_reg(context)), x = stub;
998     WORD cs, ds;
999     GET_CS(cs);
1000     GET_DS(ds);
1001
1002     /* We produce the following code:
1003      *
1004      *   mov ax, __FLATDS
1005      *   mov es, ax
1006      *   movzx ecx, cx
1007      *   mov edx, es:[ecx + $EDX]
1008      *   push bp
1009      *   push edx
1010      *   call __FLATCS:CallFrom16_t_long_
1011      */
1012
1013     *x++ = 0xB8; *((WORD *)x)++ = ds;
1014     *x++ = 0x8E; *x++ = 0xC0;
1015     *x++ = 0x66; *x++ = 0x0F; *x++ = 0xB7; *x++ = 0xC9;
1016     *x++ = 0x67; *x++ = 0x66; *x++ = 0x26; *x++ = 0x8B;
1017                  *x++ = 0x91; *((DWORD *)x)++ = EDX_reg(context);
1018
1019     *x++ = 0x55;
1020     *x++ = 0x66; *x++ = 0x52;
1021     *x++ = 0x66; *x++ = 0x9A; *((DWORD *)x)++ = (DWORD)CallFrom16_t_long_;
1022                               *((WORD *)x)++ = cs;
1023
1024     /* Jump to the stub code just created */
1025     IP_reg(context) = LOWORD(EAX_reg(context));
1026     CS_reg(context) = HIWORD(EAX_reg(context));
1027
1028     /* Since C16ThkSL got called by a jmp, we need to leave the
1029        orginal return address on the stack */
1030     SP_reg(context) -= 4;
1031 }
1032
1033 /***********************************************************************
1034  *           C16ThkSL01                         (KERNEL.631)
1035  */
1036
1037 void WINAPI C16ThkSL01(CONTEXT *context)
1038 {
1039     LPBYTE stub = PTR_SEG_TO_LIN(EAX_reg(context)), x = stub;
1040
1041     if (stub)
1042     {
1043         struct ThunkDataSL16 *SL16 = PTR_SEG_TO_LIN(EDX_reg(context));
1044         struct ThunkDataSL *td = SL16->fpData;
1045
1046         extern void CallFrom16_t_long_(void);
1047         DWORD procAddress = (DWORD)GetProcAddress16(GetModuleHandle16("KERNEL"), 631);
1048         WORD cs;
1049         GET_CS(cs);
1050
1051         if (!td)
1052         {
1053             ERR(thunk, "ThunkConnect16 was not called!\n");
1054             return;
1055         }
1056
1057         TRACE(thunk, "Creating stub for ThunkDataSL %08lx\n", (DWORD)td);
1058
1059
1060         /* We produce the following code:
1061          *
1062          *   xor eax, eax
1063          *   mov edx, $td
1064          *   call C16ThkSL01
1065          *   push bp
1066          *   push edx
1067          *   call __FLATCS:CallFrom16_t_long_
1068          */
1069
1070         *x++ = 0x66; *x++ = 0x33; *x++ = 0xC0;
1071         *x++ = 0x66; *x++ = 0xBA; *((DWORD *)x)++ = (DWORD)td;
1072         *x++ = 0x9A; *((DWORD *)x)++ = procAddress;
1073
1074         *x++ = 0x55;
1075         *x++ = 0x66; *x++ = 0x52;
1076         *x++ = 0x66; *x++ = 0x9A; *((DWORD *)x)++ = (DWORD)CallFrom16_t_long_;
1077                                   *((WORD *)x)++ = cs;
1078
1079         /* Jump to the stub code just created */
1080         IP_reg(context) = LOWORD(EAX_reg(context));
1081         CS_reg(context) = HIWORD(EAX_reg(context));
1082
1083         /* Since C16ThkSL01 got called by a jmp, we need to leave the
1084            orginal return address on the stack */
1085         SP_reg(context) -= 4;
1086     }
1087     else
1088     {
1089         struct ThunkDataSL *td = (struct ThunkDataSL *)EDX_reg(context);
1090         DWORD targetNr = CX_reg(context) / 4;
1091         struct SLTargetDB *tdb;
1092
1093         TRACE(thunk, "Process %08lx calling target %ld of ThunkDataSL %08lx\n",
1094                      (DWORD)PROCESS_Current(), targetNr, (DWORD)td);
1095
1096         for (tdb = td->targetDB; tdb; tdb = tdb->next)
1097             if (tdb->process == PROCESS_Current())
1098                 break;
1099
1100         if (!tdb)
1101         {
1102             TRACE(thunk, "Loading 32-bit library %s\n", td->pszDll32);
1103             LoadLibraryA(td->pszDll32);
1104
1105             for (tdb = td->targetDB; tdb; tdb = tdb->next)
1106                 if (tdb->process == PROCESS_Current())
1107                     break;
1108         }
1109
1110         if (tdb)
1111         {
1112             EDX_reg(context) = tdb->targetTable[targetNr];
1113
1114             TRACE(thunk, "Call target is %08lx\n", EDX_reg(context));
1115         }
1116         else
1117         {
1118             WORD *stack = PTR_SEG_OFF_TO_LIN(SS_reg(context), SP_reg(context));
1119             DX_reg(context) = HIWORD(td->apiDB[targetNr].errorReturnValue);
1120             AX_reg(context) = LOWORD(td->apiDB[targetNr].errorReturnValue);
1121             IP_reg(context) = stack[2];
1122             CS_reg(context) = stack[3];
1123             SP_reg(context) += td->apiDB[targetNr].nrArgBytes + 4;
1124
1125             ERR(thunk, "Process %08lx did not ThunkConnect32 %s to %s\n",
1126                        (DWORD)PROCESS_Current(), td->pszDll32, td->pszDll16);
1127         }
1128     }
1129 }
1130
1131 DWORD WINAPI 
1132 WOW16Call(WORD x,WORD y,WORD z) {
1133         int     i;
1134         DWORD   calladdr;
1135         FIXME(thunk,"(0x%04x,0x%04x,%d),calling (",x,y,z);
1136
1137         for (i=0;i<x/2;i++) {
1138                 WORD    a = STACK16_POP(THREAD_Current(),2);
1139                 DPRINTF("%04x ",a);
1140         }
1141         calladdr = STACK16_POP(THREAD_Current(),4);
1142         DPRINTF(") calling address was 0x%08lx\n",calladdr);
1143         return 0;
1144 }
1145
1146
1147 /***********************************************************************
1148  * 16<->32 Thunklet/Callback API:
1149  */
1150
1151 #pragma pack(1)
1152 typedef struct _THUNKLET
1153 {
1154     BYTE        prefix_target;
1155     BYTE        pushl_target;
1156     DWORD       target;
1157
1158     BYTE        prefix_relay;
1159     BYTE        pushl_relay;
1160     DWORD       relay;
1161
1162     BYTE        jmp_glue;
1163     DWORD       glue;
1164
1165     BYTE        type;
1166     HINSTANCE16 owner;
1167     struct _THUNKLET *next;
1168 } THUNKLET;
1169 #pragma pack(4)
1170
1171 #define THUNKLET_TYPE_LS  1
1172 #define THUNKLET_TYPE_SL  2
1173
1174 static HANDLE  ThunkletHeap = 0;
1175 static THUNKLET *ThunkletAnchor = NULL;
1176
1177 static FARPROC ThunkletSysthunkGlueLS = 0;
1178 static SEGPTR    ThunkletSysthunkGlueSL = 0;
1179
1180 static FARPROC ThunkletCallbackGlueLS = 0;
1181 static SEGPTR    ThunkletCallbackGlueSL = 0;
1182
1183 /***********************************************************************
1184  *     THUNK_ThunkletInit
1185  */
1186 static BOOL THUNK_ThunkletInit( void )
1187 {
1188     LPBYTE thunk;
1189
1190     ThunkletHeap = HeapCreate(HEAP_WINE_SEGPTR | HEAP_WINE_CODE16SEG, 0, 0);
1191     if (!ThunkletHeap) return FALSE;
1192
1193     thunk = HeapAlloc( ThunkletHeap, 0, 5 );
1194     if (!thunk) return FALSE;
1195     
1196     ThunkletSysthunkGlueLS = (FARPROC)thunk;
1197     *thunk++ = 0x58;                             /* popl eax */
1198     *thunk++ = 0xC3;                             /* ret      */
1199
1200     ThunkletSysthunkGlueSL = HEAP_GetSegptr( ThunkletHeap, 0, thunk );
1201     *thunk++ = 0x66; *thunk++ = 0x58;            /* popl eax */
1202     *thunk++ = 0xCB;                             /* lret     */
1203
1204     return TRUE;
1205 }
1206
1207 /***********************************************************************
1208  *     SetThunkletCallbackGlue             (KERNEL.560)
1209  */
1210 void WINAPI SetThunkletCallbackGlue16( FARPROC glueLS, SEGPTR glueSL )
1211 {
1212     ThunkletCallbackGlueLS = glueLS;
1213     ThunkletCallbackGlueSL = glueSL;
1214 }
1215
1216
1217 /***********************************************************************
1218  *     THUNK_FindThunklet
1219  */
1220 THUNKLET *THUNK_FindThunklet( DWORD target, DWORD relay, 
1221                               DWORD glue, BYTE type ) 
1222 {
1223     THUNKLET *thunk; 
1224
1225     for (thunk = ThunkletAnchor; thunk; thunk = thunk->next)
1226         if (    thunk->type   == type
1227              && thunk->target == target
1228              && thunk->relay  == relay 
1229              && thunk->glue   == glue )
1230             return thunk;
1231
1232      return NULL;
1233 }
1234
1235 /***********************************************************************
1236  *     THUNK_AllocLSThunklet
1237  */
1238 FARPROC THUNK_AllocLSThunklet( SEGPTR target, DWORD relay, 
1239                                  FARPROC glue, HTASK16 owner ) 
1240 {
1241     THUNKLET *thunk = THUNK_FindThunklet( (DWORD)target, relay, (DWORD)glue,
1242                                           THUNKLET_TYPE_LS );
1243     if (!thunk)
1244     {
1245         TDB *pTask = (TDB*)GlobalLock16( owner );
1246
1247         if ( !(thunk = HeapAlloc( ThunkletHeap, 0, sizeof(THUNKLET) )) )
1248             return 0;
1249
1250         thunk->prefix_target = thunk->prefix_relay = 0x90;
1251         thunk->pushl_target  = thunk->pushl_relay  = 0x68;
1252         thunk->jmp_glue = 0xE9;
1253
1254         thunk->target  = (DWORD)target;
1255         thunk->relay   = (DWORD)relay;
1256         thunk->glue    = (DWORD)glue - (DWORD)&thunk->type;
1257
1258         thunk->type    = THUNKLET_TYPE_LS;
1259         thunk->owner   = pTask? pTask->hInstance : 0;
1260
1261         thunk->next    = ThunkletAnchor;
1262         ThunkletAnchor = thunk;
1263     }
1264
1265     return (FARPROC)thunk;
1266 }
1267
1268 /***********************************************************************
1269  *     THUNK_AllocSLThunklet
1270  */
1271 SEGPTR THUNK_AllocSLThunklet( FARPROC target, DWORD relay,
1272                               SEGPTR glue, HTASK16 owner )
1273 {
1274     THUNKLET *thunk = THUNK_FindThunklet( (DWORD)target, relay, (DWORD)glue,
1275                                           THUNKLET_TYPE_SL );
1276     if (!thunk)
1277     {
1278         TDB *pTask = (TDB*)GlobalLock16( owner );
1279
1280         if ( !(thunk = HeapAlloc( ThunkletHeap, 0, sizeof(THUNKLET) )) )
1281             return 0;
1282
1283         thunk->prefix_target = thunk->prefix_relay = 0x66;
1284         thunk->pushl_target  = thunk->pushl_relay  = 0x68;
1285         thunk->jmp_glue = 0xEA;
1286
1287         thunk->target  = (DWORD)target;
1288         thunk->relay   = (DWORD)relay;
1289         thunk->glue    = (DWORD)glue;
1290
1291         thunk->type    = THUNKLET_TYPE_SL;
1292         thunk->owner   = pTask? pTask->hInstance : 0;
1293
1294         thunk->next    = ThunkletAnchor;
1295         ThunkletAnchor = thunk;
1296     }
1297
1298     return HEAP_GetSegptr( ThunkletHeap, 0, thunk );
1299 }
1300
1301 /**********************************************************************
1302  *     IsLSThunklet
1303  */
1304 BOOL16 WINAPI IsLSThunklet( THUNKLET *thunk )
1305 {
1306     return    thunk->prefix_target == 0x90 && thunk->pushl_target == 0x68
1307            && thunk->prefix_relay  == 0x90 && thunk->pushl_relay  == 0x68
1308            && thunk->jmp_glue == 0xE9 && thunk->type == THUNKLET_TYPE_LS;
1309 }
1310
1311 /**********************************************************************
1312  *     IsSLThunklet                        (KERNEL.612)
1313  */
1314 BOOL16 WINAPI IsSLThunklet16( THUNKLET *thunk )
1315 {
1316     return    thunk->prefix_target == 0x66 && thunk->pushl_target == 0x68
1317            && thunk->prefix_relay  == 0x66 && thunk->pushl_relay  == 0x68
1318            && thunk->jmp_glue == 0xEA && thunk->type == THUNKLET_TYPE_SL;
1319 }
1320
1321
1322
1323 /***********************************************************************
1324  *     AllocLSThunkletSysthunk             (KERNEL.607)
1325  */
1326 FARPROC WINAPI AllocLSThunkletSysthunk16( SEGPTR target, 
1327                                           FARPROC relay, DWORD dummy )
1328 {
1329     return THUNK_AllocLSThunklet( (SEGPTR)relay, (DWORD)target, 
1330                                   ThunkletSysthunkGlueLS, GetCurrentTask() );
1331 }
1332
1333 /***********************************************************************
1334  *     AllocSLThunkletSysthunk             (KERNEL.608)
1335  */
1336 SEGPTR WINAPI AllocSLThunkletSysthunk16( FARPROC target, 
1337                                        SEGPTR relay, DWORD dummy )
1338 {
1339     return THUNK_AllocSLThunklet( (FARPROC)relay, (DWORD)target, 
1340                                   ThunkletSysthunkGlueSL, GetCurrentTask() );
1341 }
1342
1343
1344 /***********************************************************************
1345  *     AllocLSThunkletCallbackEx           (KERNEL.567)
1346  */
1347 FARPROC WINAPI AllocLSThunkletCallbackEx16( SEGPTR target, 
1348                                             DWORD relay, HTASK16 task )
1349 {
1350     THUNKLET *thunk = (THUNKLET *)PTR_SEG_TO_LIN( target );
1351     if (   IsSLThunklet16( thunk ) && thunk->relay == relay 
1352         && thunk->glue == (DWORD)ThunkletCallbackGlueSL )
1353         return (FARPROC)thunk->target;
1354
1355     return THUNK_AllocLSThunklet( target, relay, 
1356                                   ThunkletCallbackGlueLS, task );
1357 }
1358
1359 /***********************************************************************
1360  *     AllocSLThunkletCallbackEx           (KERNEL.568)
1361  */
1362 SEGPTR WINAPI AllocSLThunkletCallbackEx16( FARPROC target, 
1363                                          DWORD relay, HTASK16 task )
1364 {
1365     THUNKLET *thunk = (THUNKLET *)target;
1366     if (   IsLSThunklet( thunk ) && thunk->relay == relay 
1367         && thunk->glue == (DWORD)ThunkletCallbackGlueLS )
1368         return (SEGPTR)thunk->target;
1369
1370     return THUNK_AllocSLThunklet( target, relay, 
1371                                   ThunkletCallbackGlueSL, task );
1372 }
1373
1374 /***********************************************************************
1375  *     AllocLSThunkletCallback             (KERNEL.561) (KERNEL.606)
1376  */
1377 FARPROC WINAPI AllocLSThunkletCallback16( SEGPTR target, DWORD relay )
1378 {
1379     return AllocLSThunkletCallbackEx16( target, relay, GetCurrentTask() );
1380 }
1381
1382 /***********************************************************************
1383  *     AllocSLThunkletCallback             (KERNEL.562) (KERNEL.605)
1384  */
1385 SEGPTR WINAPI AllocSLThunkletCallback16( FARPROC target, DWORD relay )
1386 {
1387     return AllocSLThunkletCallbackEx16( target, relay, GetCurrentTask() );
1388 }
1389
1390 /***********************************************************************
1391  *     FindLSThunkletCallback              (KERNEL.563) (KERNEL.609)
1392  */
1393 FARPROC WINAPI FindLSThunkletCallback( SEGPTR target, DWORD relay )
1394 {
1395     THUNKLET *thunk = (THUNKLET *)PTR_SEG_TO_LIN( target );
1396     if (   thunk && IsSLThunklet16( thunk ) && thunk->relay == relay 
1397         && thunk->glue == (DWORD)ThunkletCallbackGlueSL )
1398         return (FARPROC)thunk->target;
1399
1400     thunk = THUNK_FindThunklet( (DWORD)target, relay, 
1401                                 (DWORD)ThunkletCallbackGlueLS, 
1402                                 THUNKLET_TYPE_LS );
1403     return (FARPROC)thunk;
1404 }
1405
1406 /***********************************************************************
1407  *     FindSLThunkletCallback              (KERNEL.564) (KERNEL.610)
1408  */
1409 SEGPTR WINAPI FindSLThunkletCallback( FARPROC target, DWORD relay )
1410 {
1411     THUNKLET *thunk = (THUNKLET *)target;
1412     if (   thunk && IsLSThunklet( thunk ) && thunk->relay == relay 
1413         && thunk->glue == (DWORD)ThunkletCallbackGlueLS )
1414         return (SEGPTR)thunk->target;
1415
1416     thunk = THUNK_FindThunklet( (DWORD)target, relay, 
1417                                 (DWORD)ThunkletCallbackGlueSL, 
1418                                 THUNKLET_TYPE_SL );
1419     return HEAP_GetSegptr( ThunkletHeap, 0, thunk );
1420 }
1421
1422
1423 /***********************************************************************
1424  * Callback Client API
1425  */
1426
1427 #define N_CBC_FIXED    20
1428 #define N_CBC_VARIABLE 10
1429 #define N_CBC_TOTAL    (N_CBC_FIXED + N_CBC_VARIABLE)
1430
1431 static SEGPTR    *CBClientRelay16[ N_CBC_TOTAL ];
1432 static FARPROC *CBClientRelay32[ N_CBC_TOTAL ];
1433
1434 /***********************************************************************
1435  *     RegisterCBClient                    (KERNEL.619)
1436  */
1437 INT16 WINAPI RegisterCBClient16( INT16 wCBCId, 
1438                                SEGPTR *relay16, FARPROC *relay32 )
1439 {
1440     /* Search for free Callback ID */
1441     if ( wCBCId == -1 )
1442         for ( wCBCId = N_CBC_FIXED; wCBCId < N_CBC_TOTAL; wCBCId++ )
1443             if ( !CBClientRelay16[ wCBCId ] )
1444                 break;
1445
1446     /* Register Callback ID */
1447     if ( wCBCId > 0 && wCBCId < N_CBC_TOTAL )
1448     {
1449         CBClientRelay16[ wCBCId ] = relay16;
1450         CBClientRelay32[ wCBCId ] = relay32;
1451     }
1452     else
1453         wCBCId = 0;
1454
1455     return wCBCId;
1456 }
1457
1458 /***********************************************************************
1459  *     UnRegisterCBClient                  (KERNEL.622)
1460  */
1461 INT16 WINAPI UnRegisterCBClient16( INT16 wCBCId, 
1462                                  SEGPTR *relay16, FARPROC *relay32 )
1463 {
1464     if (    wCBCId >= N_CBC_FIXED && wCBCId < N_CBC_TOTAL 
1465          && CBClientRelay16[ wCBCId ] == relay16 
1466          && CBClientRelay32[ wCBCId ] == relay32 )
1467     {
1468         CBClientRelay16[ wCBCId ] = 0;
1469         CBClientRelay32[ wCBCId ] = 0;
1470     }
1471     else
1472         wCBCId = 0;
1473
1474     return wCBCId;
1475 }
1476
1477
1478 /***********************************************************************
1479  *     InitCBClient                        (KERNEL.623)
1480  */
1481 void WINAPI InitCBClient16( FARPROC glueLS )
1482 {
1483     HMODULE16 kernel = GetModuleHandle16( "KERNEL" );
1484     SEGPTR glueSL = (SEGPTR)WIN32_GetProcAddress16( kernel, (LPCSTR)604 );
1485
1486     SetThunkletCallbackGlue16( glueLS, glueSL );
1487 }
1488
1489 /***********************************************************************
1490  *     CBClientGlueSL                      (KERNEL.604)
1491  */
1492 void WINAPI CBClientGlueSL( CONTEXT *context )
1493 {
1494     /* Create stack frame */
1495     SEGPTR stackSeg = STACK16_PUSH( THREAD_Current(), 12 );
1496     LPWORD stackLin = PTR_SEG_TO_LIN( stackSeg );
1497     SEGPTR glue;
1498     
1499     stackLin[3] = BP_reg( context );
1500     stackLin[2] = SI_reg( context );
1501     stackLin[1] = DI_reg( context );
1502     stackLin[0] = DS_reg( context );
1503
1504     BP_reg( context ) = OFFSETOF( stackSeg ) + 6;
1505     SP_reg( context ) = OFFSETOF( stackSeg ) - 4;
1506     GS_reg( context ) = 0;
1507
1508     /* Jump to 16-bit relay code */
1509     glue = CBClientRelay16[ stackLin[5] ][ stackLin[4] ];
1510     CS_reg ( context ) = SELECTOROF( glue );
1511     EIP_reg( context ) = OFFSETOF  ( glue );
1512 }
1513
1514 /***********************************************************************
1515  *     CBClientThunkSL                      (KERNEL.620)
1516  */
1517 void WINAPI CBClientThunkSL( CONTEXT *context )
1518 {
1519     /* Call 32-bit relay code */
1520     extern DWORD WINAPI CALL32_CBClient( FARPROC proc, LPWORD args );
1521
1522     LPWORD args = PTR_SEG_OFF_TO_LIN( SS_reg( context ), BP_reg( context ) );
1523     FARPROC proc = CBClientRelay32[ args[2] ][ args[1] ];
1524
1525     EAX_reg(context) = CALL32_CBClient( proc, args );
1526 }
1527
1528 /***********************************************************************
1529  *     CBClientThunkSLEx                    (KERNEL.621)
1530  */
1531 void WINAPI CBClientThunkSLEx( CONTEXT *context )
1532 {
1533     /* Call 32-bit relay code */
1534     extern DWORD WINAPI CALL32_CBClientEx( FARPROC proc, 
1535                                            LPWORD args, INT *nArgs );
1536
1537     LPWORD args = PTR_SEG_OFF_TO_LIN( SS_reg( context ), BP_reg( context ) );
1538     FARPROC proc = CBClientRelay32[ args[2] ][ args[1] ];
1539     INT nArgs;
1540     LPWORD stackLin;
1541
1542     EAX_reg(context) = CALL32_CBClientEx( proc, args, &nArgs );
1543
1544     /* Restore registers saved by CBClientGlueSL */
1545     stackLin = (LPWORD)((LPBYTE)CURRENT_STACK16 + sizeof(STACK16FRAME) - 4);
1546     BP_reg( context ) = stackLin[3];
1547     SI_reg( context ) = stackLin[2];
1548     DI_reg( context ) = stackLin[1];
1549     DS_reg( context ) = stackLin[0];
1550     SP_reg( context ) += 16+nArgs;
1551
1552     /* Return to caller of CBClient thunklet */
1553     CS_reg ( context ) = stackLin[9];
1554     EIP_reg( context ) = stackLin[8];
1555 }
1556