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