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