wine_openpty is not properly declared (either missing or mismatched
[wine] / win32 / kernel32.c
1 /*
2  * KERNEL32 thunks and other undocumented stuff
3  *
4  * Copyright 1997-1998 Marcus Meissner
5  * Copyright 1998      Ulrich Weigand
6  *
7  * BUG: The GetBinaryType implementation is not complete. See
8  *      the function documentation for more details.
9  */
10
11 #include "windows.h"
12 #include "callback.h"
13 #include "resource.h"
14 #include "task.h"
15 #include "user.h"
16 #include "heap.h"
17 #include "module.h"
18 #include "process.h"
19 #include "stackframe.h"
20 #include "heap.h"
21 #include "selectors.h"
22 #include "task.h"
23 #include "win.h"
24 #include "file.h"
25 #include "debug.h"
26 #include "flatthunk.h"
27 #include "syslevel.h"
28 #include "winerror.h"
29
30
31 /***********************************************************************
32  *                                                                     *
33  *                 Win95 internal thunks                               *
34  *                                                                     *
35  ***********************************************************************/
36
37 /***********************************************************************
38  * Generates a FT_Prolog call.
39  *      
40  *  0FB6D1                  movzbl edx,cl
41  *  8B1495xxxxxxxx          mov edx,[4*edx + targetTable]
42  *  68xxxxxxxx              push FT_Prolog
43  *  C3                      lret
44  */
45 static void _write_ftprolog(LPBYTE relayCode ,DWORD *targetTable) {
46         LPBYTE  x;
47
48         x       = relayCode;
49         *x++    = 0x0f;*x++=0xb6;*x++=0xd1; /* movzbl edx,cl */
50         *x++    = 0x8B;*x++=0x14;*x++=0x95;*(DWORD**)x= targetTable;
51         x+=4;   /* mov edx, [4*edx + targetTable] */
52         *x++    = 0x68; *(DWORD*)x = (DWORD)GetProcAddress32(GetModuleHandle32A("KERNEL32"),"FT_Prolog");
53         x+=4;   /* push FT_Prolog */
54         *x++    = 0xC3;         /* lret */
55         /* fill rest with 0xCC / int 3 */
56 }
57
58 /***********************************************************************
59  *      _write_qtthunk                                  (internal)
60  * Generates a QT_Thunk style call.
61  *
62  *  33C9                    xor ecx, ecx
63  *  8A4DFC                  mov cl , [ebp-04]
64  *  8B148Dxxxxxxxx          mov edx, [4*ecx + targetTable]
65  *  B8yyyyyyyy              mov eax, QT_Thunk
66  *  FFE0                    jmp eax
67  */
68 static void _write_qtthunk(
69         LPBYTE relayCode,       /* [in] start of QT_Thunk stub */
70         DWORD *targetTable      /* [in] start of thunk (for index lookup) */
71 ) {
72         LPBYTE  x;
73
74         x       = relayCode;
75         *x++    = 0x33;*x++=0xC9; /* xor ecx,ecx */
76         *x++    = 0x8A;*x++=0x4D;*x++=0xFC; /* movb cl,[ebp-04] */
77         *x++    = 0x8B;*x++=0x14;*x++=0x8D;*(DWORD**)x= targetTable;
78         x+=4;   /* mov edx, [4*ecx + targetTable */
79         *x++    = 0xB8; *(DWORD*)x = (DWORD)GetProcAddress32(GetModuleHandle32A("KERNEL32"),"QT_Thunk");
80         x+=4;   /* mov eax , QT_Thunk */
81         *x++    = 0xFF; *x++ = 0xE0;    /* jmp eax */
82         /* should fill the rest of the 32 bytes with 0xCC */
83 }
84
85 /***********************************************************************
86  *           _loadthunk
87  */
88 static LPVOID _loadthunk(LPCSTR module, LPCSTR func, LPCSTR module32, 
89                          struct ThunkDataCommon *TD32, DWORD checksum)
90 {
91     struct ThunkDataCommon *TD16;
92     HMODULE32 hmod;
93     int ordinal;
94
95     if ((hmod = LoadLibrary16(module)) <= 32) 
96     {
97         ERR(thunk, "(%s, %s, %s): Unable to load '%s', error %d\n",
98                    module, func, module32, module, hmod);
99         return 0;
100     }
101
102     if (   !(ordinal = NE_GetOrdinal(hmod, func))
103         || !(TD16 = PTR_SEG_TO_LIN(NE_GetEntryPointEx(hmod, ordinal, FALSE))))
104     {
105         ERR(thunk, "(%s, %s, %s): Unable to find '%s'\n",
106                    module, func, module32, func);
107         return 0;
108     }
109
110     if (TD32 && memcmp(TD16->magic, TD32->magic, 4))
111     {
112         ERR(thunk, "(%s, %s, %s): Bad magic %c%c%c%c (should be %c%c%c%c)\n",
113                    module, func, module32, 
114                    TD16->magic[0], TD16->magic[1], TD16->magic[2], TD16->magic[3],
115                    TD32->magic[0], TD32->magic[1], TD32->magic[2], TD32->magic[3]);
116         return 0;
117     }
118
119     if (TD32 && TD16->checksum != TD32->checksum)
120     {
121         ERR(thunk, "(%s, %s, %s): Wrong checksum %08lx (should be %08lx)\n",
122                    module, func, module32, TD16->checksum, TD32->checksum);
123         return 0;
124     }
125
126     if (!TD32 && checksum && checksum != *(LPDWORD)TD16)
127     {
128         ERR(thunk, "(%s, %s, %s): Wrong checksum %08lx (should be %08lx)\n",
129                    module, func, module32, *(LPDWORD)TD16, checksum);
130         return 0;
131     }
132
133     return TD16;
134 }
135
136 /***********************************************************************
137  *           GetThunkStuff    (KERNEL32.53)
138  */
139 LPVOID WINAPI GetThunkStuff(LPSTR module, LPSTR func)
140 {
141     return _loadthunk(module, func, "<kernel>", NULL, 0L);
142 }
143
144 /***********************************************************************
145  *           GetThunkBuff    (KERNEL32.52)
146  * Returns a pointer to ThkBuf in the 16bit library SYSTHUNK.DLL.
147  */
148 LPVOID WINAPI GetThunkBuff(void)
149 {
150     return GetThunkStuff("SYSTHUNK.DLL", "ThkBuf");
151 }
152
153 /***********************************************************************
154  *              ThunkConnect32          (KERNEL32)
155  * Connects a 32bit and a 16bit thunkbuffer.
156  */
157 UINT32 WINAPI ThunkConnect32( 
158         struct ThunkDataCommon *TD,  /* [in/out] thunkbuffer */
159         LPSTR thunkfun16,            /* [in] win16 thunkfunction */
160         LPSTR module16,              /* [in] name of win16 dll */
161         LPSTR module32,              /* [in] name of win32 dll */
162         HMODULE32 hmod32,            /* [in] hmodule of win32 dll */
163         DWORD dwReason               /* [in] initialisation argument */
164 ) {
165     BOOL32 directionSL;
166
167     if (!lstrncmp32A(TD->magic, "SL01", 4))
168     {
169         directionSL = TRUE;
170
171         TRACE(thunk, "SL01 thunk %s (%lx) <- %s (%s), Reason: %ld\n",
172                      module32, (DWORD)TD, module16, thunkfun16, dwReason);
173     }
174     else if (!lstrncmp32A(TD->magic, "LS01", 4))
175     {
176         directionSL = FALSE;
177
178         TRACE(thunk, "LS01 thunk %s (%lx) -> %s (%s), Reason: %ld\n",
179                      module32, (DWORD)TD, module16, thunkfun16, dwReason);
180     }
181     else
182     {
183         ERR(thunk, "Invalid magic %c%c%c%c\n", 
184                    TD->magic[0], TD->magic[1], TD->magic[2], TD->magic[3]);
185         return 0;
186     }
187     
188     switch (dwReason)
189     {
190         case DLL_PROCESS_ATTACH:
191         {
192             struct ThunkDataCommon *TD16;
193             if (!(TD16 = _loadthunk(module16, thunkfun16, module32, TD, 0L)))
194                 return 0;
195
196             if (directionSL)
197             {
198                 struct ThunkDataSL32 *SL32 = (struct ThunkDataSL32 *)TD;
199                 struct ThunkDataSL16 *SL16 = (struct ThunkDataSL16 *)TD16;
200                 struct SLTargetDB *tdb;
201
202                 if (SL16->fpData == NULL)
203                 {
204                     ERR(thunk, "ThunkConnect16 was not called!\n");
205                     return 0;
206                 }
207
208                 SL32->data = SL16->fpData;
209
210                 tdb = HeapAlloc(GetProcessHeap(), 0, sizeof(*tdb));
211                 tdb->process = PROCESS_Current();
212                 tdb->targetTable = (DWORD *)(thunkfun16 + SL32->offsetTargetTable);
213
214                 tdb->next = SL32->data->targetDB;   /* FIXME: not thread-safe! */
215                 SL32->data->targetDB = tdb;
216
217                 TRACE(thunk, "Process %08lx allocated TargetDB entry for ThunkDataSL %08lx\n", 
218                              (DWORD)PROCESS_Current(), (DWORD)SL32->data);
219             }
220             else
221             {
222                 struct ThunkDataLS32 *LS32 = (struct ThunkDataLS32 *)TD;
223                 struct ThunkDataLS16 *LS16 = (struct ThunkDataLS16 *)TD16;
224
225                 LS32->targetTable = PTR_SEG_TO_LIN(LS16->targetTable);
226
227                 /* write QT_Thunk and FT_Prolog stubs */
228                 _write_qtthunk ((LPBYTE)TD + LS32->offsetQTThunk,  LS32->targetTable);
229                 _write_ftprolog((LPBYTE)TD + LS32->offsetFTProlog, LS32->targetTable);
230             }
231             break;
232         }
233
234         case DLL_PROCESS_DETACH:
235             /* FIXME: cleanup */
236             break;
237     }
238
239     return 1;
240 }
241
242 /**********************************************************************
243  *              QT_Thunk                        (KERNEL32)
244  *
245  * The target address is in EDX.
246  * The 16 bit arguments start at ESP+4.
247  * The number of 16bit argumentbytes is EBP-ESP-0x44 (68 Byte thunksetup).
248  * [ok]
249  */
250 REGS_ENTRYPOINT(QT_Thunk)
251 {
252     CONTEXT context16;
253     DWORD argsize;
254     THDB *thdb = THREAD_Current();
255
256     memcpy(&context16,context,sizeof(context16));
257
258     CS_reg(&context16)  = HIWORD(EDX_reg(context));
259     IP_reg(&context16)  = LOWORD(EDX_reg(context));
260     EBP_reg(&context16) = OFFSETOF( thdb->cur_stack )
261                            + (WORD)&((STACK16FRAME*)0)->bp;
262
263     argsize = EBP_reg(context)-ESP_reg(context)-0x44;
264
265     memcpy( ((LPBYTE)THREAD_STACK16(thdb))-argsize,
266             (LPBYTE)ESP_reg(context)+4, argsize );
267
268     EAX_reg(context) = Callbacks->CallRegisterShortProc( &context16, argsize );
269     EDX_reg(context) = HIWORD(EAX_reg(context));
270     EAX_reg(context) = LOWORD(EAX_reg(context));
271 }
272
273
274 /**********************************************************************
275  *              FT_Prolog                       (KERNEL32.233)
276  * 
277  * The set of FT_... thunk routines is used instead of QT_Thunk,
278  * if structures have to be converted from 32-bit to 16-bit
279  * (change of member alignment, conversion of members).
280  *
281  * The thunk function (as created by the thunk compiler) calls
282  * FT_Prolog at the beginning, to set up a stack frame and
283  * allocate a 64 byte buffer on the stack.
284  * The input parameters (target address and some flags) are
285  * saved for later use by FT_Thunk.
286  *
287  * Input:  EDX  16-bit target address (SEGPTR)
288  *         CX   bits  0..7   target number (in target table)
289  *              bits  8..9   some flags (unclear???)
290  *              bits 10..15  number of DWORD arguments
291  *
292  * Output: A new stackframe is created, and a 64 byte buffer
293  *         allocated on the stack. The layout of the stack 
294  *         on return is as follows:
295  *
296  *  (ebp+4)  return address to caller of thunk function
297  *  (ebp)    old EBP
298  *  (ebp-4)  saved EBX register of caller
299  *  (ebp-8)  saved ESI register of caller
300  *  (ebp-12) saved EDI register of caller
301  *  (ebp-16) saved ECX register, containing flags
302  *  (ebp-20) bitmap containing parameters that are to be converted
303  *           by FT_Thunk; it is initialized to 0 by FT_Prolog and
304  *           filled in by the thunk code before calling FT_Thunk
305  *  (ebp-24)
306  *    ...    (unclear)
307  *  (ebp-44)
308  *  (ebp-48) saved EAX register of caller (unclear, never restored???)
309  *  (ebp-52) saved EDX register, containing 16-bit thunk target
310  *  (ebp-56)
311  *    ...    (unclear)
312  *  (ebp-64)
313  *
314  *  ESP is EBP-68 on return.
315  *         
316  */
317
318 REGS_ENTRYPOINT(FT_Prolog)
319 {
320     /* Pop return address to thunk code */
321     EIP_reg(context) = STACK32_POP(context);
322
323     /* Build stack frame */
324     STACK32_PUSH(context, EBP_reg(context));
325     EBP_reg(context) = ESP_reg(context);
326
327     /* Allocate 64-byte Thunk Buffer */
328     ESP_reg(context) -= 64;
329     memset((char *)ESP_reg(context), '\0', 64);
330
331     /* Store Flags (ECX) and Target Address (EDX) */
332     /* Save other registers to be restored later */
333     *(DWORD *)(EBP_reg(context) -  4) = EBX_reg(context);
334     *(DWORD *)(EBP_reg(context) -  8) = ESI_reg(context);
335     *(DWORD *)(EBP_reg(context) - 12) = EDI_reg(context);
336     *(DWORD *)(EBP_reg(context) - 16) = ECX_reg(context);
337
338     *(DWORD *)(EBP_reg(context) - 48) = EAX_reg(context);
339     *(DWORD *)(EBP_reg(context) - 52) = EDX_reg(context);
340     
341     /* Push return address back onto stack */
342     STACK32_PUSH(context, EIP_reg(context));
343 }
344
345 /**********************************************************************
346  *              FT_Thunk                        (KERNEL32.234)
347  *
348  * This routine performs the actual call to 16-bit code, 
349  * similar to QT_Thunk. The differences are:
350  *  - The call target is taken from the buffer created by FT_Prolog
351  *  - Those arguments requested by the thunk code (by setting the
352  *    corresponding bit in the bitmap at EBP-20) are converted
353  *    from 32-bit pointers to segmented pointers (those pointers
354  *    are guaranteed to point to structures copied to the stack
355  *    by the thunk code, so we always use the 16-bit stack selector
356  *    for those addresses).
357  * 
358  *    The bit #i of EBP-20 corresponds here to the DWORD starting at
359  *    ESP+4 + 2*i.
360  * 
361  * FIXME: It is unclear what happens if there are more than 32 WORDs 
362  *        of arguments, so that the single DWORD bitmap is no longer
363  *        sufficient ...
364  */
365
366 REGS_ENTRYPOINT(FT_Thunk)
367 {
368     DWORD mapESPrelative = *(DWORD *)(EBP_reg(context) - 20);
369     DWORD callTarget     = *(DWORD *)(EBP_reg(context) - 52);
370
371     CONTEXT context16;
372     DWORD i, argsize;
373     LPBYTE newstack, oldstack;
374     THDB *thdb = THREAD_Current();
375
376     memcpy(&context16,context,sizeof(context16));
377
378     CS_reg(&context16)  = HIWORD(callTarget);
379     IP_reg(&context16)  = LOWORD(callTarget);
380     EBP_reg(&context16) = OFFSETOF( thdb->cur_stack )
381                            + (WORD)&((STACK16FRAME*)0)->bp;
382
383     argsize  = EBP_reg(context)-ESP_reg(context)-0x44;
384     newstack = ((LPBYTE)THREAD_STACK16(thdb))-argsize;
385     oldstack = (LPBYTE)ESP_reg(context)+4;
386
387     memcpy( newstack, oldstack, argsize );
388
389     for (i = 0; i < 32; i++)    /* NOTE: What about > 32 arguments? */
390         if (mapESPrelative & (1 << i))
391         {
392             SEGPTR *arg = (SEGPTR *)(newstack + 2*i);
393             *arg = PTR_SEG_OFF_TO_SEGPTR(SELECTOROF(thdb->cur_stack), 
394                                          OFFSETOF(thdb->cur_stack) - argsize
395                                          + (*(LPBYTE *)arg - oldstack));
396         }
397
398     EAX_reg(context) = Callbacks->CallRegisterShortProc( &context16, argsize );
399     EDX_reg(context) = HIWORD(EAX_reg(context));
400     EAX_reg(context) = LOWORD(EAX_reg(context));
401 }
402
403 /**********************************************************************
404  *              FT_ExitNN               (KERNEL32.218 - 232)
405  *
406  * One of the FT_ExitNN functions is called at the end of the thunk code.
407  * It removes the stack frame created by FT_Prolog, moves the function
408  * return from EBX to EAX (yes, FT_Thunk did use EAX for the return 
409  * value, but the thunk code has moved it from EAX to EBX in the 
410  * meantime ... :-), restores the caller's EBX, ESI, and EDI registers,
411  * and perform a return to the CALLER of the thunk code (while removing
412  * the given number of arguments from the caller's stack).
413  */
414
415 static void FT_Exit(CONTEXT *context, int nPopArgs)
416 {
417     /* Return value is in EBX */
418     EAX_reg(context) = EBX_reg(context);
419
420     /* Restore EBX, ESI, and EDI registers */
421     EBX_reg(context) = *(DWORD *)(EBP_reg(context) -  4);
422     ESI_reg(context) = *(DWORD *)(EBP_reg(context) -  8);
423     EDI_reg(context) = *(DWORD *)(EBP_reg(context) - 12);
424
425     /* Clean up stack frame */
426     ESP_reg(context) = EBP_reg(context);
427     EBP_reg(context) = STACK32_POP(context);
428
429     /* Pop return address to CALLER of thunk code */
430     EIP_reg(context) = STACK32_POP(context);
431     /* Remove arguments */
432     ESP_reg(context) += nPopArgs;
433     /* Push return address back onto stack */
434     STACK32_PUSH(context, EIP_reg(context));
435 }
436
437 REGS_ENTRYPOINT(FT_Exit0)  { FT_Exit(context,  0); }
438 REGS_ENTRYPOINT(FT_Exit4)  { FT_Exit(context,  4); }
439 REGS_ENTRYPOINT(FT_Exit8)  { FT_Exit(context,  8); }
440 REGS_ENTRYPOINT(FT_Exit12) { FT_Exit(context, 12); }
441 REGS_ENTRYPOINT(FT_Exit16) { FT_Exit(context, 16); }
442 REGS_ENTRYPOINT(FT_Exit20) { FT_Exit(context, 20); }
443 REGS_ENTRYPOINT(FT_Exit24) { FT_Exit(context, 24); }
444 REGS_ENTRYPOINT(FT_Exit28) { FT_Exit(context, 28); }
445 REGS_ENTRYPOINT(FT_Exit32) { FT_Exit(context, 32); }
446 REGS_ENTRYPOINT(FT_Exit36) { FT_Exit(context, 36); }
447 REGS_ENTRYPOINT(FT_Exit40) { FT_Exit(context, 40); }
448 REGS_ENTRYPOINT(FT_Exit44) { FT_Exit(context, 44); }
449 REGS_ENTRYPOINT(FT_Exit48) { FT_Exit(context, 48); }
450 REGS_ENTRYPOINT(FT_Exit52) { FT_Exit(context, 52); }
451 REGS_ENTRYPOINT(FT_Exit56) { FT_Exit(context, 56); }
452
453
454 /**********************************************************************
455  *           WOWCallback16 (KERNEL32.62)(WOW32.2)
456  * Calls a win16 function with a single DWORD argument.
457  * RETURNS
458  *      the return value
459  */
460 DWORD WINAPI WOWCallback16(
461         FARPROC16 fproc,        /* [in] win16 function to call */
462         DWORD arg               /* [in] single DWORD argument to function */
463 ) {
464         DWORD   ret;
465         TRACE(thunk,"(%p,0x%08lx)...\n",fproc,arg);
466         ret =  Callbacks->CallWOWCallbackProc(fproc,arg);
467         TRACE(thunk,"... returns %ld\n",ret);
468         return ret;
469 }
470
471 /**********************************************************************
472  *           WOWCallback16Ex (KERNEL32.55)(WOW32.3)
473  * Calls a function in 16bit code.
474  * RETURNS
475  *      TRUE for success
476  */
477 BOOL32 WINAPI WOWCallback16Ex(
478         FARPROC16 vpfn16,       /* [in] win16 function to call */
479         DWORD dwFlags,          /* [in] flags */
480         DWORD cbArgs,           /* [in] nr of arguments */
481         LPVOID pArgs,           /* [in] pointer to arguments (LPDWORD) */
482         LPDWORD pdwRetCode      /* [out] return value of win16 function */
483 ) {
484         return Callbacks->CallWOWCallback16Ex(vpfn16,dwFlags,cbArgs,pArgs,pdwRetCode);
485 }
486
487 /***********************************************************************
488  *              ThunkInitLS     (KERNEL32.43)
489  * A thunkbuffer link routine 
490  * The thunkbuf looks like:
491  *
492  *      00: DWORD       length          ? don't know exactly
493  *      04: SEGPTR      ptr             ? where does it point to?
494  * The pointer ptr is written into the first DWORD of 'thunk'.
495  * (probably correct implemented)
496  * [ok probably]
497  * RETURNS
498  *      segmented pointer to thunk?
499  */
500 DWORD WINAPI ThunkInitLS(
501         LPDWORD thunk,  /* [in] win32 thunk */
502         LPCSTR thkbuf,  /* [in] thkbuffer name in win16 dll */
503         DWORD len,      /* [in] thkbuffer length */
504         LPCSTR dll16,   /* [in] name of win16 dll */
505         LPCSTR dll32    /* [in] name of win32 dll (FIXME: not used?) */
506 ) {
507         LPDWORD         addr;
508
509         if (!(addr = _loadthunk( dll16, thkbuf, dll32, NULL, len )))
510                 return 0;
511
512         if (!addr[1])
513                 return 0;
514         *(DWORD*)thunk = addr[1];
515
516         return addr[1];
517 }
518
519 /***********************************************************************
520  *              Common32ThkLS   (KERNEL32.45)
521  * 
522  * This is another 32->16 thunk, independent of the QT_Thunk/FT_Thunk
523  * style thunks. The basic difference is that the parameter conversion 
524  * is done completely on the *16-bit* side here. Thus we do not call
525  * the 16-bit target directly, but call a common entry point instead.
526  * This entry function then calls the target according to the target
527  * number passed in the DI register.
528  * 
529  * Input:  EAX    SEGPTR to the common 16-bit entry point
530  *         CX     offset in thunk table (target number * 4)
531  *         DX     error return value if execution fails (unclear???)
532  *         EDX.HI number of DWORD parameters
533  *
534  * (Note that we need to move the thunk table offset from CX to DI !)
535  *
536  * The called 16-bit stub expects its stack to look like this:
537  *     ...
538  *   (esp+40)  32-bit arguments
539  *     ...
540  *   (esp+8)   32 byte of stack space available as buffer
541  *   (esp)     8 byte return address for use with 0x66 lret 
542  * 
543  * The called 16-bit stub uses a 0x66 lret to return to 32-bit code,
544  * and uses the EAX register to return a DWORD return value.
545  * Thus we need to use a special assembly glue routine 
546  * (CallRegisterLongProc instead of CallRegisterShortProc).
547  *
548  * Finally, we return to the caller, popping the arguments off 
549  * the stack.
550  *
551  * FIXME: The called function uses EBX to return the number of 
552  *        arguments that are to be popped off the caller's stack.
553  *        This is clobbered by the assembly glue, so we simply use
554  *        the original EDX.HI to get the number of arguments.
555  *        (Those two values should be equal anyway ...?)
556  * 
557  */
558 REGS_ENTRYPOINT(Common32ThkLS)
559 {
560     CONTEXT context16;
561     DWORD argsize;
562     THDB *thdb = THREAD_Current();
563
564     memcpy(&context16,context,sizeof(context16));
565
566     DI_reg(&context16)  = CX_reg(context);
567     CS_reg(&context16)  = HIWORD(EAX_reg(context));
568     IP_reg(&context16)  = LOWORD(EAX_reg(context));
569     EBP_reg(&context16) = OFFSETOF( thdb->cur_stack )
570                            + (WORD)&((STACK16FRAME*)0)->bp;
571
572     argsize = HIWORD(EDX_reg(context)) * 4;
573
574     /* FIXME: hack for stupid USER32 CallbackGlueLS routine */
575     if (EDX_reg(context) == EIP_reg(context))
576         argsize = 6 * 4;
577
578     memcpy( ((LPBYTE)THREAD_STACK16(thdb))-argsize,
579             (LPBYTE)ESP_reg(context)+4, argsize );
580
581     EAX_reg(context) = Callbacks->CallRegisterLongProc(&context16, argsize + 32);
582
583     /* Clean up caller's stack frame */
584
585     EIP_reg(context) = STACK32_POP(context);
586     ESP_reg(context) += argsize;
587     STACK32_PUSH(context, EIP_reg(context));
588 }
589
590 /***********************************************************************
591  *              OT_32ThkLSF     (KERNEL32.40)
592  *
593  * YET Another 32->16 thunk. The difference to Common32ThkLS is that
594  * argument processing is done on both the 32-bit and the 16-bit side:
595  * The 32-bit side prepares arguments, copying them onto the stack.
596  * 
597  * When this routine is called, the first word on the stack is the 
598  * number of argument bytes prepared by the 32-bit code, and EDX
599  * contains the 16-bit target address.
600  *
601  * The called 16-bit routine is another relaycode, doing further 
602  * argument processing and then calling the real 16-bit target
603  * whose address is stored at [bp-04].
604  *
605  * The call proceeds using a normal CallRegisterShortProc.
606  * After return from the 16-bit relaycode, the arguments need
607  * to be copied *back* to the 32-bit stack, since the 32-bit
608  * relaycode processes output parameters.
609  * 
610  * Note that we copy twice the number of arguments, since some of the
611  * 16-bit relaycodes in SYSTHUNK.DLL directly access the original
612  * arguments of the caller!
613  *
614  * (Note that this function seems only to be used for
615  *  OLECLI32 -> OLECLI and OLESVR32 -> OLESVR thunking.)
616  */
617 REGS_ENTRYPOINT(OT_32ThkLSF)
618 {
619     CONTEXT context16;
620     DWORD argsize;
621     THDB *thdb = THREAD_Current();
622
623     memcpy(&context16,context,sizeof(context16));
624
625     CS_reg(&context16)  = HIWORD(EDX_reg(context));
626     IP_reg(&context16)  = LOWORD(EDX_reg(context));
627     EBP_reg(&context16) = OFFSETOF( thdb->cur_stack )
628                            + (WORD)&((STACK16FRAME*)0)->bp;
629
630     argsize = 2 * *(WORD *)(ESP_reg(context) + 4) + 2;
631
632     memcpy( ((LPBYTE)THREAD_STACK16(thdb))-argsize,
633             (LPBYTE)ESP_reg(context)+4, argsize );
634
635     EAX_reg(context) = Callbacks->CallRegisterShortProc(&context16, argsize);
636
637     memcpy( (LPBYTE)ESP_reg(context)+4, 
638             ((LPBYTE)THREAD_STACK16(thdb))-argsize, argsize );
639 }
640
641 /***********************************************************************
642  *              ThunkInitLSF            (KERNEL32.41)
643  * A thunk setup routine.
644  * Expects a pointer to a preinitialized thunkbuffer in the first argument
645  * looking like:
646  *      00..03:         unknown (pointer, check _41, _43, _46)
647  *      04: EB1E                jmp +0x20
648  *
649  *      06..23:         unknown (space for replacement code, check .90)
650  *
651  *      24:>E800000000          call offset 29
652  *      29:>58                  pop eax            ( target of call )
653  *      2A: 2D25000000          sub eax,0x00000025 ( now points to offset 4 )
654  *      2F: BAxxxxxxxx          mov edx,xxxxxxxx
655  *      34: 68yyyyyyyy          push KERNEL32.90
656  *      39: C3                  ret
657  *
658  *      3A: EB1E                jmp +0x20
659  *      3E ... 59:      unknown (space for replacement code?)
660  *      5A: E8xxxxxxxx          call <32bitoffset xxxxxxxx>
661  *      5F: 5A                  pop edx
662  *      60: 81EA25xxxxxx        sub edx, 0x25xxxxxx
663  *      66: 52                  push edx
664  *      67: 68xxxxxxxx          push xxxxxxxx
665  *      6C: 68yyyyyyyy          push KERNEL32.89
666  *      71: C3                  ret
667  *      72: end?
668  * This function checks if the code is there, and replaces the yyyyyyyy entries
669  * by the functionpointers.
670  * The thunkbuf looks like:
671  *
672  *      00: DWORD       length          ? don't know exactly
673  *      04: SEGPTR      ptr             ? where does it point to?
674  * The segpointer ptr is written into the first DWORD of 'thunk'.
675  * [ok probably]
676  * RETURNS
677  *      unclear, pointer to win16 thkbuffer?
678  */
679 LPVOID WINAPI ThunkInitLSF(
680         LPBYTE thunk,   /* [in] win32 thunk */
681         LPCSTR thkbuf,  /* [in] thkbuffer name in win16 dll */
682         DWORD len,      /* [in] length of thkbuffer */
683         LPCSTR dll16,   /* [in] name of win16 dll */
684         LPCSTR dll32    /* [in] name of win32 dll */
685 ) {
686         HMODULE32       hkrnl32 = GetModuleHandle32A("KERNEL32");
687         LPDWORD         addr,addr2;
688
689         /* FIXME: add checks for valid code ... */
690         /* write pointers to kernel32.89 and kernel32.90 (+ordinal base of 1) */
691         *(DWORD*)(thunk+0x35) = (DWORD)GetProcAddress32(hkrnl32,(LPSTR)90);
692         *(DWORD*)(thunk+0x6D) = (DWORD)GetProcAddress32(hkrnl32,(LPSTR)89);
693
694         
695         if (!(addr = _loadthunk( dll16, thkbuf, dll32, NULL, len )))
696                 return 0;
697
698         addr2 = PTR_SEG_TO_LIN(addr[1]);
699         if (HIWORD(addr2))
700                 *(DWORD*)thunk = (DWORD)addr2;
701
702         return addr2;
703 }
704
705 /***********************************************************************
706  *              FT_PrologPrime                  (KERNEL32.89)
707  * 
708  * This function is called from the relay code installed by
709  * ThunkInitLSF. It replaces the location from where it was 
710  * called by a standard FT_Prolog call stub (which is 'primed'
711  * by inserting the correct target table pointer).
712  * Finally, it calls that stub.
713  * 
714  * Input:  ECX    target number + flags (passed through to FT_Prolog)
715  *        (ESP)   offset of location where target table pointer 
716  *                is stored, relative to the start of the relay code
717  *        (ESP+4) pointer to start of relay code
718  *                (this is where the FT_Prolog call stub gets written to)
719  * 
720  * Note: The two DWORD arguments get popped from the stack.
721  *        
722  */
723 REGS_ENTRYPOINT(FT_PrologPrime)
724 {
725     DWORD  targetTableOffset = STACK32_POP(context);
726     LPBYTE relayCode = (LPBYTE)STACK32_POP(context);
727     DWORD *targetTable = *(DWORD **)(relayCode+targetTableOffset);
728     DWORD  targetNr = LOBYTE(ECX_reg(context));
729
730     _write_ftprolog(relayCode, targetTable);
731
732     /* We should actually call the relay code now, */
733     /* but we skip it and go directly to FT_Prolog */
734     EDX_reg(context) = targetTable[targetNr];
735     __regs_FT_Prolog(context);
736 }
737
738 /***********************************************************************
739  *              QT_ThunkPrime                   (KERNEL32.90)
740  *
741  * This function corresponds to FT_PrologPrime, but installs a 
742  * call stub for QT_Thunk instead.
743  *
744  * Input: (EBP-4) target number (passed through to QT_Thunk)
745  *         EDX    target table pointer location offset
746  *         EAX    start of relay code
747  *      
748  */
749 REGS_ENTRYPOINT(QT_ThunkPrime)
750 {
751     DWORD  targetTableOffset = EDX_reg(context);
752     LPBYTE relayCode = (LPBYTE)EAX_reg(context);
753     DWORD *targetTable = *(DWORD **)(relayCode+targetTableOffset);
754     DWORD  targetNr = LOBYTE(*(DWORD *)(EBP_reg(context) - 4));
755
756     _write_qtthunk(relayCode, targetTable);
757
758     /* We should actually call the relay code now, */
759     /* but we skip it and go directly to QT_Thunk */
760     EDX_reg(context) = targetTable[targetNr];
761     __regs_QT_Thunk(context);
762 }
763
764 /***********************************************************************
765  *                                                      (KERNEL32.46)
766  * Another thunkbuf link routine.
767  * The start of the thunkbuf looks like this:
768  *      00: DWORD       length
769  *      04: SEGPTR      address for thunkbuffer pointer
770  * [ok probably]
771  */
772 VOID WINAPI ThunkInitSL(
773         LPBYTE thunk,           /* [in] start of thunkbuffer */
774         LPCSTR thkbuf,          /* [in] name/ordinal of thunkbuffer in win16 dll */
775         DWORD len,              /* [in] length of thunkbuffer */
776         LPCSTR dll16,           /* [in] name of win16 dll containing the thkbuf */
777         LPCSTR dll32            /* [in] win32 dll. FIXME: strange, unused */
778 ) {
779         LPDWORD         addr;
780
781         if (!(addr = _loadthunk( dll16, thkbuf, dll32, NULL, len )))
782                 return;
783
784         *(DWORD*)PTR_SEG_TO_LIN(addr[1]) = (DWORD)thunk;
785 }
786
787 /**********************************************************************
788  *           SSInit             KERNEL.700
789  * RETURNS
790  *      TRUE for success.
791  */
792 BOOL32 WINAPI SSInit()
793 {
794     return TRUE;
795 }
796
797 /**********************************************************************
798  *           SSOnBigStack       KERNEL32.87
799  * Check if thunking is initialized (ss selector set up etc.)
800  * We do that differently, so just return TRUE.
801  * [ok]
802  * RETURNS
803  *      TRUE for success.
804  */
805 BOOL32 WINAPI SSOnBigStack()
806 {
807     TRACE(thunk, "Yes, thunking is initialized\n");
808     return TRUE;
809 }
810
811 /**********************************************************************
812  *           SSCall
813  * One of the real thunking functions. This one seems to be for 32<->32
814  * thunks. It should probably be capable of crossing processboundaries.
815  *
816  * And YES, I've seen nr=48 (somewhere in the Win95 32<->16 OLE coupling)
817  * [ok]
818  */
819 DWORD WINAPIV SSCall(
820         DWORD nr,       /* [in] number of argument bytes */
821         DWORD flags,    /* [in] FIXME: flags ? */
822         FARPROC32 fun,  /* [in] function to call */
823         ...             /* [in/out] arguments */
824 ) {
825     DWORD i,ret;
826     DWORD *args = ((DWORD *)&fun) + 1;
827
828     if(TRACE_ON(thunk)){
829       dbg_decl_str(thunk, 256);
830       for (i=0;i<nr/4;i++) 
831         dsprintf(thunk,"0x%08lx,",args[i]);
832       TRACE(thunk,"(%ld,0x%08lx,%p,[%s])\n",
833                     nr,flags,fun,dbg_str(thunk));
834     }
835     switch (nr) {
836     case 0:     ret = fun();
837                 break;
838     case 4:     ret = fun(args[0]);
839                 break;
840     case 8:     ret = fun(args[0],args[1]);
841                 break;
842     case 12:    ret = fun(args[0],args[1],args[2]);
843                 break;
844     case 16:    ret = fun(args[0],args[1],args[2],args[3]);
845                 break;
846     case 20:    ret = fun(args[0],args[1],args[2],args[3],args[4]);
847                 break;
848     case 24:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5]);
849                 break;
850     case 28:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5],args[6]);
851                 break;
852     case 32:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7]);
853                 break;
854     case 36:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8]);
855                 break;
856     case 40:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9]);
857                 break;
858     case 44:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10]);
859                 break;
860     case 48:    ret = fun(args[0],args[1],args[2],args[3],args[4],args[5],args[6],args[7],args[8],args[9],args[10],args[11]);
861                 break;
862     default:
863         WARN(thunk,"Unsupported nr of arguments, %ld\n",nr);
864         ret = 0;
865         break;
866
867     }
868     TRACE(thunk," returning %ld ...\n",ret);
869     return ret;
870 }
871
872 /**********************************************************************
873  *           W32S_BackTo32                      (KERNEL32.51)
874  */
875 REGS_ENTRYPOINT(W32S_BackTo32)
876 {
877     LPDWORD stack = (LPDWORD)ESP_reg( context );
878     FARPROC32 proc = (FARPROC32) stack[0];
879
880     EAX_reg( context ) = proc( stack[2], stack[3], stack[4], stack[5], stack[6],
881                                stack[7], stack[8], stack[9], stack[10], stack[11] );
882
883     EIP_reg( context ) = stack[1];
884 }
885
886 /**********************************************************************
887  *                      AllocSLCallback         (KERNEL32)
888  *
889  * Win95 uses some structchains for callbacks. It allocates them
890  * in blocks of 100 entries, size 32 bytes each, layout:
891  * blockstart:
892  *      0:      PTR     nextblockstart
893  *      4:      entry   *first;
894  *      8:      WORD    sel ( start points to blockstart)
895  *      A:      WORD    unknown
896  * 100xentry:
897  *      00..17:         Code
898  *      18:     PDB     *owning_process;
899  *      1C:     PTR     blockstart
900  *
901  * We ignore this for now. (Just a note for further developers)
902  * FIXME: use this method, so we don't waste selectors...
903  *
904  * Following code is then generated by AllocSLCallback. The code is 16 bit, so
905  * the 0x66 prefix switches from word->long registers.
906  *
907  *      665A            pop     edx 
908  *      6668x arg2 x    pushl   <arg2>
909  *      6652            push    edx
910  *      EAx arg1 x      jmpf    <arg1>
911  *
912  * returns the startaddress of this thunk.
913  *
914  * Note, that they look very similair to the ones allocates by THUNK_Alloc.
915  * RETURNS
916  *      segmented pointer to the start of the thunk
917  */
918 DWORD WINAPI
919 AllocSLCallback(
920         DWORD finalizer,        /* [in] finalizer function */
921         DWORD callback          /* [in] callback function */
922 ) {
923         LPBYTE  x,thunk = HeapAlloc( GetProcessHeap(), 0, 32 );
924         WORD    sel;
925
926         x=thunk;
927         *x++=0x66;*x++=0x5a;                            /* popl edx */
928         *x++=0x66;*x++=0x68;*(DWORD*)x=finalizer;x+=4;  /* pushl finalizer */
929         *x++=0x66;*x++=0x52;                            /* pushl edx */
930         *x++=0xea;*(DWORD*)x=callback;x+=4;             /* jmpf callback */
931
932         *(PDB32**)(thunk+18) = PROCESS_Current();
933
934         sel = SELECTOR_AllocBlock( thunk , 32, SEGMENT_CODE, FALSE, FALSE );
935         return (sel<<16)|0;
936 }
937
938 /**********************************************************************
939  *              FreeSLCallback          (KERNEL32.274)
940  * Frees the specified 16->32 callback
941  */
942 void WINAPI
943 FreeSLCallback(
944         DWORD x /* [in] 16 bit callback (segmented pointer?) */
945 ) {
946         FIXME(win32,"(0x%08lx): stub\n",x);
947 }
948
949
950 /**********************************************************************
951  *              GetTEBSelectorFS        (KERNEL.475)
952  *      Set the 16-bit %fs to the 32-bit %fs (current TEB selector)
953  */
954 VOID WINAPI GetTEBSelectorFS( CONTEXT *context ) 
955 {
956     GET_FS( FS_reg(context) );
957 }
958
959 /**********************************************************************
960  *              KERNEL_431              (KERNEL.431)
961  *              IsPeFormat              (W32SYS.2)
962  * Checks the passed filename if it is a PE format executeable
963  * RETURNS
964  *  TRUE, if it is.
965  *  FALSE if not.
966  */
967 BOOL16 WINAPI IsPeFormat(
968         LPSTR   fn,     /* [in] filename to executeable */
969         HFILE16 hf16    /* [in] open file, if filename is NULL */
970 ) {
971         IMAGE_DOS_HEADER        mzh;
972         HFILE32                 hf=FILE_GetHandle32(hf16);
973         OFSTRUCT                ofs;
974         DWORD                   xmagic;
975
976         if (fn) {
977                 hf = OpenFile32(fn,&ofs,OF_READ);
978                 if (hf==HFILE_ERROR32)
979                         return FALSE;
980         }
981         _llseek32(hf,0,SEEK_SET);
982         if (sizeof(mzh)!=_lread32(hf,&mzh,sizeof(mzh))) {
983                 _lclose32(hf);
984                 return FALSE;
985         }
986         if (mzh.e_magic!=IMAGE_DOS_SIGNATURE) {
987                 WARN(dosmem,"File has not got dos signature!\n");
988                 _lclose32(hf);
989                 return FALSE;
990         }
991         _llseek32(hf,mzh.e_lfanew,SEEK_SET);
992         if (sizeof(DWORD)!=_lread32(hf,&xmagic,sizeof(DWORD))) {
993                 _lclose32(hf);
994                 return FALSE;
995         }
996         _lclose32(hf);
997         return (xmagic == IMAGE_NT_SIGNATURE);
998 }
999
1000 /***********************************************************************
1001  *           WOWHandle32                        (KERNEL32.57)(WOW32.16)
1002  * Converts a win16 handle of type into the respective win32 handle.
1003  * We currently just return this handle, since most handles are the same
1004  * for win16 and win32.
1005  * RETURNS
1006  *      The new handle
1007  */
1008 HANDLE32 WINAPI WOWHandle32(
1009         WORD handle,            /* [in] win16 handle */
1010         WOW_HANDLE_TYPE type    /* [in] handle type */
1011 ) {
1012         TRACE(win32,"(0x%04x,%d)\n",handle,type);
1013         return (HANDLE32)handle;
1014 }
1015
1016 /***********************************************************************
1017  *           K32Thk1632Prolog                   (KERNEL32.492)
1018  */
1019 REGS_ENTRYPOINT(K32Thk1632Prolog)
1020 {
1021    LPBYTE code = (LPBYTE)EIP_reg(context) - 5;
1022
1023    /* Arrrgh! SYSTHUNK.DLL just has to re-implement another method
1024       of 16->32 thunks instead of using one of the standard methods!
1025       This means that SYSTHUNK.DLL itself switches to a 32-bit stack,
1026       and does a far call to the 32-bit code segment of OLECLI32/OLESVR32.
1027       Unfortunately, our CallTo/CallFrom mechanism is therefore completely
1028       bypassed, which means it will crash the next time the 32-bit OLE 
1029       code thunks down again to 16-bit (this *will* happen!).
1030
1031       The following hack tries to recognize this situation.
1032       This is possible since the called stubs in OLECLI32/OLESVR32 all
1033       look exactly the same:
1034         00   E8xxxxxxxx    call K32Thk1632Prolog
1035         05   FF55FC        call [ebp-04]
1036         08   E8xxxxxxxx    call K32Thk1632Epilog
1037         0D   66CB          retf
1038
1039       If we recognize this situation, we try to simulate the actions
1040       of our CallTo/CallFrom mechanism by copying the 16-bit stack
1041       to our 32-bit stack, creating a proper STACK16FRAME and 
1042       updating thdb->cur_stack. */ 
1043
1044    if (   code[5] == 0xFF && code[6] == 0x55 && code[7] == 0xFC
1045        && code[13] == 0x66 && code[14] == 0xCB)
1046    {
1047       WORD  stackSel  = NtCurrentTeb()->stack_sel;
1048       DWORD stackBase = GetSelectorBase(stackSel);
1049
1050       THDB *thdb = THREAD_Current();
1051       DWORD argSize = EBP_reg(context) - ESP_reg(context);
1052       char *stack16 = (char *)ESP_reg(context);
1053       char *stack32 = (char *)thdb->cur_stack - argSize;
1054       STACK16FRAME *frame16 = (STACK16FRAME *)stack16 - 1;
1055
1056       TRACE(thunk, "before SYSTHUNK hack: EBP: %08lx ESP: %08lx cur_stack: %08lx\n",
1057                    EBP_reg(context), ESP_reg(context), thdb->cur_stack);
1058
1059       memset(frame16, '\0', sizeof(STACK16FRAME));
1060       frame16->frame32 = (STACK32FRAME *)thdb->cur_stack;
1061       frame16->ebp = EBP_reg(context);
1062
1063       memcpy(stack32, stack16, argSize);
1064       thdb->cur_stack = PTR_SEG_OFF_TO_SEGPTR(stackSel, (DWORD)frame16 - stackBase);
1065
1066       ESP_reg(context) = (DWORD)stack32;
1067       EBP_reg(context) = ESP_reg(context) + argSize;
1068
1069       TRACE(thunk, "after  SYSTHUNK hack: EBP: %08lx ESP: %08lx cur_stack: %08lx\n",
1070                    EBP_reg(context), ESP_reg(context), thdb->cur_stack);
1071    }
1072
1073    SYSLEVEL_ReleaseWin16Lock();
1074 }
1075
1076 /***********************************************************************
1077  *           K32Thk1632Epilog                   (KERNEL32.491)
1078  */
1079 REGS_ENTRYPOINT(K32Thk1632Epilog)
1080 {
1081    LPBYTE code = (LPBYTE)EIP_reg(context) - 13;
1082
1083    SYSLEVEL_RestoreWin16Lock();
1084
1085    /* We undo the SYSTHUNK hack if necessary. See K32Thk1632Prolog. */
1086
1087    if (   code[5] == 0xFF && code[6] == 0x55 && code[7] == 0xFC
1088        && code[13] == 0x66 && code[14] == 0xCB)
1089    {
1090       THDB *thdb = THREAD_Current();
1091       STACK16FRAME *frame16 = (STACK16FRAME *)PTR_SEG_TO_LIN(thdb->cur_stack);
1092       char *stack16 = (char *)(frame16 + 1);
1093       DWORD argSize = frame16->ebp - (DWORD)stack16;
1094       char *stack32 = (char *)frame16->frame32 - argSize;
1095
1096       DWORD nArgsPopped = ESP_reg(context) - (DWORD)stack32;
1097
1098       TRACE(thunk, "before SYSTHUNK hack: EBP: %08lx ESP: %08lx cur_stack: %08lx\n",
1099                    EBP_reg(context), ESP_reg(context), thdb->cur_stack);
1100
1101       thdb->cur_stack = (DWORD)frame16->frame32;
1102
1103       ESP_reg(context) = (DWORD)stack16 + nArgsPopped;
1104       EBP_reg(context) = frame16->ebp;
1105
1106       TRACE(thunk, "after  SYSTHUNK hack: EBP: %08lx ESP: %08lx cur_stack: %08lx\n",
1107                    EBP_reg(context), ESP_reg(context), thdb->cur_stack);
1108    }
1109 }
1110
1111 /***********************************************************************
1112  *           UpdateResource32A                 (KERNEL32.707)
1113  */
1114 BOOL32 WINAPI UpdateResource32A(
1115   HANDLE32  hUpdate,
1116   LPCSTR  lpType,
1117   LPCSTR  lpName,
1118   WORD    wLanguage,
1119   LPVOID  lpData,
1120   DWORD   cbData) {
1121
1122   FIXME(win32, ": stub\n");
1123   SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1124   return FALSE;
1125 }
1126
1127 /***********************************************************************
1128  *           UpdateResource32W                 (KERNEL32.708)
1129  */
1130 BOOL32 WINAPI UpdateResource32W(
1131   HANDLE32  hUpdate,
1132   LPCWSTR lpType,
1133   LPCWSTR lpName,
1134   WORD    wLanguage,
1135   LPVOID  lpData,
1136   DWORD   cbData) {
1137
1138   FIXME(win32, ": stub\n");
1139   SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
1140   return FALSE;
1141 }
1142
1143
1144 /***********************************************************************
1145  *           WaitNamedPipe32A                 [KERNEL32.725]
1146  */
1147 BOOL32 WINAPI WaitNamedPipe32A (LPCSTR lpNamedPipeName, DWORD nTimeOut)
1148 {       FIXME (win32,"%s 0x%08lx\n",lpNamedPipeName,nTimeOut);
1149         SetLastError(ERROR_PIPE_NOT_CONNECTED);
1150         return FALSE;
1151 }
1152 /***********************************************************************
1153  *           WaitNamedPipe32W                 [KERNEL32.726]
1154  */
1155 BOOL32 WINAPI WaitNamedPipe32W (LPCWSTR lpNamedPipeName, DWORD nTimeOut)
1156 {       FIXME (win32,"%s 0x%08lx\n",debugstr_w(lpNamedPipeName),nTimeOut);
1157         SetLastError(ERROR_PIPE_NOT_CONNECTED);
1158         return FALSE;
1159 }
1160
1161 /***********************************************************************
1162  *                       GetBinaryType32A                                 [KERNEL32.280]
1163  *
1164  * The GetBinaryType function determines whether a file is executable
1165  * or not and if it is it returns what type of executable it is.
1166  * The type of executable is a property that determines in which
1167  * subsystem an executable file runs under.
1168  *
1169  * lpApplicationName: points to a fully qualified path of the file to test
1170  * lpBinaryType: points to a variable that will receive the binary type info
1171  *
1172  * Binary types returned:
1173  * SCS_32BIT_BINARY: A win32 based application
1174  * SCS_DOS_BINARY: An MS-Dos based application
1175  * SCS_WOW_BINARY: A 16bit OS/2 based application
1176  * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app ( Not implemented )
1177  * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
1178  * SCS_OS216_BINARY: A 16bit Windows based application ( Not implemented )
1179  *
1180  * Returns TRUE if the file is an executable in which case
1181  * the value pointed by lpBinaryType is set.
1182  * Returns FALSE if the file is not an executable or if the function fails.
1183  *
1184  * This function is not complete.  It can only determine if a file
1185  * is a DOS, 32bit/16bit Windows executable. Also .COM file support
1186  * is not complete.
1187  * To do so it opens the file and reads in the header information
1188  * if the extended header information is not presend it will
1189  * assume that that the file is a DOS executable.
1190  * If the extended header information is present it will
1191  * determine if the file is an 16 or 32 bit Windows executable
1192  * by check the flags in the header.
1193  */
1194 BOOL32 WINAPI GetBinaryType32A (LPCSTR lpApplicationName, LPDWORD lpBinaryType)
1195 {
1196         BOOL32 ret = FALSE;
1197         HFILE32 hfile;
1198         OFSTRUCT ofs;
1199         IMAGE_DOS_HEADER mz_header;
1200         char magic[4];
1201
1202         TRACE (win32,"%s\n",lpApplicationName);
1203
1204         /* Sanity check.
1205          */
1206         if( lpApplicationName == NULL || lpBinaryType == NULL )
1207         {
1208                 return FALSE;
1209         }
1210
1211         /* Open the file indicated by lpApplicationName for reading.
1212          */
1213         hfile = OpenFile32( lpApplicationName, &ofs, OF_READ );
1214
1215         /* If we cannot read the file return failed.
1216          */
1217         if( hfile == HFILE_ERROR32 )
1218         {
1219                 return FALSE;
1220         }
1221
1222         /* Seek to the start of the file and read the DOS header information.
1223          */
1224         if( _llseek32( hfile, 0, SEEK_SET ) >= 0  &&
1225                 _lread32( hfile, &mz_header, sizeof(mz_header) ) == sizeof(mz_header) )
1226         {
1227                 /* Now that we have the header check the e_magic field
1228                  * to see if this is a dos image.
1229                  */
1230                 if( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
1231                 {
1232                         BOOL32 lfanewValid = FALSE;
1233                         /* We do have a DOS image so we will now try to seek into
1234                          * the file by the amount indicated by the field
1235                          * "Offset to extended header" and read in the
1236                          * "magic" field information at that location.
1237                          * This will tell us if there is more header information
1238                          * to read or not.
1239                          */
1240                         
1241                         /* But before we do we will make sure that header
1242                          * structure encompasses the "Offset to extended header"
1243                          * field.
1244                          */
1245                         if( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
1246                         {
1247                                 if( ( mz_header.e_crlc == 0 && mz_header.e_lfarlc == 0 ) ||
1248                                         ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
1249                                 {
1250                                         if( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER) &&
1251                                                 _llseek32( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
1252                                                 _lread32( hfile, magic, sizeof(magic) ) == sizeof(magic) )
1253                                         {
1254                                                 lfanewValid = TRUE;
1255                                         }
1256                                 }
1257                         }
1258                         
1259                         if( lfanewValid == FALSE )
1260                         {
1261                                 /* If we cannot read this "extended header" we will
1262                                  * assume that we have a simple DOS executable.
1263                                  */
1264                                 FIXME( win32, "Determine if this check is complete enough\n" );
1265                                 *lpBinaryType = SCS_DOS_BINARY;
1266                                 ret = TRUE;
1267                         }
1268                         else
1269                         {
1270                                 /* Reading the magic field succeeded so
1271                                  * we will not try to determine what type it is.
1272                                  */
1273                                 if( *(DWORD*)magic      == IMAGE_NT_SIGNATURE )
1274                                 {
1275                                         /* This is an NT signature.
1276                                          */
1277                                         *lpBinaryType = SCS_32BIT_BINARY;
1278                                         ret = TRUE;
1279                                 }
1280                                 else if( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
1281                                 {
1282                                         /* The IMAGE_OS2_SIGNATURE indicates that the
1283                                          * "extended header is a Windows executable (NE)
1284                                          * header.      This is a bit misleading, but it is
1285                                          * documented in the SDK. ( for more details see
1286                                          * the neexe.h file )
1287                                          */
1288
1289                                         /* Now we know that it is a Windows executable
1290                                          * we will read in the Windows header and
1291                                          * determine if it is a 16/32bit Windows executable.
1292                                          */
1293                                         IMAGE_OS2_HEADER ne_header;
1294                                         if( _lread32( hfile, &ne_header, sizeof(ne_header) ) == sizeof(ne_header) )
1295                                         {
1296                                                 /* Check the format flag to determine if it is
1297                                                  * Win32 or not.
1298                                                  */
1299                                                 if( ne_header.format_flags & NE_FFLAGS_WIN32 )
1300                                                 {
1301                                                         *lpBinaryType = SCS_32BIT_BINARY;
1302                                                         ret = TRUE;
1303                                                 }
1304                                                 else
1305                                                 {
1306                                                         /* We will assume it is a 16bit Windows executable.
1307                                                          * I'm not sure if this check is sufficient.
1308                                                          */
1309                                                         FIXME( win32, "Determine if this check is complete enough\n" );
1310                                                         *lpBinaryType = SCS_WOW_BINARY;
1311                                                         ret = TRUE;
1312                                                 }
1313                                         }
1314                                 }
1315                         }
1316                 }
1317         }
1318
1319         /* Close the file.
1320          */
1321         CloseHandle( hfile );
1322
1323         return ret;
1324 }
1325
1326
1327 /***********************************************************************
1328  *                       GetBinaryType32W                                 [KERNEL32.281]
1329  *
1330  * See GetBinaryType32A.
1331  */
1332 BOOL32 WINAPI GetBinaryType32W (LPCWSTR lpApplicationName, LPDWORD lpBinaryType)
1333 {
1334         BOOL32 ret = FALSE;
1335         LPSTR strNew = NULL;
1336         
1337         TRACE (win32,"%s\n",debugstr_w(lpApplicationName));
1338
1339         /* Sanity check.
1340          */
1341         if( lpApplicationName == NULL || lpBinaryType == NULL )
1342         {
1343                 return FALSE;
1344         }
1345
1346         
1347         /* Convert the wide string to a ascii string.
1348          */
1349         strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
1350
1351         if( strNew != NULL )
1352         {
1353                 ret = GetBinaryType32A( strNew, lpBinaryType );
1354
1355                 /* Free the allocated string.
1356                  */
1357                 HeapFree( GetProcessHeap(), 0, strNew );
1358         }
1359
1360         return ret;
1361 }
1362
1363
1364