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