Ensure that the WM_ENTERIDLE message is not sent if the wake-up event
[wine] / loader / module.c
1 /*
2  * Modules
3  *
4  * Copyright 1995 Alexandre Julliard
5  */
6
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <sys/types.h>
12 #include <unistd.h>
13 #include "wine/winuser16.h"
14 #include "wine/winbase16.h"
15 #include "windef.h"
16 #include "winerror.h"
17 #include "file.h"
18 #include "global.h"
19 #include "heap.h"
20 #include "module.h"
21 #include "snoop.h"
22 #include "neexe.h"
23 #include "pe_image.h"
24 #include "dosexe.h"
25 #include "process.h"
26 #include "thread.h"
27 #include "selectors.h"
28 #include "stackframe.h"
29 #include "task.h"
30 #include "debugtools.h"
31 #include "callback.h"
32 #include "loadorder.h"
33 #include "elfdll.h"
34
35 DECLARE_DEBUG_CHANNEL(module)
36 DECLARE_DEBUG_CHANNEL(win32)
37
38 /*************************************************************************
39  *              MODULE_WalkModref
40  * Walk MODREFs for input process ID
41  */
42 void MODULE_WalkModref( DWORD id )
43 {
44     int i;
45     WINE_MODREF  *zwm, *prev = NULL;
46     PDB *pdb = PROCESS_IdToPDB( id );
47
48     if (!pdb) {
49         MESSAGE("Invalid process id (pid)\n");
50         return;
51     }
52
53     MESSAGE("Modref list for process pdb=%p\n", pdb);
54     MESSAGE("Modref     next       prev        handle  deps  flags  name\n");
55     for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
56         MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
57                zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
58         for ( i = 0; i < zwm->nDeps; i++ ) {
59             if ( zwm->deps[i] )
60                 MESSAGE("    %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
61         }
62         if (prev != zwm->prev) 
63             MESSAGE("   --> modref corrupt, previous pointer wrong!!\n");
64         prev = zwm;
65     }
66 }
67
68 /*************************************************************************
69  *              MODULE32_LookupHMODULE
70  * looks for the referenced HMODULE in the current process
71  */
72 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
73 {
74     WINE_MODREF *wm;
75
76     if (!hmod) 
77         return PROCESS_Current()->exe_modref;
78
79     if (!HIWORD(hmod)) {
80         ERR_(module)("tried to lookup 0x%04x in win32 module handler!\n",hmod);
81         return NULL;
82     }
83     for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
84         if (wm->module == hmod)
85             return wm;
86     return NULL;
87 }
88
89 /*************************************************************************
90  *              MODULE_InitDll
91  */
92 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
93 {
94     BOOL retv = TRUE;
95
96     static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH", 
97                                  "THREAD_ATTACH", "THREAD_DETACH" };
98     assert( wm );
99
100
101     /* Skip calls for modules loaded with special load flags */
102
103     if (    ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
104          || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
105         return TRUE;
106
107
108     TRACE_(module)("(%s,%s,%p) - CALL\n", 
109            wm->modname, typeName[type], lpReserved );
110
111     /* Call the initialization routine */
112     switch ( wm->type )
113     {
114     case MODULE32_PE:
115         retv = PE_InitDLL( wm, type, lpReserved );
116         break;
117
118     case MODULE32_ELF:
119         /* no need to do that, dlopen() already does */
120         break;
121
122     default:
123         ERR_(module)("wine_modref type %d not handled.\n", wm->type );
124         retv = FALSE;
125         break;
126     }
127
128     TRACE_(module)("(%s,%s,%p) - RETURN %d\n", 
129            wm->modname, typeName[type], lpReserved, retv );
130
131     return retv;
132 }
133
134 /*************************************************************************
135  *              MODULE_DllProcessAttach
136  * 
137  * Send the process attach notification to all DLLs the given module
138  * depends on (recursively). This is somewhat complicated due to the fact that
139  *
140  * - we have to respect the module dependencies, i.e. modules implicitly
141  *   referenced by another module have to be initialized before the module
142  *   itself can be initialized
143  * 
144  * - the initialization routine of a DLL can itself call LoadLibrary,
145  *   thereby introducing a whole new set of dependencies (even involving
146  *   the 'old' modules) at any time during the whole process
147  *
148  * (Note that this routine can be recursively entered not only directly
149  *  from itself, but also via LoadLibrary from one of the called initialization
150  *  routines.)
151  *
152  * Furthermore, we need to rearrange the main WINE_MODREF list to allow
153  * the process *detach* notifications to be sent in the correct order.
154  * This must not only take into account module dependencies, but also 
155  * 'hidden' dependencies created by modules calling LoadLibrary in their
156  * attach notification routine.
157  *
158  * The strategy is rather simple: we move a WINE_MODREF to the head of the
159  * list after the attach notification has returned.  This implies that the
160  * detach notifications are called in the reverse of the sequence the attach
161  * notifications *returned*.
162  *
163  * NOTE: Assumes that the process critical section is held!
164  *
165  */
166 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
167 {
168     BOOL retv = TRUE;
169     int i;
170     assert( wm );
171
172     /* prevent infinite recursion in case of cyclical dependencies */
173     if (    ( wm->flags & WINE_MODREF_MARKER )
174          || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
175         return retv;
176
177     TRACE_(module)("(%s,%p) - START\n", 
178            wm->modname, lpReserved );
179
180     /* Tag current MODREF to prevent recursive loop */
181     wm->flags |= WINE_MODREF_MARKER;
182
183     /* Recursively attach all DLLs this one depends on */
184     for ( i = 0; retv && i < wm->nDeps; i++ )
185         if ( wm->deps[i] )
186             retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
187
188     /* Call DLL entry point */
189     if ( retv )
190     {
191         retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
192         if ( retv )
193             wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
194     }
195
196     /* Re-insert MODREF at head of list */
197     if ( retv && wm->prev )
198     {
199         wm->prev->next = wm->next;
200         if ( wm->next ) wm->next->prev = wm->prev;
201
202         wm->prev = NULL;
203         wm->next = PROCESS_Current()->modref_list;
204         PROCESS_Current()->modref_list = wm->next->prev = wm;
205     }
206
207     /* Remove recursion flag */
208     wm->flags &= ~WINE_MODREF_MARKER;
209
210     TRACE_(module)("(%s,%p) - END\n", 
211            wm->modname, lpReserved );
212
213     return retv;
214 }
215
216 /*************************************************************************
217  *              MODULE_DllProcessDetach
218  * 
219  * Send DLL process detach notifications.  See the comment about calling 
220  * sequence at MODULE_DllProcessAttach.  Unless the bForceDetach flag
221  * is set, only DLLs with zero refcount are notified.
222  *
223  * NOTE: Assumes that the process critical section is held!
224  *
225  */
226 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
227 {
228     WINE_MODREF *wm;
229
230     do
231     {
232         for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
233         {
234             /* Check whether to detach this DLL */
235             if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
236                 continue;
237             if ( wm->refCount > 0 && !bForceDetach )
238                 continue;
239
240             /* Call detach notification */
241             wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
242             MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
243
244             /* Restart at head of WINE_MODREF list, as entries might have
245                been added and/or removed while performing the call ... */
246             break;
247         }
248     } while ( wm );
249 }
250
251 /*************************************************************************
252  *              MODULE_DllThreadAttach
253  * 
254  * Send DLL thread attach notifications. These are sent in the
255  * reverse sequence of process detach notification.
256  *
257  */
258 void MODULE_DllThreadAttach( LPVOID lpReserved )
259 {
260     WINE_MODREF *wm;
261
262     EnterCriticalSection( &PROCESS_Current()->crit_section );
263
264     for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
265         if ( !wm->next )
266             break;
267
268     for ( ; wm; wm = wm->prev )
269     {
270         if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
271             continue;
272         if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
273             continue;
274
275         MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
276     }
277
278     LeaveCriticalSection( &PROCESS_Current()->crit_section );
279 }
280
281 /*************************************************************************
282  *              MODULE_DllThreadDetach
283  * 
284  * Send DLL thread detach notifications. These are sent in the
285  * same sequence as process detach notification.
286  *
287  */
288 void MODULE_DllThreadDetach( LPVOID lpReserved )
289 {
290     WINE_MODREF *wm;
291
292     EnterCriticalSection( &PROCESS_Current()->crit_section );
293
294     for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
295     {
296         if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
297             continue;
298         if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
299             continue;
300
301         MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
302     }
303
304     LeaveCriticalSection( &PROCESS_Current()->crit_section );
305 }
306
307 /****************************************************************************
308  *              DisableThreadLibraryCalls (KERNEL32.74)
309  *
310  * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
311  */
312 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
313 {
314     WINE_MODREF *wm;
315     BOOL retval = TRUE;
316
317     EnterCriticalSection( &PROCESS_Current()->crit_section );
318
319     wm = MODULE32_LookupHMODULE( hModule );
320     if ( !wm )
321         retval = FALSE;
322     else
323         wm->flags |= WINE_MODREF_NO_DLL_CALLS;
324
325     LeaveCriticalSection( &PROCESS_Current()->crit_section );
326
327     return retval;
328 }
329
330
331 /***********************************************************************
332  *           MODULE_CreateDummyModule
333  *
334  * Create a dummy NE module for Win32 or Winelib.
335  */
336 HMODULE MODULE_CreateDummyModule( const OFSTRUCT *ofs, LPCSTR modName )
337 {
338     HMODULE hModule;
339     NE_MODULE *pModule;
340     SEGTABLEENTRY *pSegment;
341     char *pStr,*s;
342     int len;
343     const char* basename;
344
345     INT of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
346                     + strlen(ofs->szPathName) + 1;
347     INT size = sizeof(NE_MODULE) +
348                  /* loaded file info */
349                  of_size +
350                  /* segment table: DS,CS */
351                  2 * sizeof(SEGTABLEENTRY) +
352                  /* name table */
353                  9 +
354                  /* several empty tables */
355                  8;
356
357     hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
358     if (!hModule) return (HMODULE)11;  /* invalid exe */
359
360     FarSetOwner16( hModule, hModule );
361     pModule = (NE_MODULE *)GlobalLock16( hModule );
362
363     /* Set all used entries */
364     pModule->magic            = IMAGE_OS2_SIGNATURE;
365     pModule->count            = 1;
366     pModule->next             = 0;
367     pModule->flags            = 0;
368     pModule->dgroup           = 0;
369     pModule->ss               = 1;
370     pModule->cs               = 2;
371     pModule->heap_size        = 0;
372     pModule->stack_size       = 0;
373     pModule->seg_count        = 2;
374     pModule->modref_count     = 0;
375     pModule->nrname_size      = 0;
376     pModule->fileinfo         = sizeof(NE_MODULE);
377     pModule->os_flags         = NE_OSFLAGS_WINDOWS;
378     pModule->expected_version = 0x030a;
379     pModule->self             = hModule;
380
381     /* Set loaded file information */
382     memcpy( pModule + 1, ofs, of_size );
383     ((OFSTRUCT *)(pModule+1))->cBytes = of_size - 1;
384
385     pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
386     pModule->seg_table = (int)pSegment - (int)pModule;
387     /* Data segment */
388     pSegment->size    = 0;
389     pSegment->flags   = NE_SEGFLAGS_DATA;
390     pSegment->minsize = 0x1000;
391     pSegment++;
392     /* Code segment */
393     pSegment->flags   = 0;
394     pSegment++;
395
396     /* Module name */
397     pStr = (char *)pSegment;
398     pModule->name_table = (int)pStr - (int)pModule;
399     if ( modName )
400         basename = modName;
401     else
402     {
403         basename = strrchr(ofs->szPathName,'\\');
404         if (!basename) basename = ofs->szPathName;
405         else basename++;
406     }
407     len = strlen(basename);
408     if ((s = strchr(basename,'.'))) len = s - basename;
409     if (len > 8) len = 8;
410     *pStr = len;
411     strncpy( pStr+1, basename, len );
412     if (len < 8) pStr[len+1] = 0;
413     pStr += 9;
414
415     /* All tables zero terminated */
416     pModule->res_table = pModule->import_table = pModule->entry_table =
417                 (int)pStr - (int)pModule;
418
419     NE_RegisterModule( pModule );
420     return hModule;
421 }
422
423
424 /**********************************************************************
425  *          MODULE_FindModule32
426  *
427  * Find a (loaded) win32 module depending on path
428  * The handling of '.' is a bit weird, but we need it that way, 
429  * for sometimes the programs use '<name>.exe' and '<name>.dll' and
430  * this is the only way to differentiate. (mainly hypertrm.exe)
431  *
432  * RETURNS
433  *      the module handle if found
434  *      0 if not
435  */
436 WINE_MODREF *MODULE_FindModule(
437         LPCSTR path     /* [in] pathname of module/library to be found */
438 ) {
439     LPSTR       filename;
440     LPSTR       dotptr;
441     WINE_MODREF *wm;
442
443     if (!(filename = strrchr( path, '\\' )))
444         filename = HEAP_strdupA( GetProcessHeap(), 0, path );
445     else 
446         filename = HEAP_strdupA( GetProcessHeap(), 0, filename+1 );
447     dotptr=strrchr(filename,'.');
448
449     for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
450         LPSTR   xmodname,xdotptr;
451
452         assert (wm->modname);
453         xmodname = HEAP_strdupA( GetProcessHeap(), 0, wm->modname );
454         xdotptr=strrchr(xmodname,'.');
455         if (    (xdotptr && !dotptr) ||
456                 (!xdotptr && dotptr)
457         ) {
458             if (dotptr) *dotptr         = '\0';
459             if (xdotptr) *xdotptr       = '\0';
460         }
461         if (!strcasecmp( filename, xmodname)) {
462             HeapFree( GetProcessHeap(), 0, filename );
463             HeapFree( GetProcessHeap(), 0, xmodname );
464             return wm;
465         }
466         if (dotptr) *dotptr='.';
467         /* FIXME: add paths, shortname */
468         HeapFree( GetProcessHeap(), 0, xmodname );
469     }
470     /* if that fails, try looking for the filename... */
471     for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
472         LPSTR   xlname,xdotptr;
473
474         assert (wm->longname);
475         xlname = strrchr(wm->longname,'\\');
476         if (!xlname) 
477             xlname = wm->longname;
478         else
479             xlname++;
480         xlname = HEAP_strdupA( GetProcessHeap(), 0, xlname );
481         xdotptr=strrchr(xlname,'.');
482         if (    (xdotptr && !dotptr) ||
483                 (!xdotptr && dotptr)
484         ) {
485             if (dotptr) *dotptr         = '\0';
486             if (xdotptr) *xdotptr       = '\0';
487         }
488         if (!strcasecmp( filename, xlname)) {
489             HeapFree( GetProcessHeap(), 0, filename );
490             HeapFree( GetProcessHeap(), 0, xlname );
491             return wm;
492         }
493         if (dotptr) *dotptr='.';
494         /* FIXME: add paths, shortname */
495         HeapFree( GetProcessHeap(), 0, xlname );
496     }
497     HeapFree( GetProcessHeap(), 0, filename );
498     return NULL;
499 }
500
501 /***********************************************************************
502  *           MODULE_GetBinaryType
503  *
504  * The GetBinaryType function determines whether a file is executable
505  * or not and if it is it returns what type of executable it is.
506  * The type of executable is a property that determines in which
507  * subsystem an executable file runs under.
508  *
509  * Binary types returned:
510  * SCS_32BIT_BINARY: A Win32 based application
511  * SCS_DOS_BINARY: An MS-Dos based application
512  * SCS_WOW_BINARY: A Win16 based application
513  * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
514  * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
515  * SCS_OS216_BINARY: A 16bit OS/2 based application
516  *
517  * Returns TRUE if the file is an executable in which case
518  * the value pointed by lpBinaryType is set.
519  * Returns FALSE if the file is not an executable or if the function fails.
520  *
521  * To do so it opens the file and reads in the header information
522  * if the extended header information is not presend it will
523  * assume that that the file is a DOS executable.
524  * If the extended header information is present it will
525  * determine if the file is an 16 or 32 bit Windows executable
526  * by check the flags in the header.
527  *
528  * Note that .COM and .PIF files are only recognized by their
529  * file name extension; but Windows does it the same way ...
530  */
531 static BOOL MODULE_GetBinaryType( HFILE hfile, OFSTRUCT *ofs, 
532                                   LPDWORD lpBinaryType )
533 {
534     IMAGE_DOS_HEADER mz_header;
535     char magic[4], *ptr;
536
537     /* Seek to the start of the file and read the DOS header information.
538      */
539     if ( _llseek( hfile, 0, SEEK_SET ) >= 0  &&
540          _lread( hfile, &mz_header, sizeof(mz_header) ) == sizeof(mz_header) )
541     {
542         /* Now that we have the header check the e_magic field
543          * to see if this is a dos image.
544          */
545         if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
546         {
547             BOOL lfanewValid = FALSE;
548             /* We do have a DOS image so we will now try to seek into
549              * the file by the amount indicated by the field
550              * "Offset to extended header" and read in the
551              * "magic" field information at that location.
552              * This will tell us if there is more header information
553              * to read or not.
554              */
555             /* But before we do we will make sure that header
556              * structure encompasses the "Offset to extended header"
557              * field.
558              */
559             if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
560                 if ( ( mz_header.e_crlc == 0 && mz_header.e_lfarlc == 0 ) ||
561                      ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
562                     if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER) &&
563                          _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
564                          _lread( hfile, magic, sizeof(magic) ) == sizeof(magic) )
565                         lfanewValid = TRUE;
566
567             if ( !lfanewValid )
568             {
569                 /* If we cannot read this "extended header" we will
570                  * assume that we have a simple DOS executable.
571                  */
572                 *lpBinaryType = SCS_DOS_BINARY;
573                 return TRUE;
574             }
575             else
576             {
577                 /* Reading the magic field succeeded so
578                  * we will try to determine what type it is.
579                  */
580                 if ( *(DWORD*)magic      == IMAGE_NT_SIGNATURE )
581                 {
582                     /* This is an NT signature.
583                      */
584                     *lpBinaryType = SCS_32BIT_BINARY;
585                     return TRUE;
586                 }
587                 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
588                 {
589                     /* The IMAGE_OS2_SIGNATURE indicates that the
590                      * "extended header is a Windows executable (NE)
591                      * header."  This can mean either a 16-bit OS/2
592                      * or a 16-bit Windows or even a DOS program 
593                      * (running under a DOS extender).  To decide
594                      * which, we'll have to read the NE header.
595                      */
596
597                      IMAGE_OS2_HEADER ne;
598                      if ( _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
599                           _lread( hfile, &ne, sizeof(ne) ) == sizeof(ne) )
600                      {
601                          switch ( ne.operating_system )
602                          {
603                          case 2:  *lpBinaryType = SCS_WOW_BINARY;   return TRUE;
604                          case 5:  *lpBinaryType = SCS_DOS_BINARY;   return TRUE;
605                          default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
606                          }
607                      }
608                      /* Couldn't read header, so abort. */
609                      return FALSE;
610                 }
611                 else
612                 {
613                     /* Unknown extended header, so abort.
614                      */
615                     return FALSE;
616                 }
617             }
618         }
619     }
620
621     /* If we get here, we don't even have a correct MZ header.
622      * Try to check the file extension for known types ...
623      */
624     ptr = strrchr( ofs->szPathName, '.' );
625     if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
626     {
627         if ( !lstrcmpiA( ptr, ".COM" ) )
628         {
629             *lpBinaryType = SCS_DOS_BINARY;
630             return TRUE;
631         }
632
633         if ( !lstrcmpiA( ptr, ".PIF" ) )
634         {
635             *lpBinaryType = SCS_PIF_BINARY;
636             return TRUE;
637         }
638     }
639
640     return FALSE;
641 }
642
643 /***********************************************************************
644  *             GetBinaryTypeA                     [KERNEL32.280]
645  */
646 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
647 {
648     BOOL ret = FALSE;
649     HFILE hfile;
650     OFSTRUCT ofs;
651
652     TRACE_(win32)("%s\n", lpApplicationName );
653
654     /* Sanity check.
655      */
656     if ( lpApplicationName == NULL || lpBinaryType == NULL )
657         return FALSE;
658
659     /* Open the file indicated by lpApplicationName for reading.
660      */
661     if ( (hfile = OpenFile( lpApplicationName, &ofs, OF_READ )) == HFILE_ERROR )
662         return FALSE;
663
664     /* Check binary type
665      */
666     ret = MODULE_GetBinaryType( hfile, &ofs, lpBinaryType );
667
668     /* Close the file.
669      */
670     CloseHandle( hfile );
671
672     return ret;
673 }
674
675 /***********************************************************************
676  *             GetBinaryTypeW                      [KERNEL32.281]
677  */
678 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
679 {
680     BOOL ret = FALSE;
681     LPSTR strNew = NULL;
682
683     TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
684
685     /* Sanity check.
686      */
687     if ( lpApplicationName == NULL || lpBinaryType == NULL )
688         return FALSE;
689
690     /* Convert the wide string to a ascii string.
691      */
692     strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
693
694     if ( strNew != NULL )
695     {
696         ret = GetBinaryTypeA( strNew, lpBinaryType );
697
698         /* Free the allocated string.
699          */
700         HeapFree( GetProcessHeap(), 0, strNew );
701     }
702
703     return ret;
704 }
705
706 /**********************************************************************
707  *          MODULE_CreateUnixProcess
708  */
709 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
710                                       LPSTARTUPINFOA lpStartupInfo,
711                                       LPPROCESS_INFORMATION lpProcessInfo,
712                                       BOOL useWine )
713 {
714     DOS_FULL_NAME full_name;
715     const char *unixfilename = filename;
716     const char *argv[256], **argptr;
717     BOOL iconic = FALSE;
718
719     /* Get Unix file name and iconic flag */
720
721     if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
722         if (    lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
723              || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
724             iconic = TRUE;
725
726     /* Build argument list */
727
728     argptr = argv;
729     if ( !useWine )
730     {
731         char *p = strdup(lpCmdLine);
732     if (    strchr(filename, '/') 
733          || strchr(filename, ':') 
734          || strchr(filename, '\\') )
735     {
736         if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
737             unixfilename = full_name.long_name;
738     }
739         *argptr++ = unixfilename;
740         if (iconic) *argptr++ = "-iconic";
741         while (1)
742         {
743             while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
744             if (!*p) break;
745             *argptr++ = p;
746             while (*p && *p != ' ' && *p != '\t') p++;
747         }
748         free (p);
749     }
750     else
751     {
752         *argptr++ = "wine";
753         if (iconic) *argptr++ = "-iconic";
754         *argptr++ = lpCmdLine;
755     }
756     *argptr++ = 0;
757
758     /* Fork and execute */
759
760     if ( !fork() )
761     {
762         /* Note: don't use Wine routines here, as this process
763                  has not been correctly initialized! */
764
765         execvp( argv[0], (char**)argv );
766
767         /* Failed ! */
768         if ( useWine )
769             fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n", 
770                              lpCmdLine );
771         exit( 1 );
772     }
773
774     /* Fake success return value */
775
776     memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
777     lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
778     lpProcessInfo->hThread  = INVALID_HANDLE_VALUE;
779
780     SetLastError( ERROR_SUCCESS );
781     return TRUE;
782 }
783
784 /***********************************************************************
785  *           WinExec16   (KERNEL.166)
786  */
787 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
788 {
789     HINSTANCE16 hInst;
790
791     SYSLEVEL_ReleaseWin16Lock();
792     hInst = WinExec( lpCmdLine, nCmdShow );
793     SYSLEVEL_RestoreWin16Lock();
794
795     return hInst;
796 }
797
798 /***********************************************************************
799  *           WinExec   (KERNEL32.566)
800  */
801 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
802 {
803     LOADPARAMS params;
804     UINT16 paramCmdShow[2];
805
806     if (!lpCmdLine)
807         return 2;  /* File not found */
808
809     /* Set up LOADPARAMS buffer for LoadModule */
810
811     memset( &params, '\0', sizeof(params) );
812     params.lpCmdLine    = (LPSTR)lpCmdLine;
813     params.lpCmdShow    = paramCmdShow;
814     params.lpCmdShow[0] = 2;
815     params.lpCmdShow[1] = nCmdShow;
816
817     /* Now load the executable file */
818
819     return LoadModule( NULL, &params );
820 }
821
822 /**********************************************************************
823  *          LoadModule    (KERNEL32.499)
824  */
825 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock ) 
826 {
827     LOADPARAMS *params = (LOADPARAMS *)paramBlock;
828     PROCESS_INFORMATION info;
829     STARTUPINFOA startup;
830     HINSTANCE hInstance;
831     PDB *pdb;
832     TDB *tdb;
833
834     memset( &startup, '\0', sizeof(startup) );
835     startup.cb = sizeof(startup);
836     startup.dwFlags = STARTF_USESHOWWINDOW;
837     startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
838
839     if ( !CreateProcessA( name, params->lpCmdLine,
840                           NULL, NULL, FALSE, 0, params->lpEnvAddress,
841                           NULL, &startup, &info ) )
842     {
843         hInstance = GetLastError();
844         if ( hInstance < 32 ) return hInstance;
845
846         FIXME_(module)("Strange error set by CreateProcess: %d\n", hInstance );
847         return 11;
848     }
849     
850     /* Get 16-bit hInstance/hTask from process */
851     pdb = PROCESS_IdToPDB( info.dwProcessId );
852     tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
853     hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
854     /* If there is no hInstance (32-bit process) return a dummy value
855      * that must be > 31
856      * FIXME: should do this in all cases and fix Win16 callers */
857     if (!hInstance) hInstance = 33;
858
859     /* Close off the handles */
860     CloseHandle( info.hThread );
861     CloseHandle( info.hProcess );
862
863     return hInstance;
864 }
865
866 /*************************************************************************
867  *               get_makename_token
868  * 
869  * Get next blank delimited token from input string. If quoted then 
870  * process till matching quote and then till blank.
871  *
872  * Returns number of characters in token (not including \0). On 
873  * end of string (EOS), returns a 0.
874  *
875  *    from  (IO)  address of start of input string to scan, updated to 
876  *                next non-processed character.
877  *    to    (IO)  address of start of output string (previous token \0 
878  *                char), updated to end of new output string (the \0
879  *                char).
880  */
881 static int get_makename_token(LPCSTR *from, LPSTR *to )
882 {
883     int len = 0;
884     LPCSTR to_old = *to;   /* only used for tracing */
885
886     while ( **from == ' ') {
887       /* Copy leading blanks (separators between previous    */
888       /* token and this token).                              */
889       **to = **from;
890       (*from)++;
891       (*to)++;
892       len++;
893     }
894     do {
895       while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
896           **to = **from; (*from)++; (*to)++; len++;
897       }
898       if ( **from == '"' ) {
899         /* Handle quoted string. */
900         (*from)++;
901         if ( !strchr(*from, '"') ) {
902           /* fail - no closing quote. Return entire string */
903           while ( **from != 0 ) {
904              **to = **from; (*from)++; (*to)++; len++;
905           }
906           break;
907         }
908         while( **from != '"') { 
909             **to = **from;
910             len++;
911             (*to)++;
912             (*from)++;
913         }
914         (*from)++;
915         continue;
916       }
917
918       /* either EOS or ' ' */
919       break;
920
921     } while (1);
922
923     **to = 0;   /* terminate output string */
924
925     TRACE_(module)("returning token len=%d, string=%s\n",
926               len, to_old);
927
928     return len;     
929 }
930
931 /*************************************************************************
932  *              make_lpCommandLine_name
933  * 
934  * Try longer and longer strings from "line" to find an existing
935  * file name. Each attempt is delimited by a blank outside of quotes.
936  * Also will attempt to append ".exe" if requested and not already
937  * present. Returns the address of the remaining portion of the
938  * input line.
939  *
940  */
941
942 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
943                                  LPCSTR *after )
944 {
945     BOOL  found = TRUE;
946     LPCSTR from;
947     char  buffer[260];
948     DWORD  retlen;
949     LPSTR to, lastpart;
950     
951     from = line;
952     to = name;
953
954     /* scan over initial blanks if any */
955     while ( *from == ' ') from++;
956
957     /* get a token and append to previous data the check for existance */
958     do {
959         if ( !get_makename_token( &from, &to ) ) {
960           /* EOS has occured and not found - exit */
961           retlen = 0;
962           found = FALSE;
963           break;
964         }
965         TRACE_(module)("checking if file exists '%s'\n", name);
966         retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
967         if ( retlen && (retlen < sizeof(buffer)) )  break;
968     } while (1);
969
970     /* if we have a non-null full path name in buffer then move to output */
971     if ( retlen ) {
972        if ( strlen(buffer) <= namelen ) {
973           strcpy( name, buffer );
974        } else {
975           /* not enough space to return full path string */
976           FIXME_(module)("internal string not long enough, need %d\n",
977              strlen(buffer) );
978         }
979     }
980
981     /* all done, indicate end of module name and then trace and exit */
982     if (after) *after = from;
983     TRACE_(module)("%i, selected file name '%s'\n    and cmdline as %s\n",
984             found, name, debugstr_a(from));
985     return found;
986     }
987
988 /*************************************************************************
989  *              make_lpApplicationName_name
990  * 
991  * Scan input string (the lpApplicationName) and remove any quotes
992  * if they are balanced. 
993  *
994  */
995
996 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
997 {
998     LPCSTR from;
999     LPSTR to, to_end, to_old;
1000     DOS_FULL_NAME  full_name;
1001
1002     to = name;
1003     to_end = to + namelen - 1;
1004     to_old = to;
1005     
1006     while ( *line == ' ' ) line++;  /* point to beginning of string */
1007     from = line;
1008     do {
1009         /* Copy all input till end, or quote */
1010         while((*from != 0) && (*from != '"') && (to < to_end)) 
1011            *to++ = *from++;
1012         if (to >= to_end) { *to = 0; break; }
1013
1014         if (*from == '"')
1015           {
1016             /* Handle quoted string. If there is a closing quote, copy all */
1017             /* that is inside.                                             */
1018             from++;
1019             if (!strchr(from, '"'))
1020               {
1021                 /* fail - no closing quote */
1022                 to = to_old; /* restore to previous attempt */
1023                 *to = 0;     /* end string  */
1024                 break;       /* exit with  previous attempt */
1025               }
1026             while((*from != '"') && (to < to_end)) *to++ = *from++;
1027             if (to >= to_end) { *to = 0; break; }
1028             from++;
1029             continue;  /* past quoted string, so restart from top */
1030           }
1031
1032         *to = 0;   /* terminate output string */
1033         to_old = to;   /* save for possible use in unmatched quote case */
1034
1035         /* loop around keeping the blank as part of file name */
1036         if (!*from)
1037           break;    /* exit if out of input string */
1038     } while (1);
1039
1040     if (!DOSFS_GetFullName(name, TRUE, &full_name)) {
1041         TRACE_(module)("file not found '%s'\n", name );
1042         return FALSE;
1043       }
1044
1045     if (strlen(full_name.long_name) >= namelen ) {
1046        FIXME_(module)("name longer than buffer (len=%d), file=%s\n",
1047            namelen, full_name.long_name);
1048        return FALSE;
1049     }
1050     strcpy(name, full_name.long_name); 
1051
1052     TRACE_(module)("selected as file name '%s'\n", name );
1053     return TRUE;
1054 }
1055
1056 /**********************************************************************
1057  *       CreateProcessA          (KERNEL32.171)
1058  */
1059 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine, 
1060                             LPSECURITY_ATTRIBUTES lpProcessAttributes,
1061                             LPSECURITY_ATTRIBUTES lpThreadAttributes,
1062                             BOOL bInheritHandles, DWORD dwCreationFlags,
1063                             LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1064                             LPSTARTUPINFOA lpStartupInfo,
1065                             LPPROCESS_INFORMATION lpProcessInfo )
1066 {
1067     BOOL retv = FALSE;
1068     BOOL found_file = FALSE;
1069     HFILE hFile;
1070     OFSTRUCT ofs;
1071     DWORD type;
1072     char name[256], dummy[256];
1073     LPCSTR cmdline = NULL;
1074     LPSTR tidy_cmdline;
1075     int len = 0;
1076
1077     /* Get name and command line */
1078
1079     if (!lpApplicationName && !lpCommandLine)
1080     {
1081         SetLastError( ERROR_FILE_NOT_FOUND );
1082         return FALSE;
1083     }
1084
1085     /* Process the AppName and/or CmdLine to get module name and path */
1086
1087     name[0] = '\0';
1088
1089     if (lpApplicationName) {
1090        found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1091        if (lpCommandLine) {
1092           make_lpCommandLine_name( lpCommandLine, dummy, sizeof ( dummy ), &cmdline );
1093     }
1094        else {
1095           cmdline = lpApplicationName;
1096        }
1097        len += strlen(lpApplicationName);
1098     }
1099     else {
1100        found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1101        if (lpCommandLine) len = strlen(lpCommandLine);
1102     }
1103
1104     if ( !found_file ) {
1105         /* make an early exit if file not found - save second pass */
1106         SetLastError( ERROR_FILE_NOT_FOUND );
1107         return FALSE;
1108     }
1109
1110     len += strlen(name) + 2;
1111     tidy_cmdline = HeapAlloc( GetProcessHeap(), 0, len );
1112     sprintf( tidy_cmdline, "\"%s\"%s", name, cmdline);
1113
1114     /* Warn if unsupported features are used */
1115
1116     if (dwCreationFlags & CREATE_SUSPENDED)
1117         FIXME_(module)("(%s,...): CREATE_SUSPENDED ignored\n", name);
1118     if (dwCreationFlags & DETACHED_PROCESS)
1119         FIXME_(module)("(%s,...): DETACHED_PROCESS ignored\n", name);
1120     if (dwCreationFlags & CREATE_NEW_CONSOLE)
1121         FIXME_(module)("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1122     if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1123         FIXME_(module)("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1124     if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1125         FIXME_(module)("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1126     if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1127         FIXME_(module)("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1128     if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1129         FIXME_(module)("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1130     if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1131         FIXME_(module)("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1132     if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1133         FIXME_(module)("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1134     if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1135         FIXME_(module)("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1136     if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1137         FIXME_(module)("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1138     if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1139         FIXME_(module)("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1140     if (dwCreationFlags & CREATE_NO_WINDOW)
1141         FIXME_(module)("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1142     if (dwCreationFlags & PROFILE_USER)
1143         FIXME_(module)("(%s,...): PROFILE_USER ignored\n", name);
1144     if (dwCreationFlags & PROFILE_KERNEL)
1145         FIXME_(module)("(%s,...): PROFILE_KERNEL ignored\n", name);
1146     if (dwCreationFlags & PROFILE_SERVER)
1147         FIXME_(module)("(%s,...): PROFILE_SERVER ignored\n", name);
1148     if (lpCurrentDirectory)
1149         FIXME_(module)("(%s,...): lpCurrentDirectory %s ignored\n", 
1150                       name, lpCurrentDirectory);
1151     if (lpStartupInfo->lpDesktop)
1152         FIXME_(module)("(%s,...): lpStartupInfo->lpDesktop %s ignored\n", 
1153                       name, lpStartupInfo->lpDesktop);
1154     if (lpStartupInfo->lpTitle)
1155         FIXME_(module)("(%s,...): lpStartupInfo->lpTitle %s ignored\n", 
1156                       name, lpStartupInfo->lpTitle);
1157     if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1158         FIXME_(module)("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n", 
1159                       name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1160     if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1161         FIXME_(module)("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n", 
1162                       name, lpStartupInfo->dwFillAttribute);
1163     if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1164         FIXME_(module)("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1165     if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1166         FIXME_(module)("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1167     if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1168         FIXME_(module)("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1169     if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1170         FIXME_(module)("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1171
1172     /* When in WineLib, always fork new Unix process */
1173
1174     if ( __winelib ) {
1175         retv = MODULE_CreateUnixProcess( name, tidy_cmdline, 
1176                                          lpStartupInfo, lpProcessInfo, TRUE );
1177         HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1178         return (retv);
1179     }
1180
1181     /* Check for special case: second instance of NE module */
1182
1183     lstrcpynA( ofs.szPathName, name, sizeof( ofs.szPathName ) );
1184     retv = NE_CreateProcess( HFILE_ERROR, &ofs, tidy_cmdline, lpEnvironment, 
1185                              lpProcessAttributes, lpThreadAttributes,
1186                              bInheritHandles, dwCreationFlags,
1187                              lpStartupInfo, lpProcessInfo );
1188
1189     /* Load file and create process */
1190
1191     if ( !retv )
1192     {
1193         /* Open file and determine executable type */
1194
1195         if ( (hFile = OpenFile( name, &ofs, OF_READ )) == HFILE_ERROR )
1196         {
1197             SetLastError( ERROR_FILE_NOT_FOUND );
1198             HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1199             return FALSE;
1200         }
1201
1202         if ( !MODULE_GetBinaryType( hFile, &ofs, &type ) )
1203         {
1204             CloseHandle( hFile );
1205
1206             /* FIXME: Try Unix executable only when appropriate! */
1207             if ( MODULE_CreateUnixProcess( name, tidy_cmdline, 
1208                                            lpStartupInfo, lpProcessInfo, FALSE ) )
1209             {
1210                 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1211                 return TRUE;
1212             }
1213             HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1214             SetLastError( ERROR_BAD_FORMAT );
1215             return FALSE;
1216         }
1217
1218
1219         /* Create process */
1220
1221         switch ( type )
1222         {
1223         case SCS_32BIT_BINARY:
1224             retv = PE_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment, 
1225                                      lpProcessAttributes, lpThreadAttributes,
1226                                      bInheritHandles, dwCreationFlags,
1227                                      lpStartupInfo, lpProcessInfo );
1228             break;
1229     
1230         case SCS_DOS_BINARY:
1231             retv = MZ_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment, 
1232                                      lpProcessAttributes, lpThreadAttributes,
1233                                      bInheritHandles, dwCreationFlags,
1234                                      lpStartupInfo, lpProcessInfo );
1235             break;
1236
1237         case SCS_WOW_BINARY:
1238             retv = NE_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment, 
1239                                      lpProcessAttributes, lpThreadAttributes,
1240                                      bInheritHandles, dwCreationFlags,
1241                                      lpStartupInfo, lpProcessInfo );
1242             break;
1243
1244         case SCS_PIF_BINARY:
1245         case SCS_POSIX_BINARY:
1246         case SCS_OS216_BINARY:
1247             FIXME_(module)("Unsupported executable type: %ld\n", type );
1248             /* fall through */
1249     
1250         default:
1251             SetLastError( ERROR_BAD_FORMAT );
1252             retv = FALSE;
1253             break;
1254         }
1255
1256         CloseHandle( hFile );
1257     }
1258     HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1259     return retv;
1260 }
1261
1262 /**********************************************************************
1263  *       CreateProcessW          (KERNEL32.172)
1264  * NOTES
1265  *  lpReserved is not converted
1266  */
1267 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine, 
1268                                 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1269                                 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1270                                 BOOL bInheritHandles, DWORD dwCreationFlags,
1271                                 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1272                                 LPSTARTUPINFOW lpStartupInfo,
1273                                 LPPROCESS_INFORMATION lpProcessInfo )
1274 {   BOOL ret;
1275     STARTUPINFOA StartupInfoA;
1276     
1277     LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1278     LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1279     LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1280
1281     memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1282     StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1283     StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1284
1285     TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1286
1287     if (lpStartupInfo->lpReserved)
1288       FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1289       
1290     ret = CreateProcessA(  lpApplicationNameA,  lpCommandLineA, 
1291                              lpProcessAttributes, lpThreadAttributes,
1292                              bInheritHandles, dwCreationFlags,
1293                              lpEnvironment, lpCurrentDirectoryA,
1294                              &StartupInfoA, lpProcessInfo );
1295
1296     HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1297     HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1298     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1299     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1300
1301     return ret;
1302 }
1303
1304 /***********************************************************************
1305  *              GetModuleHandle         (KERNEL32.237)
1306  */
1307 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1308 {
1309     WINE_MODREF *wm;
1310
1311     if ( module == NULL )
1312         wm = PROCESS_Current()->exe_modref;
1313     else
1314         wm = MODULE_FindModule( module );
1315
1316     return wm? wm->module : 0;
1317 }
1318
1319 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1320 {
1321     HMODULE hModule;
1322     LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1323     hModule = GetModuleHandleA( modulea );
1324     HeapFree( GetProcessHeap(), 0, modulea );
1325     return hModule;
1326 }
1327
1328
1329 /***********************************************************************
1330  *              GetModuleFileName32A      (KERNEL32.235)
1331  */
1332 DWORD WINAPI GetModuleFileNameA( 
1333         HMODULE hModule,        /* [in] module handle (32bit) */
1334         LPSTR lpFileName,       /* [out] filenamebuffer */
1335         DWORD size              /* [in] size of filenamebuffer */
1336 ) {                   
1337     WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1338
1339     if (!wm) /* can happen on start up or the like */
1340         return 0;
1341
1342     if (PE_HEADER(wm->module)->OptionalHeader.MajorOperatingSystemVersion >= 4.0)
1343       lstrcpynA( lpFileName, wm->longname, size );
1344     else
1345       lstrcpynA( lpFileName, wm->shortname, size );
1346        
1347     TRACE_(module)("%s\n", lpFileName );
1348     return strlen(lpFileName);
1349 }                   
1350  
1351
1352 /***********************************************************************
1353  *              GetModuleFileName32W      (KERNEL32.236)
1354  */
1355 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1356                                    DWORD size )
1357 {
1358     LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1359     DWORD res = GetModuleFileNameA( hModule, fnA, size );
1360     lstrcpynAtoW( lpFileName, fnA, size );
1361     HeapFree( GetProcessHeap(), 0, fnA );
1362     return res;
1363 }
1364
1365
1366 /***********************************************************************
1367  *           LoadLibraryEx32W   (KERNEL.513)
1368  */
1369 HMODULE WINAPI LoadLibraryEx32W16( LPCSTR libname, HANDLE16 hf,
1370                                    DWORD flags )
1371 {
1372     HMODULE hModule;
1373
1374     SYSLEVEL_ReleaseWin16Lock();
1375     hModule = LoadLibraryExA( libname, hf, flags );
1376     SYSLEVEL_RestoreWin16Lock();
1377
1378     return hModule;
1379 }
1380
1381 /***********************************************************************
1382  *           LoadLibrary32_16   (KERNEL.452)
1383  */
1384 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1385 {
1386     return LoadLibraryEx32W16( libname, 0, 0 );
1387 }
1388
1389 /***********************************************************************
1390  *           LoadLibraryExA   (KERNEL32)
1391  */
1392 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HFILE hfile, DWORD flags)
1393 {
1394         WINE_MODREF *wm;
1395
1396         if(!libname)
1397         {
1398                 SetLastError(ERROR_INVALID_PARAMETER);
1399                 return 0;
1400         }
1401
1402         EnterCriticalSection(&PROCESS_Current()->crit_section);
1403
1404         wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1405
1406         if(wm && !MODULE_DllProcessAttach(wm, NULL))
1407         {
1408                 WARN_(module)("Attach failed for module '%s', \n", libname);
1409                 MODULE_FreeLibrary(wm);
1410                 SetLastError(ERROR_DLL_INIT_FAILED);
1411                 wm = NULL;
1412         }
1413
1414         LeaveCriticalSection(&PROCESS_Current()->crit_section);
1415
1416         return wm ? wm->module : 0;
1417 }
1418
1419 /***********************************************************************
1420  *      MODULE_LoadLibraryExA   (internal)
1421  *
1422  * Load a PE style module according to the load order.
1423  *
1424  * The HFILE parameter is not used and marked reserved in the SDK. I can
1425  * only guess that it should force a file to be mapped, but I rather
1426  * ignore the parameter because it would be extremely difficult to
1427  * integrate this with different types of module represenations.
1428  *
1429  */
1430 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1431 {
1432         DWORD err;
1433         WINE_MODREF *pwm;
1434         int i;
1435         module_loadorder_t *plo;
1436
1437         EnterCriticalSection(&PROCESS_Current()->crit_section);
1438
1439         /* Check for already loaded module */
1440         if((pwm = MODULE_FindModule(libname))) 
1441         {
1442                 if(!(pwm->flags & WINE_MODREF_MARKER))
1443                         pwm->refCount++;
1444                 TRACE_(module)("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1445                 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1446                 return pwm;
1447         }
1448
1449         plo = MODULE_GetLoadOrder(libname);
1450
1451         for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1452         {
1453                 switch(plo->loadorder[i])
1454                 {
1455                 case MODULE_LOADORDER_DLL:
1456                         TRACE_(module)("Trying native dll '%s'\n", libname);
1457                         pwm = PE_LoadLibraryExA(libname, flags, &err);
1458                         break;
1459
1460                 case MODULE_LOADORDER_ELFDLL:
1461                         TRACE_(module)("Trying elfdll '%s'\n", libname);
1462                         pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1463                         break;
1464
1465                 case MODULE_LOADORDER_SO:
1466                         TRACE_(module)("Trying so-library '%s'\n", libname);
1467                         pwm = ELF_LoadLibraryExA(libname, flags, &err);
1468                         break;
1469
1470                 case MODULE_LOADORDER_BI:
1471                         TRACE_(module)("Trying built-in '%s'\n", libname);
1472                         pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1473                         break;
1474
1475                 default:
1476                         ERR_(module)("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1477                 /* Fall through */
1478
1479                 case MODULE_LOADORDER_INVALID:  /* We ignore this as it is an empty entry */
1480                         pwm = NULL;
1481                         break;
1482                 }
1483
1484                 if(pwm)
1485                 {
1486                         /* Initialize DLL just loaded */
1487                         TRACE_(module)("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1488
1489                         /* Set the refCount here so that an attach failure will */
1490                         /* decrement the dependencies through the MODULE_FreeLibrary call. */
1491                         pwm->refCount++;
1492
1493                         LeaveCriticalSection(&PROCESS_Current()->crit_section);
1494
1495                         if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1496                             DEBUG_SendLoadDLLEvent( -1 /*FIXME*/, pwm->module, pwm->modname );
1497                         
1498                         return pwm;
1499                 }
1500
1501                 if(err != ERROR_FILE_NOT_FOUND)
1502                         break;
1503         }
1504
1505         ERR_(module)("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1506         SetLastError(err);
1507         LeaveCriticalSection(&PROCESS_Current()->crit_section);
1508         return NULL;
1509 }
1510
1511 /***********************************************************************
1512  *           LoadLibraryA         (KERNEL32)
1513  */
1514 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1515         return LoadLibraryExA(libname,0,0);
1516 }
1517
1518 /***********************************************************************
1519  *           LoadLibraryW         (KERNEL32)
1520  */
1521 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1522 {
1523     return LoadLibraryExW(libnameW,0,0);
1524 }
1525
1526 /***********************************************************************
1527  *           LoadLibraryExW       (KERNEL32)
1528  */
1529 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HFILE hfile,DWORD flags)
1530 {
1531     LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1532     HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1533
1534     HeapFree( GetProcessHeap(), 0, libnameA );
1535     return ret;
1536 }
1537
1538 /***********************************************************************
1539  *           MODULE_FlushModrefs
1540  *
1541  * NOTE: Assumes that the process critical section is held!
1542  *
1543  * Remove all unused modrefs and call the internal unloading routines
1544  * for the library type.
1545  */
1546 static void MODULE_FlushModrefs(void)
1547 {
1548         WINE_MODREF *wm, *next;
1549
1550         for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1551         {
1552                 next = wm->next;
1553
1554                 if(wm->refCount)
1555                         continue;
1556
1557                 /* Unlink this modref from the chain */
1558                 if(wm->next)
1559                         wm->next->prev = wm->prev;
1560                 if(wm->prev)
1561                         wm->prev->next = wm->next;
1562                 if(wm == PROCESS_Current()->modref_list)
1563                         PROCESS_Current()->modref_list = wm->next;
1564
1565                 /* 
1566                  * The unloaders are also responsible for freeing the modref itself
1567                  * because the loaders were responsible for allocating it.
1568                  */
1569                 switch(wm->type)
1570                 {
1571                 case MODULE32_PE:       PE_UnloadLibrary(wm);           break;
1572                 case MODULE32_ELF:      ELF_UnloadLibrary(wm);          break;
1573                 case MODULE32_ELFDLL:   ELFDLL_UnloadLibrary(wm);       break;
1574                 case MODULE32_BI:       BUILTIN32_UnloadLibrary(wm);    break;
1575
1576                 default:
1577                         ERR_(module)("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1578                 }
1579         }
1580 }
1581
1582 /***********************************************************************
1583  *           FreeLibrary
1584  */
1585 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1586 {
1587     BOOL retv = FALSE;
1588     WINE_MODREF *wm;
1589
1590     EnterCriticalSection( &PROCESS_Current()->crit_section );
1591     PROCESS_Current()->free_lib_count++;
1592
1593     wm = MODULE32_LookupHMODULE( hLibModule );
1594     if ( !wm || !hLibModule )
1595         SetLastError( ERROR_INVALID_HANDLE );
1596     else
1597         retv = MODULE_FreeLibrary( wm );
1598
1599     PROCESS_Current()->free_lib_count--;
1600     LeaveCriticalSection( &PROCESS_Current()->crit_section );
1601
1602     return retv;
1603 }
1604
1605 /***********************************************************************
1606  *           MODULE_DecRefCount
1607  *
1608  * NOTE: Assumes that the process critical section is held!
1609  */
1610 static void MODULE_DecRefCount( WINE_MODREF *wm )
1611 {
1612     int i;
1613
1614     if ( wm->flags & WINE_MODREF_MARKER )
1615         return;
1616
1617     if ( wm->refCount <= 0 )
1618         return;
1619
1620     --wm->refCount;
1621     TRACE_(module)("(%s) refCount: %d\n", wm->modname, wm->refCount );
1622
1623     if ( wm->refCount == 0 )
1624     {
1625         wm->flags |= WINE_MODREF_MARKER;
1626
1627         for ( i = 0; i < wm->nDeps; i++ )
1628             if ( wm->deps[i] )
1629                 MODULE_DecRefCount( wm->deps[i] );
1630
1631         wm->flags &= ~WINE_MODREF_MARKER;
1632     }
1633 }
1634
1635 /***********************************************************************
1636  *           MODULE_FreeLibrary
1637  *
1638  * NOTE: Assumes that the process critical section is held!
1639  */
1640 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1641 {
1642     TRACE_(module)("(%s) - START\n", wm->modname );
1643
1644     /* Recursively decrement reference counts */
1645     MODULE_DecRefCount( wm );
1646
1647     /* Call process detach notifications */
1648     if ( PROCESS_Current()->free_lib_count <= 1 )
1649     {
1650         MODULE_DllProcessDetach( FALSE, NULL );
1651         if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1652             DEBUG_SendUnloadDLLEvent( wm->module );
1653     }
1654
1655     MODULE_FlushModrefs();
1656
1657     TRACE_(module)("(%s) - END\n", wm->modname );
1658
1659     return TRUE;
1660 }
1661
1662
1663 /***********************************************************************
1664  *           FreeLibraryAndExitThread
1665  */
1666 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1667 {
1668     FreeLibrary(hLibModule);
1669     ExitThread(dwExitCode);
1670 }
1671
1672 /***********************************************************************
1673  *           PrivateLoadLibrary       (KERNEL32)
1674  *
1675  * FIXME: rough guesswork, don't know what "Private" means
1676  */
1677 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1678 {
1679         return (HINSTANCE)LoadLibrary16(libname);
1680 }
1681
1682
1683
1684 /***********************************************************************
1685  *           PrivateFreeLibrary       (KERNEL32)
1686  *
1687  * FIXME: rough guesswork, don't know what "Private" means
1688  */
1689 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1690 {
1691         FreeLibrary16((HINSTANCE16)handle);
1692 }
1693
1694
1695 /***********************************************************************
1696  *           WIN32_GetProcAddress16   (KERNEL32.36)
1697  * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1698  */
1699 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1700 {
1701     WORD        ordinal;
1702     FARPROC16   ret;
1703
1704     if (!hModule) {
1705         WARN_(module)("hModule may not be 0!\n");
1706         return (FARPROC16)0;
1707     }
1708     if (HIWORD(hModule))
1709     {
1710         WARN_(module)("hModule is Win32 handle (%08x)\n", hModule );
1711         return (FARPROC16)0;
1712     }
1713     hModule = GetExePtr( hModule );
1714     if (HIWORD(name)) {
1715         ordinal = NE_GetOrdinal( hModule, name );
1716         TRACE_(module)("%04x '%s'\n",
1717                         hModule, name );
1718     } else {
1719         ordinal = LOWORD(name);
1720         TRACE_(module)("%04x %04x\n",
1721                         hModule, ordinal );
1722     }
1723     if (!ordinal) return (FARPROC16)0;
1724     ret = NE_GetEntryPoint( hModule, ordinal );
1725     TRACE_(module)("returning %08x\n",(UINT)ret);
1726     return ret;
1727 }
1728
1729 /***********************************************************************
1730  *           GetProcAddress16   (KERNEL.50)
1731  */
1732 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1733 {
1734     WORD ordinal;
1735     FARPROC16 ret;
1736
1737     if (!hModule) hModule = GetCurrentTask();
1738     hModule = GetExePtr( hModule );
1739
1740     if (HIWORD(name) != 0)
1741     {
1742         ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1743         TRACE_(module)("%04x '%s'\n",
1744                         hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1745     }
1746     else
1747     {
1748         ordinal = LOWORD(name);
1749         TRACE_(module)("%04x %04x\n",
1750                         hModule, ordinal );
1751     }
1752     if (!ordinal) return (FARPROC16)0;
1753
1754     ret = NE_GetEntryPoint( hModule, ordinal );
1755
1756     TRACE_(module)("returning %08x\n", (UINT)ret );
1757     return ret;
1758 }
1759
1760
1761 /***********************************************************************
1762  *           GetProcAddress32                   (KERNEL32.257)
1763  */
1764 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1765 {
1766     return MODULE_GetProcAddress( hModule, function, TRUE );
1767 }
1768
1769 /***********************************************************************
1770  *           WIN16_GetProcAddress32             (KERNEL.453)
1771  */
1772 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1773 {
1774     return MODULE_GetProcAddress( hModule, function, FALSE );
1775 }
1776
1777 /***********************************************************************
1778  *           MODULE_GetProcAddress32            (internal)
1779  */
1780 FARPROC MODULE_GetProcAddress( 
1781         HMODULE hModule,        /* [in] current module handle */
1782         LPCSTR function,        /* [in] function to be looked up */
1783         BOOL snoop )
1784 {
1785     WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1786     FARPROC     retproc;
1787
1788     if (HIWORD(function))
1789         TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1790     else
1791         TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1792     if (!wm) {
1793         SetLastError(ERROR_INVALID_HANDLE);
1794         return (FARPROC)0;
1795     }
1796     switch (wm->type)
1797     {
1798     case MODULE32_PE:
1799         retproc = PE_FindExportedFunction( wm, function, snoop );
1800         if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1801         return retproc;
1802     case MODULE32_ELF:
1803         retproc = ELF_FindExportedFunction( wm, function);
1804         if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1805         return retproc;
1806     default:
1807         ERR_(module)("wine_modref type %d not handled.\n",wm->type);
1808         SetLastError(ERROR_INVALID_HANDLE);
1809         return (FARPROC)0;
1810     }
1811 }
1812
1813
1814 /***********************************************************************
1815  *           RtlImageNtHeaders   (NTDLL)
1816  */
1817 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1818 {
1819     /* basically:
1820      * return  hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew); 
1821      * but we could get HMODULE16 or the like (think builtin modules)
1822      */
1823
1824     WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1825     if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1826     return PE_HEADER(wm->module);
1827 }
1828
1829
1830 /***************************************************************************
1831  *              HasGPHandler                    (KERNEL.338)
1832  */
1833
1834 #include "pshpack1.h"
1835 typedef struct _GPHANDLERDEF
1836 {
1837     WORD selector;
1838     WORD rangeStart;
1839     WORD rangeEnd;
1840     WORD handler;
1841 } GPHANDLERDEF;
1842 #include "poppack.h"
1843
1844 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1845 {
1846     HMODULE16 hModule;
1847     int gpOrdinal;
1848     SEGPTR gpPtr;
1849     GPHANDLERDEF *gpHandler;
1850    
1851     if (    (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1852          && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1853          && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1854          && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1855          && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1856     {
1857         while (gpHandler->selector)
1858         {
1859             if (    SELECTOROF(address) == gpHandler->selector
1860                  && OFFSETOF(address)   >= gpHandler->rangeStart
1861                  && OFFSETOF(address)   <  gpHandler->rangeEnd  )
1862                 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1863                                               gpHandler->handler );
1864             gpHandler++;
1865         }
1866     }
1867
1868     return 0;
1869 }
1870