Removed obsolete INT_Int31Handler.
[wine/multimedia.git] / loader / module.c
blobfcfb75696a32000c438aa7203f4c9ef05be1ede0
1 /*
2 * Modules
4 * Copyright 1995 Alexandre Julliard
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.
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.
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
21 #include "config.h"
22 #include "wine/port.h"
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"
40 #include "wine/debug.h"
41 #include "wine/unicode.h"
42 #include "wine/server.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(module);
45 WINE_DECLARE_DEBUG_CHANNEL(win32);
46 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
48 WINE_MODREF *MODULE_modref_list = NULL;
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 */
54 static CRITICAL_SECTION loader_section = CRITICAL_SECTION_INIT( "loader_section" );
56 /***********************************************************************
57 * wait_input_idle
59 * Wrapper to call WaitForInputIdle USER function
61 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
63 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
65 HMODULE mod = GetModuleHandleA( "user32.dll" );
66 if (mod)
68 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
69 if (ptr) return ptr( process, timeout );
71 return 0;
75 /*************************************************************************
76 * MODULE32_LookupHMODULE
77 * looks for the referenced HMODULE in the current process
78 * NOTE: Assumes that the process critical section is held!
80 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
82 WINE_MODREF *wm;
84 if (!hmod)
85 return exe_modref;
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;
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;
99 /*************************************************************************
100 * MODULE_AllocModRef
102 * Allocate a WINE_MODREF structure and add it to the process list
103 * NOTE: Assumes that the process critical section is held!
105 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
107 WINE_MODREF *wm;
109 DWORD long_len = strlen( filename );
110 DWORD short_len = GetShortPathNameA( filename, NULL, 0 );
112 if ((wm = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
113 sizeof(*wm) + long_len + short_len + 1 )))
115 wm->module = hModule;
116 wm->tlsindex = -1;
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;
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;
128 wm->next = MODULE_modref_list;
129 if (wm->next) wm->next->prev = wm;
130 MODULE_modref_list = wm;
132 if (!(RtlImageNtHeader(hModule)->FileHeader.Characteristics & IMAGE_FILE_DLL))
134 if (!exe_modref) exe_modref = wm;
135 else FIXME( "Trying to load second .EXE file: %s\n", filename );
138 return wm;
141 /*************************************************************************
142 * MODULE_InitDLL
144 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
146 BOOL retv = TRUE;
148 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
149 "THREAD_ATTACH", "THREAD_DETACH" };
150 assert( wm );
152 /* Skip calls for modules loaded with special load flags */
154 if (wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) return TRUE;
156 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
158 /* Call the initialization routine */
159 retv = PE_InitDLL( wm->module, type, lpReserved );
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 );
166 return retv;
169 /*************************************************************************
170 * MODULE_DllProcessAttach
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
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
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
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.)
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.
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*.
198 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
200 BOOL retv = TRUE;
201 int i;
203 RtlEnterCriticalSection( &loader_section );
205 if (!wm)
207 wm = exe_modref;
208 PE_InitTls();
210 assert( wm );
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;
217 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
219 /* Tag current MODREF to prevent recursive loop */
220 wm->flags |= WINE_MODREF_MARKER;
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 );
227 /* Call DLL entry point */
228 if ( retv )
230 retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
231 if ( retv )
232 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
235 /* Re-insert MODREF at head of list */
236 if ( retv && wm->prev )
238 wm->prev->next = wm->next;
239 if ( wm->next ) wm->next->prev = wm->prev;
241 wm->prev = NULL;
242 wm->next = MODULE_modref_list;
243 MODULE_modref_list = wm->next->prev = wm;
246 /* Remove recursion flag */
247 wm->flags &= ~WINE_MODREF_MARKER;
249 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
251 done:
252 RtlLeaveCriticalSection( &loader_section );
253 return retv;
256 /*************************************************************************
257 * MODULE_DllProcessDetach
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.
263 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
265 WINE_MODREF *wm;
267 RtlEnterCriticalSection( &loader_section );
268 if (bForceDetach) process_detaching = 1;
271 for ( wm = MODULE_modref_list; wm; wm = wm->next )
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;
279 /* Call detach notification */
280 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
281 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
283 /* Restart at head of WINE_MODREF list, as entries might have
284 been added and/or removed while performing the call ... */
285 break;
287 } while ( wm );
289 RtlLeaveCriticalSection( &loader_section );
292 /*************************************************************************
293 * MODULE_DllThreadAttach
295 * Send DLL thread attach notifications. These are sent in the
296 * reverse sequence of process detach notification.
299 void MODULE_DllThreadAttach( LPVOID lpReserved )
301 WINE_MODREF *wm;
303 /* don't do any attach calls if process is exiting */
304 if (process_detaching) return;
305 /* FIXME: there is still a race here */
307 RtlEnterCriticalSection( &loader_section );
309 PE_InitTls();
311 for ( wm = MODULE_modref_list; wm; wm = wm->next )
312 if ( !wm->next )
313 break;
315 for ( ; wm; wm = wm->prev )
317 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
318 continue;
319 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
320 continue;
322 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
325 RtlLeaveCriticalSection( &loader_section );
328 /*************************************************************************
329 * MODULE_DllThreadDetach
331 * Send DLL thread detach notifications. These are sent in the
332 * same sequence as process detach notification.
335 void MODULE_DllThreadDetach( LPVOID lpReserved )
337 WINE_MODREF *wm;
339 /* don't do any detach calls if process is exiting */
340 if (process_detaching) return;
341 /* FIXME: there is still a race here */
343 RtlEnterCriticalSection( &loader_section );
345 for ( wm = MODULE_modref_list; wm; wm = wm->next )
347 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
348 continue;
349 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
350 continue;
352 MODULE_InitDLL( wm, DLL_THREAD_DETACH, lpReserved );
355 RtlLeaveCriticalSection( &loader_section );
358 /****************************************************************************
359 * DisableThreadLibraryCalls (KERNEL32.@)
361 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
363 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
365 WINE_MODREF *wm;
366 BOOL retval = TRUE;
368 RtlEnterCriticalSection( &loader_section );
370 wm = MODULE32_LookupHMODULE( hModule );
371 if ( !wm )
372 retval = FALSE;
373 else
374 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
376 RtlLeaveCriticalSection( &loader_section );
378 return retval;
382 /***********************************************************************
383 * MODULE_CreateDummyModule
385 * Create a dummy NE module for Win32 or Winelib.
387 HMODULE16 MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
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;
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;
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 */
418 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
419 if (!hModule) return (HMODULE16)11; /* invalid exe */
421 FarSetOwner16( hModule, hModule );
422 pModule = (NE_MODULE *)GlobalLock16( hModule );
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;
442 /* Set version and flags */
443 if (module32)
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;
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 );
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++;
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;
478 /* All tables zero terminated */
479 pModule->res_table = pModule->import_table = pModule->entry_table =
480 (int)pStr - (int)pModule;
482 NE_RegisterModule( pModule );
483 return hModule;
487 /**********************************************************************
488 * MODULE_FindModule
490 * Find a (loaded) win32 module depending on path
492 * RETURNS
493 * the module handle if found
494 * 0 if not
496 WINE_MODREF *MODULE_FindModule(
497 LPCSTR path /* [in] pathname of module/library to be found */
499 WINE_MODREF *wm;
500 char dllname[260], *p;
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" );
507 for ( wm = MODULE_modref_list; wm; wm = wm->next )
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;
519 return wm;
523 /* Check whether a file is an OS/2 or a very old Windows executable
524 * by testing on import of KERNEL.
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...
529 static enum binary_type MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz,
530 const IMAGE_OS2_HEADER *ne)
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;
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;
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;
553 for (i=0; i < ne->ne_cmod; i++)
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;
565 broken:
566 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
568 good:
569 HeapFree( GetProcessHeap(), 0, modtab);
570 HeapFree( GetProcessHeap(), 0, nametab);
571 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
572 return ret;
575 /***********************************************************************
576 * MODULE_GetBinaryType
578 enum binary_type MODULE_GetBinaryType( HANDLE hfile )
580 union
582 struct
584 unsigned char magic[4];
585 unsigned char ignored[12];
586 unsigned short type;
587 } elf;
588 IMAGE_DOS_HEADER mz;
589 } header;
591 char magic[4];
592 DWORD len;
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;
600 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
602 /* FIXME: we don't bother to check byte order, architecture, etc. */
603 switch(header.elf.type)
605 case 2: return BINARY_UNIX_EXE;
606 case 3: return BINARY_UNIX_LIB;
608 return BINARY_UNKNOWN;
611 /* Not ELF, try DOS */
613 if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
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.
622 /* But before we do we will make sure that header
623 * structure encompasses the "Offset to extended header"
624 * field.
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;
637 /* Reading the magic field succeeded so
638 * we will try to determine what type it is.
640 if (!memcmp( magic, "PE\0\0", 4 ))
642 IMAGE_FILE_HEADER FileHeader;
644 if (ReadFile( hfile, &FileHeader, sizeof(FileHeader), &len, NULL ) && len == sizeof(FileHeader))
646 if (FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
647 return BINARY_PE_EXE;
649 return BINARY_DOS;
652 if (!memcmp( magic, "NE", 2 ))
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.
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) )
664 switch ( ne.ne_exetyp )
666 case 2: return BINARY_WIN16;
667 case 5: return BINARY_DOS;
668 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ne);
671 /* Couldn't read header, so abort. */
672 return BINARY_DOS;
675 /* Unknown extended header, but this file is nonetheless DOS-executable. */
676 return BINARY_DOS;
679 return BINARY_UNKNOWN;
682 /***********************************************************************
683 * GetBinaryTypeA [KERNEL32.@]
684 * GetBinaryType [KERNEL32.@]
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.
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
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.
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.
710 * Note that .COM and .PIF files are only recognized by their
711 * file name extension; but Windows does it the same way ...
713 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
715 BOOL ret = FALSE;
716 HANDLE hfile;
717 char *ptr;
719 TRACE_(win32)("%s\n", lpApplicationName );
721 /* Sanity check.
723 if ( lpApplicationName == NULL || lpBinaryType == NULL )
724 return FALSE;
726 /* Open the file indicated by lpApplicationName for reading.
728 hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
729 NULL, OPEN_EXISTING, 0, 0 );
730 if ( hfile == INVALID_HANDLE_VALUE )
731 return FALSE;
733 /* Check binary type
735 switch(MODULE_GetBinaryType( hfile ))
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" ))
743 *lpBinaryType = SCS_DOS_BINARY;
744 ret = TRUE;
746 else if (!FILE_strcasecmp( ptr, ".PIF" ))
748 *lpBinaryType = SCS_PIF_BINARY;
749 ret = TRUE;
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;
775 CloseHandle( hfile );
776 return ret;
779 /***********************************************************************
780 * GetBinaryTypeW [KERNEL32.@]
782 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
784 BOOL ret = FALSE;
785 LPSTR strNew = NULL;
787 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
789 /* Sanity check.
791 if ( lpApplicationName == NULL || lpBinaryType == NULL )
792 return FALSE;
794 /* Convert the wide string to a ascii string.
796 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
798 if ( strNew != NULL )
800 ret = GetBinaryTypeA( strNew, lpBinaryType );
802 /* Free the allocated string.
804 HeapFree( GetProcessHeap(), 0, strNew );
807 return ret;
811 /***********************************************************************
812 * WinExec (KERNEL.166)
814 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
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];
823 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
825 name_beg = lpCmdLine+1;
826 p = strchr ( lpCmdLine+1, '"' );
827 if (p)
829 name_end = p;
830 args = strchr ( p, ' ' );
832 else /* yes, even valid with trailing '"' missing */
833 name_end = lpCmdLine+strlen(lpCmdLine);
835 else
837 name_beg = lpCmdLine;
838 args = strchr( lpCmdLine, ' ' );
839 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
842 if ((name_beg == lpCmdLine) && (!args))
843 { /* just use the original cmdline string as file name */
844 name = (LPSTR)lpCmdLine;
846 else
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';
854 if (args)
856 args++;
857 arglen = strlen(args);
858 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
859 cmdline[0] = (BYTE)arglen;
860 strcpy( cmdline + 1, args );
862 else
864 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
865 cmdline[0] = cmdline[1] = 0;
868 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
870 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
872 LOADPARAMS16 params;
873 WORD showCmd[2];
874 showCmd[0] = 2;
875 showCmd[1] = nCmdShow;
877 params.hEnvironment = 0;
878 params.cmdLine = MapLS( cmdline );
879 params.showCmd = MapLS( showCmd );
880 params.reserved = 0;
882 ret = LoadModule16( buffer, &params );
883 UnMapLS( params.cmdLine );
884 UnMapLS( params.showCmd );
886 else ret = GetLastError();
888 HeapFree( GetProcessHeap(), 0, cmdline );
889 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
891 if (ret == 21) /* 32-bit module */
893 DWORD count;
894 ReleaseThunkLock( &count );
895 ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
896 RestoreThunkLock( count );
898 return ret;
901 /***********************************************************************
902 * WinExec (KERNEL32.@)
904 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
906 PROCESS_INFORMATION info;
907 STARTUPINFOA startup;
908 char *cmdline;
909 UINT ret;
911 memset( &startup, 0, sizeof(startup) );
912 startup.cb = sizeof(startup);
913 startup.dwFlags = STARTF_USESHOWWINDOW;
914 startup.wShowWindow = nCmdShow;
916 /* cmdline needs to be writeable for CreateProcess */
917 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
918 strcpy( cmdline, lpCmdLine );
920 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
921 0, NULL, NULL, &startup, &info ))
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 );
931 else if ((ret = GetLastError()) >= 32)
933 FIXME("Strange error set by CreateProcess: %d\n", ret );
934 ret = 11;
936 HeapFree( GetProcessHeap(), 0, cmdline );
937 return ret;
940 /**********************************************************************
941 * LoadModule (KERNEL32.@)
943 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
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;
953 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
955 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
956 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
957 return (HINSTANCE)GetLastError();
959 len = (BYTE)params->lpCmdLine[0];
960 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
961 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
963 strcpy( cmdline, filename );
964 p = cmdline + strlen(cmdline);
965 *p++ = ' ';
966 memcpy( p, params->lpCmdLine + 1, len );
967 p[len] = 0;
969 memset( &startup, 0, sizeof(startup) );
970 startup.cb = sizeof(startup);
971 if (params->lpCmdShow)
973 startup.dwFlags = STARTF_USESHOWWINDOW;
974 startup.wShowWindow = params->lpCmdShow[1];
977 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
978 params->lpEnvAddress, NULL, &startup, &info ))
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 );
988 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
990 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
991 hInstance = (HINSTANCE)11;
994 HeapFree( GetProcessHeap(), 0, cmdline );
995 return hInstance;
999 /***********************************************************************
1000 * GetModuleHandleA (KERNEL32.@)
1001 * GetModuleHandle32 (KERNEL.488)
1003 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1005 WINE_MODREF *wm;
1007 if ( module == NULL )
1008 wm = exe_modref;
1009 else
1010 wm = MODULE_FindModule( module );
1012 return wm? wm->module : 0;
1015 /***********************************************************************
1016 * GetModuleHandleW (KERNEL32.@)
1018 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1020 HMODULE hModule;
1021 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1022 hModule = GetModuleHandleA( modulea );
1023 HeapFree( GetProcessHeap(), 0, modulea );
1024 return hModule;
1028 /***********************************************************************
1029 * GetModuleFileNameA (KERNEL32.@)
1030 * GetModuleFileName32 (KERNEL.487)
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)
1037 DWORD WINAPI GetModuleFileNameA(
1038 HMODULE hModule, /* [in] module handle (32bit) */
1039 LPSTR lpFileName, /* [out] filenamebuffer */
1040 DWORD size ) /* [in] size of filenamebuffer */
1042 RtlEnterCriticalSection( &loader_section );
1044 lpFileName[0] = 0;
1045 if (!hModule && !(NtCurrentTeb()->tibflags & TEBF_WIN32))
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);
1051 else
1053 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1054 if (wm) lstrcpynA( lpFileName, wm->filename, size );
1057 RtlLeaveCriticalSection( &loader_section );
1058 TRACE("%s\n", lpFileName );
1059 return strlen(lpFileName);
1063 /***********************************************************************
1064 * GetModuleFileNameW (KERNEL32.@)
1066 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
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);
1078 /***********************************************************************
1079 * LoadLibraryExA (KERNEL32.@)
1081 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1083 WINE_MODREF *wm;
1085 if(!libname)
1087 SetLastError(ERROR_INVALID_PARAMETER);
1088 return 0;
1091 if (flags & LOAD_LIBRARY_AS_DATAFILE)
1093 char filename[256];
1094 HMODULE hmod = 0;
1096 /* This method allows searching for the 'native' libraries only */
1097 if (SearchPathA( NULL, libname, ".dll", sizeof(filename), filename, NULL ))
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)
1104 HANDLE mapping;
1105 switch (MODULE_GetBinaryType( hFile ))
1107 case BINARY_PE_EXE:
1108 case BINARY_PE_DLL:
1109 mapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1110 if (mapping)
1112 hmod = (HMODULE)MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
1113 CloseHandle( mapping );
1115 break;
1116 default:
1117 break;
1119 CloseHandle( hFile );
1121 if (hmod) return (HMODULE)((ULONG_PTR)hmod + 1);
1123 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1124 /* Fallback to normal behaviour */
1127 RtlEnterCriticalSection( &loader_section );
1129 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1130 if ( wm )
1132 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1134 WARN_(module)("Attach failed for module '%s'.\n", libname);
1135 MODULE_FreeLibrary(wm);
1136 SetLastError(ERROR_DLL_INIT_FAILED);
1137 wm = NULL;
1141 RtlLeaveCriticalSection( &loader_section );
1142 return wm ? wm->module : 0;
1145 /***********************************************************************
1146 * allocate_lib_dir
1148 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
1149 * portion of the provided name and put the name in it.
1152 static LPCSTR allocate_lib_dir(LPCSTR libname)
1154 LPCSTR p, pmax;
1155 LPSTR result;
1156 int length;
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;
1163 length = pmax - libname;
1165 result = HeapAlloc (GetProcessHeap(), 0, length+1);
1167 if (result)
1169 strncpy (result, libname, length);
1170 result [length] = '\0';
1173 return result;
1176 /***********************************************************************
1177 * MODULE_LoadLibraryExA (internal)
1179 * Load a PE style module according to the load order.
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.
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
1197 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HANDLE hfile, DWORD flags )
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 */
1209 if ( !libname ) return NULL;
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 */
1215 RtlEnterCriticalSection( &loader_section );
1217 if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
1219 if (!(libdir = allocate_lib_dir(libname))) goto error;
1220 allocated_libdir = TRUE;
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);
1228 /* build the modules filename */
1229 if (!found)
1231 if (!MODULE_GetBuiltinPath( libname, ".dll", filename, MAX_PATH )) goto error;
1234 /* Check for already loaded module */
1235 if (!(pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
1237 LPSTR fn = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1238 if (fn)
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)
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 );
1255 if (pwm)
1257 pwm->refCount++;
1259 if ((pwm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
1260 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1262 pwm->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
1263 PE_fixup_imports( pwm );
1265 TRACE("Already loaded module '%s' at 0x%08x, count=%d\n", filename, pwm->module, pwm->refCount);
1266 if (allocated_libdir)
1268 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1269 libdir = NULL;
1271 RtlLeaveCriticalSection( &loader_section );
1272 HeapFree ( GetProcessHeap(), 0, filename );
1273 return pwm;
1276 MODULE_GetLoadOrder( loadorder, filename, TRUE);
1278 for(i = 0; i < LOADORDER_NTYPES; i++)
1280 if (loadorder[i] == LOADORDER_INVALID) break;
1281 SetLastError( ERROR_FILE_NOT_FOUND );
1283 switch(loadorder[i])
1285 case LOADORDER_DLL:
1286 TRACE("Trying native dll '%s'\n", filename);
1287 pwm = PE_LoadLibraryExA(filename, flags);
1288 filetype = "native";
1289 break;
1291 case LOADORDER_SO:
1292 TRACE("Trying so-library '%s'\n", filename);
1293 pwm = ELF_LoadLibraryExA(filename, flags);
1294 filetype = "so";
1295 break;
1297 case LOADORDER_BI:
1298 TRACE("Trying built-in '%s'\n", filename);
1299 pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1300 filetype = "builtin";
1301 break;
1303 default:
1304 pwm = NULL;
1305 break;
1308 if(pwm)
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;
1318 if (allocated_libdir)
1320 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1321 libdir = NULL;
1323 RtlLeaveCriticalSection( &loader_section );
1324 SetLastError( err ); /* restore last error */
1325 HeapFree ( GetProcessHeap(), 0, filename );
1326 return pwm;
1329 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1331 WARN("Loading of %s DLL %s failed (error %ld).\n",
1332 filetype, filename, GetLastError());
1333 break;
1337 error:
1338 if (allocated_libdir)
1340 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1341 libdir = NULL;
1343 RtlLeaveCriticalSection( &loader_section );
1344 WARN("Failed to load module '%s'; error=%ld\n", filename, GetLastError());
1345 HeapFree ( GetProcessHeap(), 0, filename );
1346 return NULL;
1349 /***********************************************************************
1350 * LoadLibraryA (KERNEL32.@)
1352 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1353 return LoadLibraryExA(libname,0,0);
1356 /***********************************************************************
1357 * LoadLibraryW (KERNEL32.@)
1359 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1361 return LoadLibraryExW(libnameW,0,0);
1364 /***********************************************************************
1365 * LoadLibrary32 (KERNEL.452)
1366 * LoadSystemLibrary32 (KERNEL.482)
1368 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1370 HMODULE hModule;
1371 DWORD count;
1373 ReleaseThunkLock( &count );
1374 hModule = LoadLibraryA( libname );
1375 RestoreThunkLock( count );
1376 return hModule;
1379 /***********************************************************************
1380 * LoadLibraryExW (KERNEL32.@)
1382 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1384 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1385 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1387 HeapFree( GetProcessHeap(), 0, libnameA );
1388 return ret;
1391 /***********************************************************************
1392 * MODULE_FlushModrefs
1394 * NOTE: Assumes that the process critical section is held!
1396 * Remove all unused modrefs and call the internal unloading routines
1397 * for the library type.
1399 static void MODULE_FlushModrefs(void)
1401 WINE_MODREF *wm, *next;
1403 for(wm = MODULE_modref_list; wm; wm = next)
1405 next = wm->next;
1407 if(wm->refCount)
1408 continue;
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;
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" );
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 );
1431 /***********************************************************************
1432 * FreeLibrary (KERNEL32.@)
1433 * FreeLibrary32 (KERNEL.486)
1435 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1437 BOOL retv = FALSE;
1438 WINE_MODREF *wm;
1440 if (!hLibModule)
1442 SetLastError( ERROR_INVALID_HANDLE );
1443 return FALSE;
1446 if ((ULONG_PTR)hLibModule & 1)
1448 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1449 char *ptr = (char *)hLibModule - 1;
1450 UnmapViewOfFile( ptr );
1451 return TRUE;
1454 RtlEnterCriticalSection( &loader_section );
1456 /* if we're stopping the whole process (and forcing the removal of all
1457 * DLLs) the library will be freed anyway
1459 if (process_detaching) retv = TRUE;
1460 else
1462 free_lib_count++;
1463 if ((wm = MODULE32_LookupHMODULE( hLibModule ))) retv = MODULE_FreeLibrary( wm );
1464 free_lib_count--;
1467 RtlLeaveCriticalSection( &loader_section );
1469 return retv;
1472 /***********************************************************************
1473 * MODULE_DecRefCount
1475 * NOTE: Assumes that the process critical section is held!
1477 static void MODULE_DecRefCount( WINE_MODREF *wm )
1479 int i;
1481 if ( wm->flags & WINE_MODREF_MARKER )
1482 return;
1484 if ( wm->refCount <= 0 )
1485 return;
1487 --wm->refCount;
1488 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1490 if ( wm->refCount == 0 )
1492 wm->flags |= WINE_MODREF_MARKER;
1494 for ( i = 0; i < wm->nDeps; i++ )
1495 if ( wm->deps[i] )
1496 MODULE_DecRefCount( wm->deps[i] );
1498 wm->flags &= ~WINE_MODREF_MARKER;
1502 /***********************************************************************
1503 * MODULE_FreeLibrary
1505 * NOTE: Assumes that the process critical section is held!
1507 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1509 TRACE("(%s) - START\n", wm->modname );
1511 /* Recursively decrement reference counts */
1512 MODULE_DecRefCount( wm );
1514 /* Call process detach notifications */
1515 if ( free_lib_count <= 1 )
1517 MODULE_DllProcessDetach( FALSE, NULL );
1518 SERVER_START_REQ( unload_dll )
1520 req->base = (void *)wm->module;
1521 wine_server_call( req );
1523 SERVER_END_REQ;
1524 MODULE_FlushModrefs();
1527 TRACE("END\n");
1529 return TRUE;
1533 /***********************************************************************
1534 * FreeLibraryAndExitThread (KERNEL32.@)
1536 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1538 FreeLibrary(hLibModule);
1539 ExitThread(dwExitCode);
1542 /***********************************************************************
1543 * PrivateLoadLibrary (KERNEL32.@)
1545 * FIXME: rough guesswork, don't know what "Private" means
1547 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
1549 return LoadLibrary16(libname);
1554 /***********************************************************************
1555 * PrivateFreeLibrary (KERNEL32.@)
1557 * FIXME: rough guesswork, don't know what "Private" means
1559 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
1561 FreeLibrary16(handle);
1565 /***********************************************************************
1566 * GetProcAddress16 (KERNEL32.37)
1567 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1569 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1571 if (!hModule) {
1572 WARN("hModule may not be 0!\n");
1573 return (FARPROC16)0;
1575 if (HIWORD(hModule))
1577 WARN("hModule is Win32 handle (%08x)\n", hModule );
1578 return (FARPROC16)0;
1580 return GetProcAddress16( LOWORD(hModule), name );
1583 /***********************************************************************
1584 * GetProcAddress (KERNEL.50)
1586 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1588 WORD ordinal;
1589 FARPROC16 ret;
1591 if (!hModule) hModule = GetCurrentTask();
1592 hModule = GetExePtr( hModule );
1594 if (HIWORD(name) != 0)
1596 ordinal = NE_GetOrdinal( hModule, name );
1597 TRACE("%04x '%s'\n", hModule, name );
1599 else
1601 ordinal = LOWORD(name);
1602 TRACE("%04x %04x\n", hModule, ordinal );
1604 if (!ordinal) return (FARPROC16)0;
1606 ret = NE_GetEntryPoint( hModule, ordinal );
1608 TRACE("returning %08x\n", (UINT)ret );
1609 return ret;
1613 /***********************************************************************
1614 * GetProcAddress (KERNEL32.@)
1616 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1618 return MODULE_GetProcAddress( hModule, function, -1, TRUE );
1621 /***********************************************************************
1622 * GetProcAddress32 (KERNEL.453)
1624 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1626 return MODULE_GetProcAddress( hModule, function, -1, FALSE );
1629 /***********************************************************************
1630 * MODULE_GetProcAddress (internal)
1632 FARPROC MODULE_GetProcAddress(
1633 HMODULE hModule, /* [in] current module handle */
1634 LPCSTR function, /* [in] function to be looked up */
1635 int hint,
1636 BOOL snoop )
1638 WINE_MODREF *wm;
1639 FARPROC retproc = 0;
1641 if (HIWORD(function))
1642 TRACE_(win32)("(%08lx,%s (%d))\n",(DWORD)hModule,function,hint);
1643 else
1644 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1646 RtlEnterCriticalSection( &loader_section );
1647 if ((wm = MODULE32_LookupHMODULE( hModule )))
1649 retproc = wm->find_export( wm, function, hint, snoop );
1650 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1652 RtlLeaveCriticalSection( &loader_section );
1653 return retproc;
1657 /***************************************************************************
1658 * HasGPHandler (KERNEL.338)
1661 #include "pshpack1.h"
1662 typedef struct _GPHANDLERDEF
1664 WORD selector;
1665 WORD rangeStart;
1666 WORD rangeEnd;
1667 WORD handler;
1668 } GPHANDLERDEF;
1669 #include "poppack.h"
1671 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1673 HMODULE16 hModule;
1674 int gpOrdinal;
1675 SEGPTR gpPtr;
1676 GPHANDLERDEF *gpHandler;
1678 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1679 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1680 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1681 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1682 && (gpHandler = MapSL( gpPtr )) != NULL )
1684 while (gpHandler->selector)
1686 if ( SELECTOROF(address) == gpHandler->selector
1687 && OFFSETOF(address) >= gpHandler->rangeStart
1688 && OFFSETOF(address) < gpHandler->rangeEnd )
1689 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1690 gpHandler++;
1694 return 0;