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