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