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