Delay sending debug events until process initialization is complete.
[wine] / loader / module.c
1 /*
2  * Modules
3  *
4  * Copyright 1995 Alexandre Julliard
5  */
6
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <sys/types.h>
12 #include <unistd.h>
13 #include "wine/winuser16.h"
14 #include "wine/winbase16.h"
15 #include "windef.h"
16 #include "winerror.h"
17 #include "file.h"
18 #include "global.h"
19 #include "heap.h"
20 #include "module.h"
21 #include "snoop.h"
22 #include "neexe.h"
23 #include "pe_image.h"
24 #include "dosexe.h"
25 #include "process.h"
26 #include "thread.h"
27 #include "selectors.h"
28 #include "stackframe.h"
29 #include "task.h"
30 #include "debugtools.h"
31 #include "callback.h"
32 #include "loadorder.h"
33 #include "elfdll.h"
34
35 DECLARE_DEBUG_CHANNEL(module)
36 DECLARE_DEBUG_CHANNEL(win32)
37
38 /*************************************************************************
39  *              MODULE_WalkModref
40  * Walk MODREFs for input process ID
41  */
42 void MODULE_WalkModref( DWORD id )
43 {
44     int i;
45     WINE_MODREF  *zwm, *prev = NULL;
46     PDB *pdb = PROCESS_IdToPDB( id );
47
48     if (!pdb) {
49         MESSAGE("Invalid process id (pid)\n");
50         return;
51     }
52
53     MESSAGE("Modref list for process pdb=%p\n", pdb);
54     MESSAGE("Modref     next       prev        handle  deps  flags  name\n");
55     for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
56         MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
57                zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
58         for ( i = 0; i < zwm->nDeps; i++ ) {
59             if ( zwm->deps[i] )
60                 MESSAGE("    %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
61         }
62         if (prev != zwm->prev) 
63             MESSAGE("   --> modref corrupt, previous pointer wrong!!\n");
64         prev = zwm;
65     }
66 }
67
68 /*************************************************************************
69  *              MODULE32_LookupHMODULE
70  * looks for the referenced HMODULE in the current process
71  */
72 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
73 {
74     WINE_MODREF *wm;
75
76     if (!hmod) 
77         return PROCESS_Current()->exe_modref;
78
79     if (!HIWORD(hmod)) {
80         ERR_(module)("tried to lookup 0x%04x in win32 module handler!\n",hmod);
81         return NULL;
82     }
83     for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
84         if (wm->module == hmod)
85             return wm;
86     return NULL;
87 }
88
89 /*************************************************************************
90  *              MODULE_InitDll
91  */
92 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
93 {
94     BOOL retv = TRUE;
95
96     static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH", 
97                                  "THREAD_ATTACH", "THREAD_DETACH" };
98     assert( wm );
99
100
101     /* Skip calls for modules loaded with special load flags */
102
103     if (    ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
104          || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
105         return TRUE;
106
107
108     TRACE_(module)("(%s,%s,%p) - CALL\n", 
109            wm->modname, typeName[type], lpReserved );
110
111     /* Call the initialization routine */
112     switch ( wm->type )
113     {
114     case MODULE32_PE:
115         retv = PE_InitDLL( wm, type, lpReserved );
116         break;
117
118     case MODULE32_ELF:
119         /* no need to do that, dlopen() already does */
120         break;
121
122     default:
123         ERR_(module)("wine_modref type %d not handled.\n", wm->type );
124         retv = FALSE;
125         break;
126     }
127
128     TRACE_(module)("(%s,%s,%p) - RETURN %d\n", 
129            wm->modname, typeName[type], lpReserved, retv );
130
131     return retv;
132 }
133
134 /*************************************************************************
135  *              MODULE_DllProcessAttach
136  * 
137  * Send the process attach notification to all DLLs the given module
138  * depends on (recursively). This is somewhat complicated due to the fact that
139  *
140  * - we have to respect the module dependencies, i.e. modules implicitly
141  *   referenced by another module have to be initialized before the module
142  *   itself can be initialized
143  * 
144  * - the initialization routine of a DLL can itself call LoadLibrary,
145  *   thereby introducing a whole new set of dependencies (even involving
146  *   the 'old' modules) at any time during the whole process
147  *
148  * (Note that this routine can be recursively entered not only directly
149  *  from itself, but also via LoadLibrary from one of the called initialization
150  *  routines.)
151  *
152  * Furthermore, we need to rearrange the main WINE_MODREF list to allow
153  * the process *detach* notifications to be sent in the correct order.
154  * This must not only take into account module dependencies, but also 
155  * 'hidden' dependencies created by modules calling LoadLibrary in their
156  * attach notification routine.
157  *
158  * The strategy is rather simple: we move a WINE_MODREF to the head of the
159  * list after the attach notification has returned.  This implies that the
160  * detach notifications are called in the reverse of the sequence the attach
161  * notifications *returned*.
162  *
163  * NOTE: Assumes that the process critical section is held!
164  *
165  */
166 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
167 {
168     BOOL retv = TRUE;
169     int i;
170     assert( wm );
171
172     /* prevent infinite recursion in case of cyclical dependencies */
173     if (    ( wm->flags & WINE_MODREF_MARKER )
174          || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
175         return retv;
176
177     TRACE_(module)("(%s,%p) - START\n", 
178            wm->modname, lpReserved );
179
180     /* Tag current MODREF to prevent recursive loop */
181     wm->flags |= WINE_MODREF_MARKER;
182
183     /* Recursively attach all DLLs this one depends on */
184     for ( i = 0; retv && i < wm->nDeps; i++ )
185         if ( wm->deps[i] )
186             retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
187
188     /* Call DLL entry point */
189     if ( retv )
190     {
191         retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
192         if ( retv )
193             wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
194     }
195
196     /* Re-insert MODREF at head of list */
197     if ( retv && wm->prev )
198     {
199         wm->prev->next = wm->next;
200         if ( wm->next ) wm->next->prev = wm->prev;
201
202         wm->prev = NULL;
203         wm->next = PROCESS_Current()->modref_list;
204         PROCESS_Current()->modref_list = wm->next->prev = wm;
205     }
206
207     /* Remove recursion flag */
208     wm->flags &= ~WINE_MODREF_MARKER;
209
210     TRACE_(module)("(%s,%p) - END\n", 
211            wm->modname, lpReserved );
212
213     return retv;
214 }
215
216 /*************************************************************************
217  *              MODULE_DllProcessDetach
218  * 
219  * Send DLL process detach notifications.  See the comment about calling 
220  * sequence at MODULE_DllProcessAttach.  Unless the bForceDetach flag
221  * is set, only DLLs with zero refcount are notified.
222  *
223  * NOTE: Assumes that the process critical section is held!
224  *
225  */
226 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
227 {
228     WINE_MODREF *wm;
229
230     do
231     {
232         for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
233         {
234             /* Check whether to detach this DLL */
235             if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
236                 continue;
237             if ( wm->refCount > 0 && !bForceDetach )
238                 continue;
239
240             /* Call detach notification */
241             wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
242             MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
243
244             /* Restart at head of WINE_MODREF list, as entries might have
245                been added and/or removed while performing the call ... */
246             break;
247         }
248     } while ( wm );
249 }
250
251 /*************************************************************************
252  *              MODULE_DllThreadAttach
253  * 
254  * Send DLL thread attach notifications. These are sent in the
255  * reverse sequence of process detach notification.
256  *
257  */
258 void MODULE_DllThreadAttach( LPVOID lpReserved )
259 {
260     WINE_MODREF *wm;
261
262     EnterCriticalSection( &PROCESS_Current()->crit_section );
263
264     for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
265         if ( !wm->next )
266             break;
267
268     for ( ; wm; wm = wm->prev )
269     {
270         if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
271             continue;
272         if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
273             continue;
274
275         MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
276     }
277
278     LeaveCriticalSection( &PROCESS_Current()->crit_section );
279 }
280
281 /*************************************************************************
282  *              MODULE_DllThreadDetach
283  * 
284  * Send DLL thread detach notifications. These are sent in the
285  * same sequence as process detach notification.
286  *
287  */
288 void MODULE_DllThreadDetach( LPVOID lpReserved )
289 {
290     WINE_MODREF *wm;
291
292     EnterCriticalSection( &PROCESS_Current()->crit_section );
293
294     for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
295     {
296         if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
297             continue;
298         if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
299             continue;
300
301         MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
302     }
303
304     LeaveCriticalSection( &PROCESS_Current()->crit_section );
305 }
306
307 /****************************************************************************
308  *              DisableThreadLibraryCalls (KERNEL32.74)
309  *
310  * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
311  */
312 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
313 {
314     WINE_MODREF *wm;
315     BOOL retval = TRUE;
316
317     EnterCriticalSection( &PROCESS_Current()->crit_section );
318
319     wm = MODULE32_LookupHMODULE( hModule );
320     if ( !wm )
321         retval = FALSE;
322     else
323         wm->flags |= WINE_MODREF_NO_DLL_CALLS;
324
325     LeaveCriticalSection( &PROCESS_Current()->crit_section );
326
327     return retval;
328 }
329
330 /*************************************************************************
331  *              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     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     *pStr = len;
435     strncpy( pStr+1, basename, len );
436     pStr[len+1] = 0;
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 presend it will
505  * assume that that the file is a DOS executable.
506  * If the extended header information is present it will
507  * determine if the file is an 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_(module)("Strange error set by CreateProcess: %d\n", hInstance );
836         return 11;
837     }
838     
839     /* Get 16-bit hInstance/hTask from process */
840     pdb = PROCESS_IdToPDB( info.dwProcessId );
841     tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
842     hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
843     /* If there is no hInstance (32-bit process) return a dummy value
844      * that must be > 31
845      * FIXME: should do this in all cases and fix Win16 callers */
846     if (!hInstance) hInstance = 33;
847
848     /* Close off the handles */
849     CloseHandle( info.hThread );
850     CloseHandle( info.hProcess );
851
852     return hInstance;
853 }
854
855 /*************************************************************************
856  *               get_makename_token
857  * 
858  * Get next blank delimited token from input string. If quoted then 
859  * process till matching quote and then till blank.
860  *
861  * Returns number of characters in token (not including \0). On 
862  * end of string (EOS), returns a 0.
863  *
864  *    from  (IO)  address of start of input string to scan, updated to 
865  *                next non-processed character.
866  *    to    (IO)  address of start of output string (previous token \0 
867  *                char), updated to end of new output string (the \0
868  *                char).
869  */
870 static int get_makename_token(LPCSTR *from, LPSTR *to )
871 {
872     int len = 0;
873     LPCSTR to_old = *to;   /* only used for tracing */
874
875     while ( **from == ' ') {
876       /* Copy leading blanks (separators between previous    */
877       /* token and this token).                              */
878       **to = **from;
879       (*from)++;
880       (*to)++;
881       len++;
882     }
883     do {
884       while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
885           **to = **from; (*from)++; (*to)++; len++;
886       }
887       if ( **from == '"' ) {
888         /* Handle quoted string. */
889         (*from)++;
890         if ( !strchr(*from, '"') ) {
891           /* fail - no closing quote. Return entire string */
892           while ( **from != 0 ) {
893              **to = **from; (*from)++; (*to)++; len++;
894           }
895           break;
896         }
897         while( **from != '"') { 
898             **to = **from;
899             len++;
900             (*to)++;
901             (*from)++;
902         }
903         (*from)++;
904         continue;
905       }
906
907       /* either EOS or ' ' */
908       break;
909
910     } while (1);
911
912     **to = 0;   /* terminate output string */
913
914     TRACE_(module)("returning token len=%d, string=%s\n",
915               len, to_old);
916
917     return len;     
918 }
919
920 /*************************************************************************
921  *              make_lpCommandLine_name
922  * 
923  * Try longer and longer strings from "line" to find an existing
924  * file name. Each attempt is delimited by a blank outside of quotes.
925  * Also will attempt to append ".exe" if requested and not already
926  * present. Returns the address of the remaining portion of the
927  * input line.
928  *
929  */
930
931 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
932                                  LPCSTR *after )
933 {
934     BOOL  found = TRUE;
935     LPCSTR from;
936     char  buffer[260];
937     DWORD  retlen;
938     LPSTR to, lastpart;
939     
940     from = line;
941     to = name;
942
943     /* scan over initial blanks if any */
944     while ( *from == ' ') from++;
945
946     /* get a token and append to previous data the check for existance */
947     do {
948         if ( !get_makename_token( &from, &to ) ) {
949           /* EOS has occured and not found - exit */
950           retlen = 0;
951           found = FALSE;
952           break;
953         }
954         TRACE_(module)("checking if file exists '%s'\n", name);
955         retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
956         if ( retlen && (retlen < sizeof(buffer)) )  break;
957     } while (1);
958
959     /* if we have a non-null full path name in buffer then move to output */
960     if ( retlen ) {
961        if ( strlen(buffer) <= namelen ) {
962           strcpy( name, buffer );
963        } else {
964           /* not enough space to return full path string */
965           FIXME_(module)("internal string not long enough, need %d\n",
966              strlen(buffer) );
967         }
968     }
969
970     /* all done, indicate end of module name and then trace and exit */
971     if (after) *after = from;
972     TRACE_(module)("%i, selected file name '%s'\n    and cmdline as %s\n",
973             found, name, debugstr_a(from));
974     return found;
975     }
976
977 /*************************************************************************
978  *              make_lpApplicationName_name
979  * 
980  * Scan input string (the lpApplicationName) and remove any quotes
981  * if they are balanced. 
982  *
983  */
984
985 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
986 {
987     LPCSTR from;
988     LPSTR to, to_end, to_old;
989     char  buffer[260];
990
991     to = buffer;
992     to_end = to + sizeof(buffer) - 1;
993     to_old = to;
994     
995     while ( *line == ' ' ) line++;  /* point to beginning of string */
996     from = line;
997     do {
998         /* Copy all input till end, or quote */
999         while((*from != 0) && (*from != '"') && (to < to_end)) 
1000            *to++ = *from++;
1001         if (to >= to_end) { *to = 0; break; }
1002
1003         if (*from == '"')
1004           {
1005             /* Handle quoted string. If there is a closing quote, copy all */
1006             /* that is inside.                                             */
1007             from++;
1008             if (!strchr(from, '"'))
1009               {
1010                 /* fail - no closing quote */
1011                 to = to_old; /* restore to previous attempt */
1012                 *to = 0;     /* end string  */
1013                 break;       /* exit with  previous attempt */
1014               }
1015             while((*from != '"') && (to < to_end)) *to++ = *from++;
1016             if (to >= to_end) { *to = 0; break; }
1017             from++;
1018             continue;  /* past quoted string, so restart from top */
1019           }
1020
1021         *to = 0;   /* terminate output string */
1022         to_old = to;   /* save for possible use in unmatched quote case */
1023
1024         /* loop around keeping the blank as part of file name */
1025         if (!*from)
1026           break;    /* exit if out of input string */
1027     } while (1);
1028
1029     if (!SearchPathA( NULL, buffer, ".exe", namelen, name, NULL )) {
1030         TRACE_(module)("file not found '%s'\n", buffer );
1031         return FALSE;
1032     }
1033
1034     TRACE_(module)("selected as file name '%s'\n", name );
1035     return TRUE;
1036 }
1037
1038 /**********************************************************************
1039  *       CreateProcessA          (KERNEL32.171)
1040  */
1041 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine, 
1042                             LPSECURITY_ATTRIBUTES lpProcessAttributes,
1043                             LPSECURITY_ATTRIBUTES lpThreadAttributes,
1044                             BOOL bInheritHandles, DWORD dwCreationFlags,
1045                             LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1046                             LPSTARTUPINFOA lpStartupInfo,
1047                             LPPROCESS_INFORMATION lpProcessInfo )
1048 {
1049     BOOL retv = FALSE;
1050     BOOL found_file = FALSE;
1051     HANDLE hFile;
1052     DWORD type;
1053     char name[256], dummy[256];
1054     LPCSTR cmdline = NULL;
1055     LPSTR tidy_cmdline;
1056     int len = 0;
1057
1058     /* Get name and command line */
1059
1060     if (!lpApplicationName && !lpCommandLine)
1061     {
1062         SetLastError( ERROR_FILE_NOT_FOUND );
1063         return FALSE;
1064     }
1065
1066     /* Process the AppName and/or CmdLine to get module name and path */
1067
1068     name[0] = '\0';
1069
1070     if (lpApplicationName) {
1071        found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1072        if (lpCommandLine) {
1073           make_lpCommandLine_name( lpCommandLine, dummy, sizeof ( dummy ), &cmdline );
1074     }
1075        else {
1076           cmdline = lpApplicationName;
1077        }
1078        len += strlen(lpApplicationName);
1079     }
1080     else {
1081        found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1082        if (lpCommandLine) len = strlen(lpCommandLine);
1083     }
1084
1085     if ( !found_file ) {
1086         /* make an early exit if file not found - save second pass */
1087         SetLastError( ERROR_FILE_NOT_FOUND );
1088         return FALSE;
1089     }
1090
1091     len += strlen(name) + 2;
1092     tidy_cmdline = HeapAlloc( GetProcessHeap(), 0, len );
1093     sprintf( tidy_cmdline, "\"%s\"%s", name, cmdline);
1094
1095     /* Warn if unsupported features are used */
1096
1097     if (dwCreationFlags & DETACHED_PROCESS)
1098         FIXME_(module)("(%s,...): DETACHED_PROCESS ignored\n", name);
1099     if (dwCreationFlags & CREATE_NEW_CONSOLE)
1100         FIXME_(module)("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1101     if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1102         FIXME_(module)("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1103     if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1104         FIXME_(module)("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1105     if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1106         FIXME_(module)("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1107     if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1108         FIXME_(module)("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1109     if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1110         FIXME_(module)("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1111     if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1112         FIXME_(module)("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1113     if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1114         FIXME_(module)("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1115     if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1116         FIXME_(module)("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1117     if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1118         FIXME_(module)("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1119     if (dwCreationFlags & CREATE_NO_WINDOW)
1120         FIXME_(module)("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1121     if (dwCreationFlags & PROFILE_USER)
1122         FIXME_(module)("(%s,...): PROFILE_USER ignored\n", name);
1123     if (dwCreationFlags & PROFILE_KERNEL)
1124         FIXME_(module)("(%s,...): PROFILE_KERNEL ignored\n", name);
1125     if (dwCreationFlags & PROFILE_SERVER)
1126         FIXME_(module)("(%s,...): PROFILE_SERVER ignored\n", name);
1127     if (lpCurrentDirectory)
1128         FIXME_(module)("(%s,...): lpCurrentDirectory %s ignored\n", 
1129                       name, lpCurrentDirectory);
1130     if (lpStartupInfo->lpDesktop)
1131         FIXME_(module)("(%s,...): lpStartupInfo->lpDesktop %s ignored\n", 
1132                       name, lpStartupInfo->lpDesktop);
1133     if (lpStartupInfo->lpTitle)
1134         FIXME_(module)("(%s,...): lpStartupInfo->lpTitle %s ignored\n", 
1135                       name, lpStartupInfo->lpTitle);
1136     if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1137         FIXME_(module)("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n", 
1138                       name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1139     if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1140         FIXME_(module)("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n", 
1141                       name, lpStartupInfo->dwFillAttribute);
1142     if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1143         FIXME_(module)("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1144     if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1145         FIXME_(module)("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1146     if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1147         FIXME_(module)("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1148     if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1149         FIXME_(module)("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1150
1151
1152     /* Load file and create process */
1153
1154     if ( !retv )
1155     {
1156         /* Open file and determine executable type */
1157
1158         hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
1159                              NULL, OPEN_EXISTING, 0, -1 );
1160         if ( hFile == INVALID_HANDLE_VALUE )
1161         {
1162             SetLastError( ERROR_FILE_NOT_FOUND );
1163             HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1164             return FALSE;
1165         }
1166
1167         if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1168         {
1169             CloseHandle( hFile );
1170
1171             /* FIXME: Try Unix executable only when appropriate! */
1172             if ( MODULE_CreateUnixProcess( name, tidy_cmdline, 
1173                                            lpStartupInfo, lpProcessInfo, FALSE ) )
1174             {
1175                 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1176                 return TRUE;
1177             }
1178             HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1179             SetLastError( ERROR_BAD_FORMAT );
1180             return FALSE;
1181         }
1182
1183
1184         /* Create process */
1185
1186         switch ( type )
1187         {
1188         case SCS_32BIT_BINARY:
1189             retv = PE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment, 
1190                                      lpProcessAttributes, lpThreadAttributes,
1191                                      bInheritHandles, dwCreationFlags,
1192                                      lpStartupInfo, lpProcessInfo );
1193             break;
1194     
1195         case SCS_DOS_BINARY:
1196             retv = MZ_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment, 
1197                                      lpProcessAttributes, lpThreadAttributes,
1198                                      bInheritHandles, dwCreationFlags,
1199                                      lpStartupInfo, lpProcessInfo );
1200             break;
1201
1202         case SCS_WOW_BINARY:
1203             retv = NE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment, 
1204                                      lpProcessAttributes, lpThreadAttributes,
1205                                      bInheritHandles, dwCreationFlags,
1206                                      lpStartupInfo, lpProcessInfo );
1207             break;
1208
1209         case SCS_PIF_BINARY:
1210         case SCS_POSIX_BINARY:
1211         case SCS_OS216_BINARY:
1212             FIXME_(module)("Unsupported executable type: %ld\n", type );
1213             /* fall through */
1214     
1215         default:
1216             SetLastError( ERROR_BAD_FORMAT );
1217             retv = FALSE;
1218             break;
1219         }
1220
1221         CloseHandle( hFile );
1222     }
1223     HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1224     return retv;
1225 }
1226
1227 /**********************************************************************
1228  *       CreateProcessW          (KERNEL32.172)
1229  * NOTES
1230  *  lpReserved is not converted
1231  */
1232 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine, 
1233                                 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1234                                 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1235                                 BOOL bInheritHandles, DWORD dwCreationFlags,
1236                                 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1237                                 LPSTARTUPINFOW lpStartupInfo,
1238                                 LPPROCESS_INFORMATION lpProcessInfo )
1239 {   BOOL ret;
1240     STARTUPINFOA StartupInfoA;
1241     
1242     LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1243     LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1244     LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1245
1246     memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1247     StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1248     StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1249
1250     TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1251
1252     if (lpStartupInfo->lpReserved)
1253       FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1254       
1255     ret = CreateProcessA(  lpApplicationNameA,  lpCommandLineA, 
1256                              lpProcessAttributes, lpThreadAttributes,
1257                              bInheritHandles, dwCreationFlags,
1258                              lpEnvironment, lpCurrentDirectoryA,
1259                              &StartupInfoA, lpProcessInfo );
1260
1261     HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1262     HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1263     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1264     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1265
1266     return ret;
1267 }
1268
1269 /***********************************************************************
1270  *              GetModuleHandle         (KERNEL32.237)
1271  */
1272 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1273 {
1274     WINE_MODREF *wm;
1275
1276     if ( module == NULL )
1277         wm = PROCESS_Current()->exe_modref;
1278     else
1279         wm = MODULE_FindModule( module );
1280
1281     return wm? wm->module : 0;
1282 }
1283
1284 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1285 {
1286     HMODULE hModule;
1287     LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1288     hModule = GetModuleHandleA( modulea );
1289     HeapFree( GetProcessHeap(), 0, modulea );
1290     return hModule;
1291 }
1292
1293
1294 /***********************************************************************
1295  *              GetModuleFileName32A      (KERNEL32.235)
1296  */
1297 DWORD WINAPI GetModuleFileNameA( 
1298         HMODULE hModule,        /* [in] module handle (32bit) */
1299         LPSTR lpFileName,       /* [out] filenamebuffer */
1300         DWORD size              /* [in] size of filenamebuffer */
1301 ) {                   
1302     WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1303
1304     if (!wm) /* can happen on start up or the like */
1305         return 0;
1306
1307     if (PE_HEADER(wm->module)->OptionalHeader.MajorOperatingSystemVersion >= 4.0)
1308       lstrcpynA( lpFileName, wm->filename, size );
1309     else
1310       lstrcpynA( lpFileName, wm->short_filename, size );
1311        
1312     TRACE_(module)("%s\n", lpFileName );
1313     return strlen(lpFileName);
1314 }                   
1315  
1316
1317 /***********************************************************************
1318  *              GetModuleFileName32W      (KERNEL32.236)
1319  */
1320 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1321                                    DWORD size )
1322 {
1323     LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1324     DWORD res = GetModuleFileNameA( hModule, fnA, size );
1325     lstrcpynAtoW( lpFileName, fnA, size );
1326     HeapFree( GetProcessHeap(), 0, fnA );
1327     return res;
1328 }
1329
1330
1331 /***********************************************************************
1332  *           LoadLibraryExA   (KERNEL32)
1333  */
1334 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1335 {
1336         WINE_MODREF *wm;
1337
1338         if(!libname)
1339         {
1340                 SetLastError(ERROR_INVALID_PARAMETER);
1341                 return 0;
1342         }
1343
1344         EnterCriticalSection(&PROCESS_Current()->crit_section);
1345
1346         wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1347         if ( wm )
1348         {
1349                 if ( PROCESS_Current()->flags & PDB32_DEBUGGED )
1350                         MODULE_SendLoadDLLEvents();
1351                         
1352                 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1353                 {
1354                         WARN_(module)("Attach failed for module '%s', \n", libname);
1355                         MODULE_FreeLibrary(wm);
1356                         SetLastError(ERROR_DLL_INIT_FAILED);
1357                         wm = NULL;
1358                 }
1359         }
1360
1361         LeaveCriticalSection(&PROCESS_Current()->crit_section);
1362
1363         return wm ? wm->module : 0;
1364 }
1365
1366 /***********************************************************************
1367  *      MODULE_LoadLibraryExA   (internal)
1368  *
1369  * Load a PE style module according to the load order.
1370  *
1371  * The HFILE parameter is not used and marked reserved in the SDK. I can
1372  * only guess that it should force a file to be mapped, but I rather
1373  * ignore the parameter because it would be extremely difficult to
1374  * integrate this with different types of module represenations.
1375  *
1376  */
1377 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1378 {
1379         DWORD err;
1380         WINE_MODREF *pwm;
1381         int i;
1382         module_loadorder_t *plo;
1383
1384         EnterCriticalSection(&PROCESS_Current()->crit_section);
1385
1386         /* Check for already loaded module */
1387         if((pwm = MODULE_FindModule(libname))) 
1388         {
1389                 if(!(pwm->flags & WINE_MODREF_MARKER))
1390                         pwm->refCount++;
1391                 TRACE_(module)("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1392                 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1393                 return pwm;
1394         }
1395
1396         plo = MODULE_GetLoadOrder(libname);
1397
1398         for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1399         {
1400                 switch(plo->loadorder[i])
1401                 {
1402                 case MODULE_LOADORDER_DLL:
1403                         TRACE_(module)("Trying native dll '%s'\n", libname);
1404                         pwm = PE_LoadLibraryExA(libname, flags, &err);
1405                         break;
1406
1407                 case MODULE_LOADORDER_ELFDLL:
1408                         TRACE_(module)("Trying elfdll '%s'\n", libname);
1409                         pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1410                         break;
1411
1412                 case MODULE_LOADORDER_SO:
1413                         TRACE_(module)("Trying so-library '%s'\n", libname);
1414                         pwm = ELF_LoadLibraryExA(libname, flags, &err);
1415                         break;
1416
1417                 case MODULE_LOADORDER_BI:
1418                         TRACE_(module)("Trying built-in '%s'\n", libname);
1419                         pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1420                         break;
1421
1422                 default:
1423                         ERR_(module)("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1424                 /* Fall through */
1425
1426                 case MODULE_LOADORDER_INVALID:  /* We ignore this as it is an empty entry */
1427                         pwm = NULL;
1428                         break;
1429                 }
1430
1431                 if(pwm)
1432                 {
1433                         /* Initialize DLL just loaded */
1434                         TRACE_(module)("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1435
1436                         /* Set the refCount here so that an attach failure will */
1437                         /* decrement the dependencies through the MODULE_FreeLibrary call. */
1438                         pwm->refCount++;
1439
1440                         LeaveCriticalSection(&PROCESS_Current()->crit_section);
1441
1442                         return pwm;
1443                 }
1444
1445                 if(err != ERROR_FILE_NOT_FOUND)
1446                         break;
1447         }
1448
1449         WARN_(module)("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1450         SetLastError(err);
1451         LeaveCriticalSection(&PROCESS_Current()->crit_section);
1452         return NULL;
1453 }
1454
1455 /***********************************************************************
1456  *           LoadLibraryA         (KERNEL32)
1457  */
1458 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1459         return LoadLibraryExA(libname,0,0);
1460 }
1461
1462 /***********************************************************************
1463  *           LoadLibraryW         (KERNEL32)
1464  */
1465 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1466 {
1467     return LoadLibraryExW(libnameW,0,0);
1468 }
1469
1470 /***********************************************************************
1471  *           LoadLibrary32_16   (KERNEL.452)
1472  */
1473 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1474 {
1475     HMODULE hModule;
1476
1477     SYSLEVEL_ReleaseWin16Lock();
1478     hModule = LoadLibraryA( libname );
1479     SYSLEVEL_RestoreWin16Lock();
1480
1481     return hModule;
1482 }
1483
1484 /***********************************************************************
1485  *           LoadLibraryExW       (KERNEL32)
1486  */
1487 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1488 {
1489     LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1490     HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1491
1492     HeapFree( GetProcessHeap(), 0, libnameA );
1493     return ret;
1494 }
1495
1496 /***********************************************************************
1497  *           MODULE_FlushModrefs
1498  *
1499  * NOTE: Assumes that the process critical section is held!
1500  *
1501  * Remove all unused modrefs and call the internal unloading routines
1502  * for the library type.
1503  */
1504 static void MODULE_FlushModrefs(void)
1505 {
1506         WINE_MODREF *wm, *next;
1507
1508         for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1509         {
1510                 next = wm->next;
1511
1512                 if(wm->refCount)
1513                         continue;
1514
1515                 /* Unlink this modref from the chain */
1516                 if(wm->next)
1517                         wm->next->prev = wm->prev;
1518                 if(wm->prev)
1519                         wm->prev->next = wm->next;
1520                 if(wm == PROCESS_Current()->modref_list)
1521                         PROCESS_Current()->modref_list = wm->next;
1522
1523                 /* 
1524                  * The unloaders are also responsible for freeing the modref itself
1525                  * because the loaders were responsible for allocating it.
1526                  */
1527                 switch(wm->type)
1528                 {
1529                 case MODULE32_PE:       PE_UnloadLibrary(wm);           break;
1530                 case MODULE32_ELF:      ELF_UnloadLibrary(wm);          break;
1531                 case MODULE32_ELFDLL:   ELFDLL_UnloadLibrary(wm);       break;
1532                 case MODULE32_BI:       BUILTIN32_UnloadLibrary(wm);    break;
1533
1534                 default:
1535                         ERR_(module)("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1536                 }
1537         }
1538 }
1539
1540 /***********************************************************************
1541  *           FreeLibrary
1542  */
1543 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1544 {
1545     BOOL retv = FALSE;
1546     WINE_MODREF *wm;
1547
1548     EnterCriticalSection( &PROCESS_Current()->crit_section );
1549     PROCESS_Current()->free_lib_count++;
1550
1551     wm = MODULE32_LookupHMODULE( hLibModule );
1552     if ( !wm || !hLibModule )
1553         SetLastError( ERROR_INVALID_HANDLE );
1554     else
1555         retv = MODULE_FreeLibrary( wm );
1556
1557     PROCESS_Current()->free_lib_count--;
1558     LeaveCriticalSection( &PROCESS_Current()->crit_section );
1559
1560     return retv;
1561 }
1562
1563 /***********************************************************************
1564  *           MODULE_DecRefCount
1565  *
1566  * NOTE: Assumes that the process critical section is held!
1567  */
1568 static void MODULE_DecRefCount( WINE_MODREF *wm )
1569 {
1570     int i;
1571
1572     if ( wm->flags & WINE_MODREF_MARKER )
1573         return;
1574
1575     if ( wm->refCount <= 0 )
1576         return;
1577
1578     --wm->refCount;
1579     TRACE_(module)("(%s) refCount: %d\n", wm->modname, wm->refCount );
1580
1581     if ( wm->refCount == 0 )
1582     {
1583         wm->flags |= WINE_MODREF_MARKER;
1584
1585         for ( i = 0; i < wm->nDeps; i++ )
1586             if ( wm->deps[i] )
1587                 MODULE_DecRefCount( wm->deps[i] );
1588
1589         wm->flags &= ~WINE_MODREF_MARKER;
1590     }
1591 }
1592
1593 /***********************************************************************
1594  *           MODULE_FreeLibrary
1595  *
1596  * NOTE: Assumes that the process critical section is held!
1597  */
1598 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1599 {
1600     TRACE_(module)("(%s) - START\n", wm->modname );
1601
1602     /* Recursively decrement reference counts */
1603     MODULE_DecRefCount( wm );
1604
1605     /* Call process detach notifications */
1606     if ( PROCESS_Current()->free_lib_count <= 1 )
1607     {
1608         MODULE_DllProcessDetach( FALSE, NULL );
1609         if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1610             DEBUG_SendUnloadDLLEvent( wm->module );
1611     }
1612
1613     MODULE_FlushModrefs();
1614
1615     TRACE_(module)("(%s) - END\n", wm->modname );
1616
1617     return TRUE;
1618 }
1619
1620
1621 /***********************************************************************
1622  *           FreeLibraryAndExitThread
1623  */
1624 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1625 {
1626     FreeLibrary(hLibModule);
1627     ExitThread(dwExitCode);
1628 }
1629
1630 /***********************************************************************
1631  *           PrivateLoadLibrary       (KERNEL32)
1632  *
1633  * FIXME: rough guesswork, don't know what "Private" means
1634  */
1635 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1636 {
1637         return (HINSTANCE)LoadLibrary16(libname);
1638 }
1639
1640
1641
1642 /***********************************************************************
1643  *           PrivateFreeLibrary       (KERNEL32)
1644  *
1645  * FIXME: rough guesswork, don't know what "Private" means
1646  */
1647 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1648 {
1649         FreeLibrary16((HINSTANCE16)handle);
1650 }
1651
1652
1653 /***********************************************************************
1654  *           WIN32_GetProcAddress16   (KERNEL32.36)
1655  * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1656  */
1657 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1658 {
1659     WORD        ordinal;
1660     FARPROC16   ret;
1661
1662     if (!hModule) {
1663         WARN_(module)("hModule may not be 0!\n");
1664         return (FARPROC16)0;
1665     }
1666     if (HIWORD(hModule))
1667     {
1668         WARN_(module)("hModule is Win32 handle (%08x)\n", hModule );
1669         return (FARPROC16)0;
1670     }
1671     hModule = GetExePtr( hModule );
1672     if (HIWORD(name)) {
1673         ordinal = NE_GetOrdinal( hModule, name );
1674         TRACE_(module)("%04x '%s'\n",
1675                         hModule, name );
1676     } else {
1677         ordinal = LOWORD(name);
1678         TRACE_(module)("%04x %04x\n",
1679                         hModule, ordinal );
1680     }
1681     if (!ordinal) return (FARPROC16)0;
1682     ret = NE_GetEntryPoint( hModule, ordinal );
1683     TRACE_(module)("returning %08x\n",(UINT)ret);
1684     return ret;
1685 }
1686
1687 /***********************************************************************
1688  *           GetProcAddress16   (KERNEL.50)
1689  */
1690 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1691 {
1692     WORD ordinal;
1693     FARPROC16 ret;
1694
1695     if (!hModule) hModule = GetCurrentTask();
1696     hModule = GetExePtr( hModule );
1697
1698     if (HIWORD(name) != 0)
1699     {
1700         ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1701         TRACE_(module)("%04x '%s'\n",
1702                         hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1703     }
1704     else
1705     {
1706         ordinal = LOWORD(name);
1707         TRACE_(module)("%04x %04x\n",
1708                         hModule, ordinal );
1709     }
1710     if (!ordinal) return (FARPROC16)0;
1711
1712     ret = NE_GetEntryPoint( hModule, ordinal );
1713
1714     TRACE_(module)("returning %08x\n", (UINT)ret );
1715     return ret;
1716 }
1717
1718
1719 /***********************************************************************
1720  *           GetProcAddress32                   (KERNEL32.257)
1721  */
1722 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1723 {
1724     return MODULE_GetProcAddress( hModule, function, TRUE );
1725 }
1726
1727 /***********************************************************************
1728  *           WIN16_GetProcAddress32             (KERNEL.453)
1729  */
1730 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1731 {
1732     return MODULE_GetProcAddress( hModule, function, FALSE );
1733 }
1734
1735 /***********************************************************************
1736  *           MODULE_GetProcAddress32            (internal)
1737  */
1738 FARPROC MODULE_GetProcAddress( 
1739         HMODULE hModule,        /* [in] current module handle */
1740         LPCSTR function,        /* [in] function to be looked up */
1741         BOOL snoop )
1742 {
1743     WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1744     FARPROC     retproc;
1745
1746     if (HIWORD(function))
1747         TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1748     else
1749         TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1750     if (!wm) {
1751         SetLastError(ERROR_INVALID_HANDLE);
1752         return (FARPROC)0;
1753     }
1754     switch (wm->type)
1755     {
1756     case MODULE32_PE:
1757         retproc = PE_FindExportedFunction( wm, function, snoop );
1758         if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1759         return retproc;
1760     case MODULE32_ELF:
1761         retproc = ELF_FindExportedFunction( wm, function);
1762         if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1763         return retproc;
1764     default:
1765         ERR_(module)("wine_modref type %d not handled.\n",wm->type);
1766         SetLastError(ERROR_INVALID_HANDLE);
1767         return (FARPROC)0;
1768     }
1769 }
1770
1771
1772 /***********************************************************************
1773  *           RtlImageNtHeaders   (NTDLL)
1774  */
1775 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1776 {
1777     /* basically:
1778      * return  hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew); 
1779      * but we could get HMODULE16 or the like (think builtin modules)
1780      */
1781
1782     WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1783     if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1784     return PE_HEADER(wm->module);
1785 }
1786
1787
1788 /***************************************************************************
1789  *              HasGPHandler                    (KERNEL.338)
1790  */
1791
1792 #include "pshpack1.h"
1793 typedef struct _GPHANDLERDEF
1794 {
1795     WORD selector;
1796     WORD rangeStart;
1797     WORD rangeEnd;
1798     WORD handler;
1799 } GPHANDLERDEF;
1800 #include "poppack.h"
1801
1802 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1803 {
1804     HMODULE16 hModule;
1805     int gpOrdinal;
1806     SEGPTR gpPtr;
1807     GPHANDLERDEF *gpHandler;
1808    
1809     if (    (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1810          && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1811          && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1812          && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1813          && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1814     {
1815         while (gpHandler->selector)
1816         {
1817             if (    SELECTOROF(address) == gpHandler->selector
1818                  && OFFSETOF(address)   >= gpHandler->rangeStart
1819                  && OFFSETOF(address)   <  gpHandler->rangeEnd  )
1820                 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1821                                               gpHandler->handler );
1822             gpHandler++;
1823         }
1824     }
1825
1826     return 0;
1827 }
1828